Skip to content

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

feat(vmm): add a replaceable memory view and a hotplug window (#2900)

ltstriker1405db27587e
diff --git a/Cargo.lock b/Cargo.lock
index 148da9b2c..cf71f7bff 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7084,6 +7084,7 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b55e753c7725603745cb32b2287ef7ef3da05c03c7702cda3fa8abe25ae0465"
dependencies = [
+ "arc-swap",
"libc",
"thiserror 2.0.18",
"winapi",
diff --git a/src/vmm/Cargo.toml b/src/vmm/Cargo.toml
index 9cca70046..a7c318240 100644
--- a/src/vmm/Cargo.toml
+++ b/src/vmm/Cargo.toml
@@ -16,7 +16,7 @@ imago = { version = "0.2.6", default-features = false, features = ["sync"] }
mio = { version = "1.2.0", default-features = false, features = ["os-poll", "net"] }
tracing = "0.1"
virtio-queue = "0.18.0"
-vm-memory = { version = "0.18.0", features = ["backend-mmap"] }
+vm-memory = { version = "0.18.0", features = ["backend-atomic", "backend-mmap"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
diff --git a/src/vmm/README.md b/src/vmm/README.md
index 09b6f1ac4..a3e3126e1 100644
--- a/src/vmm/README.md
+++ b/src/vmm/README.md
@@ -32,11 +32,12 @@ boxlite-vmm
| `config` | `VmConfig`: CPU, RAM, kernel and initramfs, disks, optional filesystem/vsock/network, and virtio console; 1..=64 vCPUs, nonzero `u32` MiB of RAM whose layout must pass host and boot address checks, a printable-ASCII command line under 2048 bytes, and at most 8 disks |
| `error` | VMM errors that keep the hypervisor's cause chain, including a virtio device that cannot continue |
| `memory` | `GuestRam`: owned guest RAM, the RAM layout, and the registration lifetime rules |
+| `hotplug` | `HotplugMemory` places a window after boot RAM, plugs 2 MiB blocks and maps 128 MiB slots |
| `cpu_features` | x86_64 guest-memory capability preflight, CPUID for each vCPU, and the boot MSRs |
| `vcpu` | x86_64 vCPU workers: create and configure each vCPU, hold them at a start gate, run the guest and dispatch its exits until the VM ends |
| `chipset` | `ChipsetBuilder`, the one registry of ranges and interrupt lines, and `Chipset`, the read-only machine it builds |
| `bus` | `Bus`, `BusRange` and `BusDevice`, and `Buses::dispatch`, which serves the MMIO and port exits of a vCPU |
-| `virtio` | The virtio common infrastructure: the synchronous device contract (`VirtioDevice`, `DeviceSpec`, `DeviceEvent`, `ActivationContext`, `EventRegistrar`, `Waker`, `WorkerControl`), the `VirtQueues` facade (dense preparation and validation, EVENT_IDX, exactly-once deferred completion, notification drain, the stored guest-memory Arc and negotiated indirect flag, and `save`/`restore` stubs that report snapshots unsupported until M8), the 4 KiB virtio-mmio transport (register file, feature negotiation, queue configuration and activation, Status=0 reset, post-activation queue-write rejection), `mmio::add_device`, which attaches any device through that transport, the MMIO interrupt handle, the default snapshot methods, and the virtio workers (`VirtioWorkers` over a `WorkerRuntime`; `SharedRuntime` runs every device's events on one thread) |
+| `virtio` | The virtio common infrastructure: the synchronous device contract (`VirtioDevice`, `DeviceSpec`, `DeviceEvent`, `ActivationContext`, `EventRegistrar`, `Waker`, `WorkerControl`), the `VirtQueues` facade (dense preparation and validation, EVENT_IDX, exactly-once deferred completion, notification drain, the stored guest-memory view and negotiated indirect flag, and `save`/`restore` stubs that report snapshots unsupported until M8), the 4 KiB virtio-mmio transport (register file, feature negotiation, queue configuration and activation, Status=0 reset, post-activation queue-write rejection), `mmio::add_device`, which attaches any device through that transport, the MMIO interrupt handle, the default snapshot methods, and the virtio workers (`VirtioWorkers` over a `WorkerRuntime`; `SharedRuntime` runs every device's events on one thread) |
| `irq` | `IrqChip`, the host interrupt controller as devices see it, and `IrqLine`, one device line; HVF and KVM provide the controller, WHP (M10) only local APICs |
| `devices` | `devices::add_all`, the one composition helper (add a device type as one `add_slot_device` line), the console queue, internal virtio-net device, output-only virtio console device, and on x86_64 the 8250 UART at COM1 and the i8042 reset, with `add_legacy_devices` |
| `devices::balloon` | Reporting-only `VirtioBalloon`: configuration, negotiation, whole-chain prevalidation and a `ReclaimPolicy` chosen when the device is constructed; `devices::add_all` composes it after the disks, so it never renumbers them |
@@ -113,11 +114,22 @@ MMIO hole leaves a maximum x86 RAM configuration of
**64 TiB - 1 GiB (67,107,840 MiB)** before truncation.
`GuestRam` allocates the layout as zero-filled anonymous memory through
-vm-memory and registers it with the host VM. Three rules keep the backend's
+vm-memory and registers it with the host VM. These rules keep the backend's
`map_memory` contract:
-- Host-side users clone the shared `Arc<GuestMemoryMmap>` and access guest
- memory through vm-memory's volatile API, never through Rust references.
+- Host-side users clone the shared `GuestMemoryView`, vm-memory's
+ `GuestMemoryAtomic` over the region map, and access guest memory through
+ vm-memory's volatile API, never through Rust references.
+- A user loads one snapshot per unit of work and drops it before returning;
+ no device keeps one across events.
+- `VirtQueues::drain` and `complete` load one per call. Block, fs, console and
+ balloon load one per device callback, such as `on_event`, `activate` or
+ `quiesce`.
+- Net loads one per guest buffer read or write. Vsock loads one per TX intake
+ pass and one per RX buffer write.
+- The next event therefore sees a map that gained or lost a region. A
+ descriptor naming a removed region fails translation like any other invalid
+ address. A snapshot still held keeps its regions mapped until it drops.
- `map` registers logical RAM regions from low to high. KVM slices each region
into slots of at most `2^31−1` host pages and rolls back installed slices if
a registration fails. `GuestRam` also rolls back attempted regions, including
@@ -127,6 +139,24 @@ vm-memory and registers it with the host VM. Three rules keep the backend's
created host VM with exclusive ownership is closed before `run` starts.
If registrations may still exist, `GuestRam` retains the backing.
+A map replaced while a worker event runs reaches the next event, not the
+current one:
+
+```mermaid
+sequenceDiagram
+ participant W as Virtio worker
+ participant V as GuestMemoryView
+ participant H as Map owner
+ W->>V: memory() at event start
+ V-->>W: snapshot S1 (regions A, B)
+ H->>V: replace with S2 (region A only)
+ Note over W: event still reads B through S1
+ W->>W: drop S1 at event end
+ Note over V: B stays mapped until its last reference drops
+ W->>V: memory() at next event start
+ V-->>W: snapshot S2: a descriptor into B fails translation
+```
+
`Vm::new` validates the configuration, then opens and checks the KVM system fd
and reads supported CPUID once. It preflights the RAM addresses and boot leaf
before spawning the console worker or allocating RAM. The VM builder
@@ -142,6 +172,39 @@ as unit-test modules, which
keeps them outside the counted sources and the coverage denominator; `config`
and `error` keep inline test modules.
+`GuestRam` registers and releases only the boot regions it allocated. The
+shared view can gain hotplug regions, so `GuestRam` keeps its own boot map
+instead of reading registrations back from the view.
+
+## Hotplug memory
+
+`HotplugMemory` owns the window that grows and shrinks guest RAM at runtime.
+Design: [#2882](https://github.com/boxlite-ai/boxlite/issues/2882).
+
+- The window starts at or above 4 GiB after all boot RAM. The base is rounded
+ up to the bundled Linux guest's memory block size, and capacity must be a
+ positive multiple of that size. A guest with 6 GiB of boot RAM and 1 GiB of
+ hotplug capacity has a window at `[7 GiB, 8 GiB)`.
+- The planner checks the end against KVM's GPA limit and Linux's pluggable
+ address limit. It checks capacity against KVM's slot budget after boot RAM.
+ E820 and the startup identity map describe the backed boot ranges.
+- The guest plugs 2 MiB blocks. A 128 MiB slot gets its own private anonymous
+ mapping and KVM registration when its first block is plugged.
+- Unplugging the last block of a slot removes its KVM registration, publishes
+ a view without it, then drops the mapping. A held snapshot keeps the mapping
+ alive until it drops, as the [Guest RAM](#guest-ram) diagram shows.
+- Publishing a removal cannot fail: a poisoned view lock is still used, and a
+ region already missing from the view counts as removed.
+- Unplugging blocks discards them with `MADV_DONTNEED` while other blocks in
+ that slot remain plugged. An emptied slot retained after a failed unmap
+ retains its contents.
+- A failed slot map unregisters the slots that plug added and leaves every
+ 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.
+
## Kernel loading
On Linux x86_64, `boot::elf::load_elf(ram, kernel)` delegates ELF parsing and
diff --git a/src/vmm/src/boot/mod.rs b/src/vmm/src/boot/mod.rs
index 9f89537f2..5f1ded345 100644
--- a/src/vmm/src/boot/mod.rs
+++ b/src/vmm/src/boot/mod.rs
@@ -47,7 +47,7 @@ pub(crate) fn prepare(
config: &VmConfig,
leaf: CheckedBootLeaf,
) -> Result<BootSetup> {
- let memory = ram.memory().as_ref();
+ let memory = ram.boot_memory().as_ref();
let ranges: Vec<(GuestAddress, usize)> = ram.ranges().collect();
let load_kernel = |source: io::Error| Error::LoadKernel {
path: config.kernel.clone(),
diff --git a/src/vmm/src/devices/balloon.rs b/src/vmm/src/devices/balloon.rs
index ba639b8c0..c3266aeeb 100644
--- a/src/vmm/src/devices/balloon.rs
+++ b/src/vmm/src/devices/balloon.rs
@@ -118,6 +118,7 @@ impl VirtioDevice for VirtioBalloon {
return Err(DeviceError::NeedsReset("balloon queues"));
}
self.control_count = 0;
+ let snapshot = vm_memory::GuestAddressSpace::memory(&ctx.memory);
for range in ctx.queues.control_ranges() {
let slot = self
.control_ranges
@@ -128,9 +129,8 @@ impl VirtioDevice for VirtioBalloon {
"balloon queue control range overflow",
));
}
- let slice =
- vm_memory::GuestMemoryBackend::get_slice(ctx.memory.as_ref(), range.0, range.1)
- .map_err(|_| DeviceError::NeedsReset("balloon queue control region"))?;
+ let slice = vm_memory::GuestMemoryBackend::get_slice(&*snapshot, range.0, range.1)
+ .map_err(|_| DeviceError::NeedsReset("balloon queue control region"))?;
let host = slice.ptr_guard().as_ptr() as usize;
host.checked_add(range.1).ok_or(DeviceError::NeedsReset(
"balloon queue control host overflow",
@@ -138,6 +138,7 @@ impl VirtioDevice for VirtioBalloon {
*slot = (range.0, range.1, host);
self.control_count += 1;
}
+ drop(snapshot);
self.context = Some(ctx);
Ok(())
}
@@ -170,7 +171,8 @@ impl VirtioDevice for VirtioBalloon {
})?,
2 => {
let controls = &self.control_ranges[..self.control_count];
- let memory = ctx.memory.as_ref();
+ let snapshot = vm_memory::GuestAddressSpace::memory(&ctx.memory);
+ let memory: &GuestMemoryMmap = &snapshot;
let page_size = self.page_size;
let reclaim = self.reclaim;
ctx.queues.drain(2, |chain| {
diff --git a/src/vmm/src/devices/net.rs b/src/vmm/src/devices/net.rs
index 93a60277f..d455eabe9 100644
--- a/src/vmm/src/devices/net.rs
+++ b/src/vmm/src/devices/net.rs
@@ -16,7 +16,7 @@ use std::{
path::PathBuf,
};
use virtio_queue::desc::split::Descriptor;
-use vm_memory::{Bytes, GuestMemory, Permissions};
+use vm_memory::{Bytes, GuestAddressSpace, GuestMemory, Permissions};
const RX: usize = 0;
const TX: usize = 1;
@@ -280,6 +280,7 @@ impl Active {
let end = offset + d.len() as usize;
self.ctx
.memory
+ .memory()
.read_slice(&mut bytes[offset..end], d.addr())
.map_err(|e| fault("read TX buffer", e))?;
offset = end;
@@ -349,6 +350,7 @@ impl Active {
if end > written {
self.ctx
.memory
+ .memory()
.write_slice(&self.rx.bytes[written..end], d.addr())
.map_err(|e| fault("write RX buffer", e))?;
}
diff --git a/src/vmm/src/devices/virtio_console.rs b/src/vmm/src/devices/virtio_console.rs
index ebb39d539..f6b52d8c8 100644
--- a/src/vmm/src/devices/virtio_console.rs
+++ b/src/vmm/src/devices/virtio_console.rs
@@ -70,7 +70,8 @@ impl VirtioConsole {
let mut descriptors = [Descriptor::default(); QUEUE_SIZE];
let mut buffer = [0u8; CHUNK_BYTES];
let writer = &mut self.writer;
- let memory = &ctx.memory;
+ let snapshot = vm_memory::GuestAddressSpace::memory(&ctx.memory);
+ let memory: &GuestMemoryMmap = &snapshot;
// Defer used publication until drain returns: if a later head is
// malformed, complete the earlier heads and resolve their notifications
// anyway. drain's inline Used path loses that decision on an error.
diff --git a/src/vmm/src/hotplug.rs b/src/vmm/src/hotplug.rs
new file mode 100644
index 000000000..f5532f3c9
--- /dev/null
+++ b/src/vmm/src/hotplug.rs
@@ -0,0 +1,347 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+//! Hotplug memory above the boot RAM.
+//!
+//! [`HotplugMemory`] owns a guest-physical window that a virtio-mem driver
+//! plugs and unplugs in [`BLOCK_SIZE`] blocks. The VMM backs and registers it
+//! in [`SLOT_SIZE`] slots: a slot gains its own anonymous mapping and KVM
+//! registration when its first block is plugged, and loses both when its last
+//! block is unplugged and unregistration succeeds. An unplugged block inside a
+//! slot that still contains plugged blocks is
+//! discarded with `MADV_DONTNEED`. The host memory bound is therefore the
+//! mapped slots, not the plugged blocks.
+//!
+//! Every change publishes a new [`GuestMemoryView`], so devices see a slot from
+//! their next snapshot on. Removal runs KVM unregistration, then the view
+//! update, then drops the mapping, which a snapshot still in use keeps alive.
+
+use std::{
+ convert::Infallible,
+ io,
+ ops::Range,
+ ptr::NonNull,
+ sync::{Arc, PoisonError},
+};
+
+use boxlite_hypervisor::{MemoryRegion, Vm};
+use vm_memory::{GuestAddress, GuestAddressSpace, GuestMemoryRegion, GuestRegionMmap};
+
+use crate::memory::{GuestMemoryMmap, GuestMemoryView};
+
+const MIB: u64 = 1 << 20;
+
+/// The virtio-mem device block: the unit the guest plugs and unplugs.
+pub(crate) const BLOCK_SIZE: u64 = 2 * MIB;
+
+/// The unit of host mapping and KVM registration; also the capacity step.
+pub(crate) const SLOT_SIZE: u64 = 128 * MIB;
+
+const BLOCKS_PER_SLOT: usize = (SLOT_SIZE / BLOCK_SIZE) as usize;
+
+/// The lowest window address, immediately above the x86_64 MMIO hole.
+const HOTPLUG_MIN_ADDR: u64 = 1 << 32;
+/// Exclusive pluggable limit of the bundled guest's four-level direct map.
+const GUEST_PLUGGABLE_END: u64 = 1 << 46;
+
+/// An x86_64 virtio-mem window checked against boot RAM, Linux and KVM.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct HotplugWindow {
+ base: u64,
+ slots: usize,
+}
+
+impl HotplugWindow {
+ pub(crate) fn plan(
+ boot_ranges: &[(GuestAddress, usize)],
+ capacity_mib: u32,
+ physical_end: u64,
+ available_slots: usize,
+ ) -> io::Result<Self> {
+ let overflow = || io::Error::new(io::ErrorKind::InvalidInput, "hotplug address overflow");
+ let boot_end = boot_ranges.iter().try_fold(0, |highest, (start, size)| {
+ let end = start.0.checked_add(*size as u64).ok_or_else(overflow)?;
+ Ok::<_, io::Error>(highest.max(end))
+ })?;
+ // The bundled Linux x86_64 guest uses probe_memory_block_size() with
+ // the hypervisor bit set. At 64 GiB it scales up to a divisor of boot_end.
+ let alignment = if boot_end < 1 << 36 {
+ SLOT_SIZE
+ } else {
+ (1u64 << boot_end.trailing_zeros().min(31)).max(SLOT_SIZE)
+ };
+ let size = u64::from(capacity_mib) * MIB;
+ if size == 0 || !size.is_multiple_of(alignment) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ format!(
+ "hotplug capacity must be a positive multiple of {} MiB",
+ alignment / MIB
+ ),
+ ));
+ }
+ let base = boot_end
+ .max(HOTPLUG_MIN_ADDR)
+ .checked_next_multiple_of(alignment)
+ .ok_or_else(overflow)?;
+ let end = base.checked_add(size).ok_or_else(overflow)?;
+ if end > physical_end.min(GUEST_PLUGGABLE_END) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "hotplug window exceeds the guest physical address limit",
+ ));
+ }
+ let slots = (size / SLOT_SIZE) as usize;
+ if slots > available_slots {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "hotplug capacity exceeds the available KVM memory slots",
+ ));
+ }
+ Ok(Self { base, slots })
+ }
+}
+
+/// Whether a block range is plugged, unplugged or both.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum BlockState {
+ Plugged,
+ Unplugged,
+ Mixed,
+}
+
+/// The hotplug window, its mapped slots and its plugged blocks.
+pub(crate) struct HotplugMemory<V: Vm + ?Sized> {
+ vm: Arc<V>,
+ view: GuestMemoryView,
+ base: u64,
+ slots: Vec<Option<Arc<GuestRegionMmap>>>,
+ plugged: Vec<bool>,
+}
+
+impl<V: Vm + ?Sized> HotplugMemory<V> {
+ /// Nothing is mapped or registered in the window until a plug.
+ pub(crate) fn new(vm: Arc<V>, view: GuestMemoryView, window: HotplugWindow) -> Self {
+ Self {
+ vm,
+ view,
+ base: window.base,
+ slots: vec![None; window.slots],
+ plugged: vec![false; window.slots * BLOCKS_PER_SLOT],
+ }
+ }
+
+ /// The first guest address of the window.
+ pub(crate) fn base(&self) -> u64 {
+ self.base
+ }
+
+ /// The window size in bytes.
+ pub(crate) fn size(&self) -> u64 {
+ self.slots.len() as u64 * SLOT_SIZE
+ }
+
+ /// Bytes in plugged blocks.
+ pub(crate) fn plugged_bytes(&self) -> u64 {
+ self.plugged.iter().filter(|&&plugged| plugged).count() as u64 * BLOCK_SIZE
+ }
+
+ /// Bytes in mapped slots: the host memory the guest can reach.
+ pub(crate) fn mapped_bytes(&self) -> u64 {
+ self.slots.iter().flatten().count() as u64 * SLOT_SIZE
+ }
+
+ /// The block indexes of `count` blocks at `addr`, or `None` when the range
+ /// is empty, misaligned or outside the window.
+ pub(crate) fn blocks(&self, addr: u64, count: u16) -> Option<Range<usize>> {
+ let offset = addr.checked_sub(self.base)?;
+ let end = offset.checked_add(u64::from(count) * BLOCK_SIZE)?;
+ if count == 0 || !offset.is_multiple_of(BLOCK_SIZE) || end > self.size() {
+ return None;
+ }
+ Some((offset / BLOCK_SIZE) as usize..(end / BLOCK_SIZE) as usize)
+ }
+
+ /// The state of `blocks`, which [`Self::blocks`] produced.
+ pub(crate) fn state(&self, blocks: Range<usize>) -> BlockState {
+ let plugged = self.plugged[blocks.clone()].iter().filter(|&&p| p).count();
+ match plugged {
+ 0 => BlockState::Unplugged,
+ n if n == blocks.len() => BlockState::Plugged,
+ _ => BlockState::Mixed,
+ }
+ }
+
+ /// Plugs `blocks`, mapping and registering every slot they need. A failure
+ /// unregisters the slots this call added and leaves every block unplugged.
+ pub(crate) fn plug(&mut self, blocks: Range<usize>) -> io::Result<()> {
+ let mut added = Vec::new();
+ for slot in slots_of(&blocks) {
+ if self.slots[slot].is_some() {
+ continue;
+ }
+ match self.map_slot(slot) {
+ Ok(region) => added.push((slot, region)),
+ Err(error) => {
+ for (slot, region) in added.into_iter().rev() {
+ self.release(slot, region);
+ }
+ return Err(error);
+ }
+ }
+ }
+ if !added.is_empty() {
+ let mut regions = added.iter().map(|(_, region)| Arc::clone(region));
+ let published = self.publish(|map| {
+ regions.try_fold(map, |map, region| {
+ map.insert_region(region).map_err(io::Error::other)
+ })
+ });
+ if let Err(error) = published {
+ for (slot, region) in added.into_iter().rev() {
+ self.release(slot, region);
+ }
+ return Err(error);
+ }
+ }
+ for (slot, region) in added {
+ self.slots[slot] = Some(region);
+ }
+ self.plugged[blocks].fill(true);
+ Ok(())
+ }
+
+ /// Unplugs `blocks`. A slot left empty is unregistered, removed from the
+ /// view and dropped; blocks in a slot that stays mapped are discarded.
+ /// A failed unregistration keeps that slot mapped.
+ pub(crate) fn unplug(&mut self, blocks: Range<usize>) -> io::Result<()> {
+ self.plugged[blocks.clone()].fill(false);
+ let mut emptied = Vec::new();
+ let mut result = Ok(());
+ for slot in slots_of(&blocks) {
+ let Some(region) = self.slots[slot].clone() else {
+ continue;
+ };
+ let whole = slot * BLOCKS_PER_SLOT..(slot + 1) * BLOCKS_PER_SLOT;
+ if self.plugged[whole.clone()].iter().any(|&p| p) {
+ let start = blocks.start.max(whole.start);
+ let end = blocks.end.min(whole.end);
+ if let Err(error) = discard(&region, start - whole.start, end - start) {
+ result = Err(error);
+ }
+ } else if let Err(error) = self.vm.unmap_memory(&kvm_region(&region)) {
+ result = Err(io::Error::other(error));
+ } else {
+ emptied.push((slot, region));
+ }
+ }
+ if !emptied.is_empty() {
+ let removed: Vec<_> = emptied.iter().map(|(_, r)| r.start_addr()).collect();
+ // Removal cannot fail: KVM no longer maps these slots, so the view
+ // and the slot records must follow. A region already missing from
+ // the view counts as removed.
+ let Ok(()) = self.publish::<Infallible>(|map| {
+ Ok(removed.iter().fold(map, |map, &start| {
+ map.remove_region(start, SLOT_SIZE)
+ .map(|(map, _)| map)
+ .unwrap_or(map)
+ }))
+ });
+ for (slot, _) in emptied {
+ self.slots[slot] = None;
+ }
+ }
+ result
+ }
+
+ /// Unplugs every block.
+ pub(crate) fn unplug_all(&mut self) -> io::Result<()> {
+ self.unplug(0..self.plugged.len())
+ }
+
+ fn map_slot(&self, slot: usize) -> io::Result<Arc<GuestRegionMmap>> {
+ let addr = GuestAddress(self.base + slot as u64 * SLOT_SIZE);
+ let region = GuestRegionMmap::from_range(addr, SLOT_SIZE as usize, None)
+ .map_err(io::Error::other)?;
+ let region = Arc::new(region);
+ // SAFETY: the mapping is private anonymous memory this owner keeps
+ // alive until the registration is removed; `Drop` leaks it otherwise.
+ // Host access goes through vm-memory's volatile API.
+ unsafe { self.vm.map_memory(&kvm_region(&region)) }.map_err(io::Error::other)?;
+ Ok(region)
+ }
+
+ /// Unregisters a slot that never reached the view; leaks it on failure.
+ fn release(&self, slot: usize, region: Arc<GuestRegionMmap>) {
+ if self.vm.unmap_memory(&kvm_region(&region)).is_err() {
+ tracing::warn!(slot, "leaking a hotplug slot KVM may still map");
+ std::mem::forget(region);
+ }
+ }
+
+ /// Replaces the view with `update` applied to the current map. Only
+ /// `update` can fail.
+ fn publish<E>(
+ &self,
+ update: impl FnOnce(GuestMemoryMmap) -> Result<GuestMemoryMmap, E>,
+ ) -> Result<(), E> {
+ // The lock only orders writers; a writer that panicked left the view
+ // whole, so a poisoned lock is still safe to use.
+ let guard = self.view.lock().unwrap_or_else(PoisonError::into_inner);
+ let current = GuestMemoryMmap::clone(&self.view.memory());
+ guard.replace(update(current)?);
+ Ok(())
+ }
+}
+
+impl<V: Vm + ?Sized> Drop for HotplugMemory<V> {
+ fn drop(&mut self) {
+ for slot in self.slots.iter_mut() {
+ if let Some(region) = slot.take()
+ && self.vm.unmap_memory(&kvm_region(&region)).is_err()
+ {
+ // KVM may still map it; leaking beats freeing guest memory.
+ std::mem::forget(region);
+ }
+ }
+ }
+}
+
+fn slots_of(blocks: &Range<usize>) -> Range<usize> {
+ blocks.start / BLOCKS_PER_SLOT..blocks.end.div_ceil(BLOCKS_PER_SLOT)
+}
+
+fn kvm_region(region: &GuestRegionMmap) -> MemoryRegion {
+ MemoryRegion {
+ guest_addr: region.start_addr().0,
+ // vm-memory rejects a failed mmap, so a region pointer is never null.
+ host_addr: NonNull::new(region.as_ptr()).expect("mmap returned a null mapping"),
+ size: region.len() as usize,
+ }
+}
+
+/// Returns `count` blocks starting at block `first` of `region` to the host.
+fn discard(region: &GuestRegionMmap, first: usize, count: usize) -> io::Result<()> {
+ let offset = first as u64 * BLOCK_SIZE;
+ let len = count as u64 * BLOCK_SIZE;
+ // SAFETY: the range lies inside the private anonymous mapping `region`
+ // owns. The guest unplugged these blocks, so dropping their contents is
+ // the requested effect; a later access faults in zero pages.
+ let result = unsafe {
+ libc::madvise(
+ region.as_ptr().add(offset as usize).cast(),
+ len as usize,
+ libc::MADV_DONTNEED,
+ )
+ };
+ if result != 0 {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(())
+}
+
+// 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/hotplug/mod.rs"]
+mod tests;
diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rs
index d8b7a0219..117cb26bc 100644
--- a/src/vmm/src/lib.rs
+++ b/src/vmm/src/lib.rs
@@ -44,6 +44,14 @@ mod error;
)
)]
mod events;
+#[cfg_attr(
+ not(test),
+ expect(
+ dead_code,
+ reason = "The virtio-mem device that drives hotplug memory comes next."
+ )
+)]
+mod hotplug;
#[cfg_attr(
not(test),
expect(
diff --git a/src/vmm/src/memory.rs b/src/vmm/src/memory.rs
index 85f1e2e31..8b5d6feb8 100644
--- a/src/vmm/src/memory.rs
+++ b/src/vmm/src/memory.rs
@@ -7,8 +7,8 @@
//! hypervisor. It releases the backing once every registration is removed or
//! the VM and its vCPUs are closed. A `GuestRam` dropped while a registration may
//! still exist leaks the backing, so the host VM never references freed memory.
-//! Host-side users of guest memory hold clones of the shared [`Arc`] and go
-//! through vm-memory's volatile access API, never plain references.
+//! Devices hold clones of the shared [`GuestMemoryView`] and load snapshots
+//! for guest access through vm-memory's volatile API.
use std::{io, ptr::NonNull, sync::Arc};
@@ -21,6 +21,14 @@ use crate::error::{Error, Result};
/// (M8) changes this alias rather than every holder.
pub(crate) type GuestMemoryMmap = vm_memory::GuestMemoryMmap<()>;
+/// The replaceable guest memory map host-side users share.
+///
+/// [`GuestAddressSpace::memory`] loads the current snapshot. A caller loads it
+/// once per unit of work, such as one worker event, and drops it before
+/// returning, so a later replacement of the map becomes visible to the next
+/// unit. A held snapshot keeps every region it names mapped until it drops.
+pub(crate) type GuestMemoryView = vm_memory::GuestMemoryAtomic<GuestMemoryMmap>;
+
/// Bytes per MiB.
const MIB: u64 = 1 << 20;
@@ -258,7 +266,10 @@ fn interior_pages(start: usize, len: usize, page_size: usize) -> (usize, usize)
/// Guest RAM owned by the VMM.
#[derive(Debug)]
pub(crate) struct GuestRam {
- memory: Arc<GuestMemoryMmap>,
+ memory: GuestMemoryView,
+ /// The boot RAM map. `GuestRam` registers and releases exactly these
+ /// regions, whatever later views add or remove.
+ boot_memory: Arc<GuestMemoryMmap>,
/// Regions `0..mapped`, in ascending address order, may still have
/// mappings with the host VM.
mapped: usize,
@@ -271,7 +282,7 @@ impl GuestRam {
/// each region: fresh owned MAP_PRIVATE | MAP_ANONYMOUS mappings, without
/// files, raw pointers or hugetlb. Distinct live allocations have disjoint
/// host virtual ranges; this constructor creates no second GPA/HVA view of
- /// one allocation. Arc clones retain the same mapping. Kernel zero-page
+ /// one allocation. Snapshots retain the same mapping. Kernel zero-page
/// sharing or COW does not create another VMM mapping. Reporting rejects
/// other backing kinds instead of extending this ownership contract.
pub(crate) fn new(ranges: &[(GuestAddress, usize)]) -> Result<Self> {
@@ -281,31 +292,38 @@ impl GuestRam {
bytes,
source: io::Error::other(source),
})?;
+ let boot_memory = Arc::new(memory);
Ok(Self {
- memory: Arc::new(memory),
+ memory: GuestMemoryView::from(Arc::clone(&boot_memory)),
+ boot_memory,
mapped: 0,
})
}
- /// The shared guest memory every host-side user clones.
- pub(crate) fn memory(&self) -> &Arc<GuestMemoryMmap> {
+ /// The shared guest memory view every host-side user clones.
+ pub(crate) fn memory(&self) -> &GuestMemoryView {
&self.memory
}
+ /// The map used by the boot loader and host VM registrations.
+ pub(crate) fn boot_memory(&self) -> &Arc<GuestMemoryMmap> {
+ &self.boot_memory
+ }
+
/// The guest RAM ranges this instance backs, in ascending guest order.
#[cfg_attr(
not(all(target_os = "linux", target_arch = "x86_64")),
expect(dead_code, reason = "Only Linux x86_64 prepares boot data yet.")
)]
pub(crate) fn ranges(&self) -> impl Iterator<Item = (GuestAddress, usize)> + '_ {
- self.memory
+ self.boot_memory()
.iter()
.map(|region| (region.start_addr(), region.len() as usize))
}
/// Each RAM range as the hypervisor registers it, in ascending guest order.
pub(crate) fn regions(&self) -> impl Iterator<Item = MemoryRegion> + '_ {
- self.memory.iter().map(|region| MemoryRegion {
+ self.boot_memory().iter().map(|region| MemoryRegion {
guest_addr: region.start_addr().0,
// vm-memory rejects a failed mmap, so a region pointer is never null.
host_addr: NonNull::new(region.as_ptr()).expect("mmap returned a null mapping"),
@@ -375,7 +393,7 @@ impl Drop for GuestRam {
if self.mapped > 0 {
// The host VM may still reference the range; leaking beats freeing
// memory the guest can still write.
- std::mem::forget(Arc::clone(&self.memory));
+ std::mem::forget(Arc::clone(&self.boot_memory));
}
}
}
diff --git a/src/vmm/src/virtio/blk/device.rs b/src/vmm/src/virtio/blk/device.rs
index 63fb10fbd..29eab7295 100644
--- a/src/vmm/src/virtio/blk/device.rs
+++ b/src/vmm/src/virtio/blk/device.rs
@@ -131,7 +131,8 @@ impl VirtioBlk {
.as_mut()
.ok_or(DeviceError::NeedsReset("block device is not active"))?;
let ActiveState { ctx, inflight, .. } = active;
- let memory = ctx.memory.as_ref();
+ let snapshot = vm_memory::GuestAddressSpace::memory(&ctx.memory);
+ let memory: &GuestMemoryMmap = &snapshot;
let notify = ctx.queues.drain(0, |chain| {
let head = chain.head_index();
match request::parse(chain, memory, &disk_info, negotiated)? {
@@ -174,7 +175,8 @@ impl VirtioBlk {
completed,
..
} = active;
- let memory = ctx.memory.as_ref();
+ let snapshot = vm_memory::GuestAddressSpace::memory(&ctx.memory);
+ let memory: &GuestMemoryMmap = &snapshot;
let mut notify = false;
loop {
backend.completions(completed);
diff --git a/src/vmm/src/virtio/fs/device.rs b/src/vmm/src/virtio/fs/device.rs
index 934296baf..04e436c1f 100644
--- a/src/vmm/src/virtio/fs/device.rs
+++ b/src/vmm/src/virtio/fs/device.rs
@@ -4,6 +4,7 @@
use std::io;
use super::{AggregateFs, Share, descriptor::request_buffers, server::Server};
+use crate::memory::GuestMemoryMmap;
use crate::virtio::{
ActivationContext, DeviceError, DeviceEvent, DeviceSpec, FeatureError, SnapshotSupport,
VirtioDevice,
@@ -119,10 +120,11 @@ impl VirtioDevice for Fs {
.as_mut()
.ok_or(DeviceError::NeedsReset("virtio-fs is inactive"))?;
let server = &self.server;
- let memory = &ctx.memory;
+ let snapshot = vm_memory::GuestAddressSpace::memory(&ctx.memory);
+ let memory: &GuestMemoryMmap = &snapshot;
let mut processed = false;
let result = ctx.queues.drain(usize::from(index), |chain| {
- let (reader, writer) = request_buffers(memory.as_ref(), chain)
+ let (reader, writer) = request_buffers(memory, chain)
.map_err(|_| DeviceError::NeedsReset("virtio-fs request descriptors"))?;
let written = server.handle_message(reader, writer).map_err(|error| {
tracing::warn!(%error, "virtio-fs request failed");
diff --git a/src/vmm/src/virtio/mmio.rs b/src/vmm/src/virtio/mmio.rs
index de06f7b20..9c81605bc 100644
--- a/src/vmm/src/virtio/mmio.rs
+++ b/src/vmm/src/virtio/mmio.rs
@@ -41,7 +41,7 @@ use crate::{
chipset::ChipsetBuilder,
error::{Error, Result},
events::{Event, EventSender},
- memory::GuestMemoryMmap,
+ memory::GuestMemoryView,
};
/// The MMIO window length a transport claims.
@@ -153,7 +153,7 @@ pub(crate) fn add_device(
device,
interrupt,
MmioResources {
- memory: Arc::clone(ctx.memory),
+ memory: ctx.memory.clone(),
sender: resources.event_sender(),
worker,
},
@@ -209,8 +209,8 @@ type DeviceResult<T> = std::result::Result<T, DeviceError>;
/// The resources a transport shares with its device and the workers.
pub(crate) struct MmioResources {
- /// The guest memory the queues address.
- pub(crate) memory: Arc<GuestMemoryMmap>,
+ /// The guest memory view the queues address.
+ pub(crate) memory: GuestMemoryView,
/// The run thread's event sender.
pub(crate) sender: EventSender,
/// The device's slot in the virtio workers.
@@ -236,7 +236,7 @@ struct QueueConfig {
pub(crate) struct MmioTransport {
device: Arc<Mutex<dyn VirtioDevice>>,
interrupt: Arc<super::interrupt::MmioInterrupt>,
- memory: Arc<GuestMemoryMmap>,
+ memory: GuestMemoryView,
sender: EventSender,
worker: Arc<dyn WorkerControl>,
spec: DeviceSpec,
@@ -636,13 +636,13 @@ impl MmioTransport {
self.spec.queue_max,
event_idx,
indirect,
- Arc::clone(&self.memory),
+ self.memory.clone(),
)
.map_err(DeviceError::from)?;
let interrupt: Arc<dyn VirtioInterrupt> = self.interrupt.clone();
let ctx = ActivationContext {
- memory: Arc::clone(&self.memory),
+ memory: self.memory.clone(),
queues,
interrupt,
events: worker.events,
diff --git a/src/vmm/src/virtio/mod.rs b/src/vmm/src/virtio/mod.rs
index a3cc0e6e5..eac6f04b9 100644
--- a/src/vmm/src/virtio/mod.rs
+++ b/src/vmm/src/virtio/mod.rs
@@ -26,7 +26,7 @@
use std::{fmt, io, sync::Arc};
use self::{queue::VirtQueues, worker::VirtioWorkers};
-use crate::{events::EventSender, memory::GuestMemoryMmap};
+use crate::{events::EventSender, memory::GuestMemoryView};
pub(crate) mod blk;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
@@ -88,8 +88,8 @@ pub(crate) enum SnapshotSupport {
)
)]
pub(crate) struct DeviceContext<'a> {
- /// The guest RAM every host-side user shares.
- pub(crate) memory: &'a Arc<GuestMemoryMmap>,
+ /// The guest memory view every host-side user shares.
+ pub(crate) memory: &'a GuestMemoryView,
/// The VM's virtio workers.
pub(crate) workers: &'a VirtioWorkers,
/// Device control channels registered during VM construction.
@@ -201,8 +201,9 @@ pub(crate) trait VirtioInterrupt: Send + Sync {
/// The resources a transport gives a device when the driver activates it.
pub(crate) struct ActivationContext {
- /// The guest memory the queues address.
- pub(crate) memory: Arc<GuestMemoryMmap>,
+ /// The guest memory view the queues address. Load one snapshot per unit
+ /// of work, drop it before returning, and never keep one across events.
+ pub(crate) memory: GuestMemoryView,
/// The prepared queues, one slot per `DeviceSpec::queue_max` entry, in
/// queue-number order.
///
diff --git a/src/vmm/src/virtio/queue.rs b/src/vmm/src/virtio/queue.rs
index 7624dce35..fc654ac43 100644
--- a/src/vmm/src/virtio/queue.rs
+++ b/src/vmm/src/virtio/queue.rs
@@ -9,9 +9,11 @@
//! including unready ones; a device checks [`VirtQueues::is_ready`] for the
//! queues it needs.
//!
-//! `prepare` also stores the guest-memory `Arc` and the negotiated
+//! `prepare` also stores the guest-memory view and the negotiated
//! `VIRTIO_F_INDIRECT_DESC` flag, so [`VirtQueues::drain`] and
-//! [`VirtQueues::complete`] do not take them on every call.
+//! [`VirtQueues::complete`] do not take them on every call. Each of those
+//! calls loads the current memory snapshot once and drops it before
+//! returning.
//!
//! A device completes a chain inline with [`Completion::Used`] or takes it with
//! [`Completion::Deferred`]: a deferred chain has already left the available
@@ -23,15 +25,15 @@
//! [`VirtQueues::restore`] keep their signatures but return
//! [`SnapshotError::Unsupported`].
-use std::{fmt, mem::size_of, sync::Arc};
+use std::{fmt, mem::size_of};
use virtio_queue::{
DescriptorChain, Queue, QueueOwnedT, QueueState, QueueT, desc::split::Descriptor,
};
-use vm_memory::{Address, Bytes, GuestAddress};
+use vm_memory::{Address, Bytes, GuestAddress, GuestAddressSpace};
use super::{DeviceError, SnapshotError};
-use crate::memory::GuestMemoryMmap;
+use crate::memory::{GuestMemoryMmap, GuestMemoryView};
/// `VIRTIO_F_INDIRECT_DESC`: the driver may point a chain at an indirect table.
pub(crate) const VIRTIO_F_INDIRECT_DESC: u64 = 1 << 28;
@@ -117,7 +119,7 @@ pub(crate) enum Completion {
pub(crate) struct VirtQueues {
queues: Vec<Queue>,
deferred: Vec<Vec<u16>>,
- memory: Arc<GuestMemoryMmap>,
+ memory: GuestMemoryView,
indirect: bool,
}
@@ -129,14 +131,14 @@ impl VirtQueues {
/// check; the device decides whether it needs them. A ready queue must have
/// a valid size, a non-zero available ring, and rings inside `memory`.
///
- /// The facade stores `memory` and `indirect` for later calls; the Arc is
+ /// The facade stores `memory` and `indirect` for later calls; the view is
/// shared with the activation context, so guest RAM is not copied.
pub(crate) fn prepare(
mut queues: Vec<Queue>,
queue_max: &[u16],
event_idx: bool,
indirect: bool,
- memory: Arc<GuestMemoryMmap>,
+ memory: GuestMemoryView,
) -> Result<Self, QueueError> {
if queues.len() != queue_max.len() {
return Err(QueueError::Count {
@@ -160,7 +162,7 @@ impl VirtQueues {
if queue.avail_ring() == 0 {
return Err(QueueError::Invalid);
}
- if !queue.is_valid(memory.as_ref()) {
+ if !queue.is_valid(&*memory.memory()) {
return Err(QueueError::Memory);
}
}
@@ -187,7 +189,7 @@ impl VirtQueues {
_queue_max: &[u16],
_event_idx: bool,
_indirect: bool,
- _memory: Arc<GuestMemoryMmap>,
+ _memory: GuestMemoryView,
) -> Result<Self, SnapshotError> {
Err(SnapshotError::Unsupported)
}
@@ -258,7 +260,8 @@ impl VirtQueues {
memory,
indirect,
} = self;
- let memory = memory.as_ref();
+ let snapshot = memory.memory();
+ let memory: &GuestMemoryMmap = &snapshot;
let queue = queues
.get_mut(index)
.ok_or(DeviceError::NeedsReset("virtio queue"))?;
@@ -318,7 +321,8 @@ impl VirtQueues {
memory,
..
} = self;
- let memory = memory.as_ref();
+ let snapshot = memory.memory();
+ let memory: &GuestMemoryMmap = &snapshot;
let queue = queues
.get_mut(index)
.ok_or(DeviceError::NeedsReset("virtio queue"))?;
diff --git a/src/vmm/src/virtio/vsock/mod.rs b/src/vmm/src/virtio/vsock/mod.rs
index d0f1c8492..a5bfd92b5 100644
--- a/src/vmm/src/virtio/vsock/mod.rs
+++ b/src/vmm/src/virtio/vsock/mod.rs
@@ -263,7 +263,8 @@ impl Active {
Ok(Completion::Deferred)
})?;
let pending = &mut self.tx;
- let memory = &self.ctx.memory;
+ let snapshot = vm_memory::GuestAddressSpace::memory(&self.ctx.memory);
+ let memory: &crate::memory::GuestMemoryMmap = &snapshot;
let limit = self.ctx.queues.max_size(TX).unwrap() as usize;
self.ctx.queues.drain(TX, |chain| {
if pending.len() >= limit || chain.clone().any(|descriptor| descriptor.is_write_only())
@@ -271,7 +272,7 @@ impl Active {
return Err(bad_queue());
}
let head = chain.head_index();
- let mut reader = Reader::new(memory.as_ref(), chain).map_err(|_| bad_queue())?;
+ let mut reader = Reader::new(memory, chain).map_err(|_| bad_queue())?;
let packet = Packet::read(&mut reader).map_err(|_| bad_queue())?;
pending.push_back((head, packet));
Ok(Completion::Deferred)
@@ -323,7 +324,10 @@ impl Active {
header.len = count as u32;
let mut bytes = header.encode().to_vec();
bytes.extend_from_slice(&packet.payload[..count]);
- buffer.write(&self.ctx.memory, &bytes)?;
+ buffer.write(
+ &vm_memory::GuestAddressSpace::memory(&self.ctx.memory),
+ &bytes,
+ )?;
if count == packet.payload.len() {
self.backend.outgoing.pop_front();
} else {
diff --git a/src/vmm/tests/boot/balloon.rs b/src/vmm/tests/boot/balloon.rs
index 8ffe3a3b1..be80d9fc0 100644
--- a/src/vmm/tests/boot/balloon.rs
+++ b/src/vmm/tests/boot/balloon.rs
@@ -111,7 +111,7 @@ fn run_reporting_guest(init_on_free: bool) -> (Evidence, String) {
move || boxlite_hypervisor::KvmVm::from_prepared(prepared),
move |ram, config| prepare(ram, config, leaf).map(|setup| setup.boot_regs),
|chipset, ctx, config| {
- sampler_memory = Some(Arc::clone(ctx.memory));
+ sampler_memory = Some(ctx.memory.memory().into_inner());
crate::devices::add_all(chipset, ctx, config, writer).map(|_| ())
},
)
diff --git a/src/vmm/tests/boot/mod.rs b/src/vmm/tests/boot/mod.rs
index 339da603a..d20d61196 100644
--- a/src/vmm/tests/boot/mod.rs
+++ b/src/vmm/tests/boot/mod.rs
@@ -20,6 +20,7 @@ use std::{
thread,
time::{Duration, Instant},
};
+use vm_memory::GuestAddressSpace as _;
use linux_loader::loader::bootparam::boot_params;
use vm_memory::{Bytes, GuestAddress};
@@ -98,7 +99,7 @@ fn enters_the_loaded_kernel_with_rsi_at_the_zero_page() {
.boot_regs;
assert_eq!((regs.rip, regs.rsi), (ENTRY, 0x7000));
- let memory = ram.memory();
+ let memory = ram.memory().memory();
let mut code = [0; 8];
memory.read_slice(&mut code, GuestAddress(ENTRY)).unwrap();
assert_eq!(&code, b"CODE1234", "the kernel is loaded at its entry");
@@ -130,7 +131,7 @@ fn loads_the_initramfs_at_the_top_of_ram_and_records_it() {
let leaf = PageSize::Mib.checked(false).unwrap();
let regs = prepare(&ram, &config, leaf).unwrap().boot_regs;
- let memory = ram.memory();
+ let memory = ram.memory().memory();
let params: boot_params = memory.read_obj(GuestAddress(regs.rsi)).unwrap();
// 2 MiB of RAM minus 3000 bytes, rounded down to a page.
let hdr = params.hdr;
@@ -392,7 +393,7 @@ fn linux_vm_with_leaf(
|ram, config| {
let setup = prepare(ram, config, leaf)?;
let address = GuestAddress(setup.boot_regs.rsi);
- zero_page = Some(ram.memory().read_obj(address).unwrap());
+ zero_page = Some(ram.memory().memory().read_obj(address).unwrap());
Ok(setup.boot_regs)
},
|chipset, _| add_legacy_devices(chipset, writer),
diff --git a/src/vmm/tests/elf/mod.rs b/src/vmm/tests/elf/mod.rs
index 660c31c03..eeb7f4080 100644
--- a/src/vmm/tests/elf/mod.rs
+++ b/src/vmm/tests/elf/mod.rs
@@ -4,6 +4,7 @@
//! Tests for the library-backed ELF adapter and guest visibility.
use std::io::{self, Cursor};
+use vm_memory::GuestAddressSpace as _;
use vm_memory::{Bytes, GuestAddress};
@@ -85,7 +86,8 @@ fn load(ram: &GuestMemoryMmap, image: &[u8]) -> io::Result<LoadedKernel> {
#[test]
fn loads_physical_bytes_and_returns_the_kernel_entry() {
let ram = ram(RAM_SIZE);
- let memory = ram.memory().as_ref();
+ let memory = ram.memory().memory();
+ let memory = &*memory;
let image = fixture();
let kernel = load(memory, &image).unwrap();
@@ -115,7 +117,7 @@ fn reports_the_lowest_loadable_physical_address_not_the_entry() {
let lowest_paddr = 0xf_f000;
put64(&mut image, header(1) + 24, lowest_paddr);
- let kernel = load(ram.memory().as_ref(), &image).unwrap();
+ let kernel = load(ram.boot_memory().as_ref(), &image).unwrap();
assert_eq!(kernel.entry, ENTRY);
assert_eq!(kernel.start, lowest_paddr);
}
@@ -139,7 +141,7 @@ fn zero_memsz_load_segments_do_not_widen_kernel_bounds() {
put64(&mut image, 32, phoff as u64);
put16(&mut image, 56, (SEGMENTS.len() + 2) as u16);
- let kernel = load(ram.memory().as_ref(), &image).unwrap();
+ let kernel = load(ram.boot_memory().as_ref(), &image).unwrap();
assert_eq!(kernel.entry, ENTRY);
assert_eq!(kernel.start, 0x10_0000);
assert_eq!(kernel.end, 0x10_3080);
@@ -151,12 +153,12 @@ fn rejects_invalid_elf64_headers_and_overflowing_segments() {
for (offset, value) in [(0, 0), (4, 1)] {
let mut image = fixture();
image[offset] = value;
- let error = load(ram.memory().as_ref(), &image).unwrap_err();
+ let error = load(ram.boot_memory().as_ref(), &image).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
}
let mut image = fixture();
put64(&mut image, header(2) + 24, u64::MAX);
- let error = load(ram.memory().as_ref(), &image).unwrap_err();
+ let error = load(ram.boot_memory().as_ref(), &image).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
assert_eq!(error.to_string(), "ELF64 segment end overflows");
}
@@ -166,10 +168,10 @@ fn reports_truncated_headers_and_preserves_the_library_error_for_truncated_paylo
let valid = fixture();
let ram = ram(RAM_SIZE);
for image in [&[][..], &valid[..header(2)]] {
- let error = load(ram.memory().as_ref(), image).unwrap_err();
+ let error = load(ram.boot_memory().as_ref(), image).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
}
- let error = load(ram.memory().as_ref(), &valid[..valid.len() - 1]).unwrap_err();
+ let error = load(ram.boot_memory().as_ref(), &valid[..valid.len() - 1]).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Other);
assert!(
error
@@ -241,7 +243,8 @@ fn native_vmlinux_bytes_are_visible_to_a_kvm_vcpu() {
// RAM is declared before the VM and vCPU so it outlives them during unwinding.
let ram = ram(RAM_SIZE);
- let memory = ram.memory().as_ref();
+ let memory = ram.memory().memory();
+ let memory = &*memory;
let mut kernel = std::fs::File::open(&path).expect("open VMM_KERNEL");
let kernel = load_elf(memory, &mut kernel).unwrap();
assert_eq!(kernel.entry, expected_entry);
diff --git a/src/vmm/tests/flat_guest/mod.rs b/src/vmm/tests/flat_guest/mod.rs
index 445dbdb35..0ad6a1f00 100644
--- a/src/vmm/tests/flat_guest/mod.rs
+++ b/src/vmm/tests/flat_guest/mod.rs
@@ -10,6 +10,7 @@ use std::{
thread,
time::Duration,
};
+use vm_memory::GuestAddressSpace as _;
use boxlite_hypervisor::{KvmVcpu, KvmVm, VcpuExit, VcpuHandle as _, X86BootRegisters, X86Segment};
use vm_memory::{Bytes, GuestAddress};
@@ -37,7 +38,7 @@ impl FlatGuest {
let mut ram = GuestRam::new(&ram_ranges(2)).unwrap();
let vm = Arc::new(KvmVm::new().expect("create KVM VM"));
ram.map(&*vm).expect("map guest RAM");
- let regs = load(ram.memory(), program);
+ let regs = load(&ram.memory().memory(), program);
let mut vcpu = vm.create_vcpu(0).expect("create vCPU");
vcpu.set_boot_registers(&regs).unwrap();
Self { vcpu, vm, ram }
@@ -83,6 +84,7 @@ impl FlatGuest {
/// Reads guest RAM at `addr`.
pub(crate) fn read(&self, addr: u64, data: &mut [u8]) {
self.ram
+ .memory()
.memory()
.read_slice(data, GuestAddress(addr))
.unwrap();
diff --git a/src/vmm/tests/hotplug/mod.rs b/src/vmm/tests/hotplug/mod.rs
new file mode 100644
index 000000000..36866602b
--- /dev/null
+++ b/src/vmm/tests/hotplug/mod.rs
@@ -0,0 +1,314 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+//! Hotplug window tests: block ranges, slot mapping and rollback, discard,
+//! slot removal, and the view devices load.
+
+use std::sync::Arc;
+
+use vm_memory::{Bytes, GuestAddress, GuestAddressSpace, GuestMemoryBackend};
+
+use super::*;
+use crate::mock_vm::{Call, MockVm};
+
+const MIB: u64 = 1 << 20;
+const GIB: u64 = 1024 * MIB;
+const HOTPLUG_START: u64 = 4 * GIB;
+
+fn view() -> GuestMemoryView {
+ GuestMemoryView::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x1_0000)]).unwrap())
+}
+
+fn window(vm: MockVm, capacity_mib: u32) -> (Arc<MockVm>, GuestMemoryView, HotplugMemory<MockVm>) {
+ let vm = Arc::new(vm);
+ let view = view();
+ let window =
+ HotplugWindow::plan(&[(GuestAddress(0), 0x1_0000)], capacity_mib, 64 * GIB, 16).unwrap();
+ let memory = HotplugMemory::new(Arc::clone(&vm), view.clone(), window);
+ (vm, view, memory)
+}
+
+fn block_addr(block: u64) -> GuestAddress {
+ GuestAddress(HOTPLUG_START + block * BLOCK_SIZE)
+}
+
+fn slot_calls(vm: &MockVm) -> Vec<(bool, u64, usize)> {
+ vm.calls()
+ .into_iter()
+ .filter_map(|call| match call {
+ Call::Map {
+ guest_addr, size, ..
+ } => Some((true, guest_addr, size)),
+ Call::Unmap {
+ guest_addr, size, ..
+ } => Some((false, guest_addr, size)),
+ _ => None,
+ })
+ .collect()
+}
+
+const SLOT: usize = SLOT_SIZE as usize;
+const SECOND_SLOT: u64 = HOTPLUG_START + SLOT_SIZE;
+
+#[test]
+#[cfg(target_arch = "x86_64")]
+fn window_starts_after_high_boot_ram() {
+ use crate::memory::{GuestRam, ram_ranges};
+
+ let ranges = ram_ranges(6144);
+ let mut ram = GuestRam::new(&ranges).unwrap();
+ let vm = Arc::new(MockVm::new());
+ ram.map(vm.as_ref()).unwrap();
+ let window = HotplugWindow::plan(&ranges, 128, 64 * GIB, 1).unwrap();
+ let mut memory = HotplugMemory::new(Arc::clone(&vm), ram.memory().clone(), window);
+
+ assert_eq!(memory.base(), 7 * GIB);
+ memory
+ .plug(memory.blocks(memory.base(), 1).unwrap())
+ .unwrap();
+ assert_eq!(slot_calls(&vm)[2], (true, 7 * GIB, SLOT));
+ drop(memory);
+ ram.unmap(vm.as_ref()).unwrap();
+}
+
+#[test]
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm"]
+fn kvm_rejects_the_old_window_and_maps_the_planned_window() {
+ use boxlite_hypervisor::{Error, KvmVm};
+
+ use crate::{
+ cpu_features::X86MemoryCaps,
+ memory::{GuestRam, ram_ranges},
+ };
+
+ let ranges = ram_ranges(6144);
+ let mut ram = GuestRam::new(&ranges).unwrap();
+ let vm = Arc::new(KvmVm::new().unwrap());
+ ram.map(vm.as_ref()).unwrap();
+ let old_window = HotplugWindow {
+ base: 4 * GIB,
+ slots: 1,
+ };
+ let mut old = HotplugMemory::new(Arc::clone(&vm), ram.memory().clone(), old_window);
+ let error = old.plug(0..1).unwrap_err();
+ assert!(
+ matches!(error.get_ref().and_then(|e| e.downcast_ref::<Error>()),
+ Some(Error::MapMemory { source, .. }) if source.kind() == io::ErrorKind::AlreadyExists)
+ );
+
+ let caps = X86MemoryCaps::from_cpuid(vm.supported_cpuid()).unwrap();
+ let window = HotplugWindow::plan(&ranges, 128, caps.physical_end, 1).unwrap();
+ let mut memory = HotplugMemory::new(Arc::clone(&vm), ram.memory().clone(), window);
+ assert_eq!(memory.base(), 7 * GIB);
+ memory.plug(0..1).unwrap();
+ ram.memory()
+ .memory()
+ .write_obj(0x2au8, GuestAddress(7 * GIB))
+ .unwrap();
+ memory.unplug(0..1).unwrap();
+ ram.unmap(vm.as_ref()).unwrap();
+}
+
+#[test]
+fn capacity_must_be_a_positive_multiple_of_a_slot() {
+ for capacity in [0, 64, 129] {
+ let error = HotplugWindow::plan(&[], capacity, 64 * GIB, 16).unwrap_err();
+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
+ }
+ let (_, _, memory) = window(MockVm::new(), 256);
+ assert_eq!((memory.base(), memory.size()), (HOTPLUG_START, 256 * MIB));
+}
+
+#[test]
+#[cfg(target_arch = "x86_64")]
+fn placement_and_capacity_follow_linux_memory_block_alignment() {
+ use crate::memory::ram_ranges;
+
+ for (boot_mib, base, block_mib) in [
+ (512, 4 * GIB, 128),
+ (3072, 4 * GIB, 128),
+ (3073, 4 * GIB + SLOT_SIZE, 128),
+ (63 * 1024, 64 * GIB, 2048),
+ (64 * 1024, 65 * GIB, 1024),
+ (63 * 1024 + 128, 64 * GIB + SLOT_SIZE, 128),
+ ] {
+ let boot = ram_ranges(boot_mib);
+ let plan = HotplugWindow::plan(&boot, block_mib, 128 * GIB, 16).unwrap();
+ assert_eq!(plan.base, base, "{boot_mib} MiB of boot RAM");
+ assert!(HotplugWindow::plan(&boot, block_mib / 2, 128 * GIB, 16).is_err());
+ }
+}
+
+#[test]
+fn window_respects_address_and_slot_limits() {
+ let boot = [(GuestAddress(4 * GIB), GIB as usize)];
+ assert!(HotplugWindow::plan(&boot, 128, 5 * GIB + SLOT_SIZE, 1).is_ok());
+ assert!(HotplugWindow::plan(&boot, 256, 5 * GIB + SLOT_SIZE, 2).is_err());
+ assert!(HotplugWindow::plan(&boot, 128, 5 * GIB + SLOT_SIZE, 0).is_err());
+
+ let boot = [(GuestAddress(GUEST_PLUGGABLE_END - 2 * SLOT_SIZE), SLOT)];
+ assert!(HotplugWindow::plan(&boot, 128, 2 * GUEST_PLUGGABLE_END, 1).is_ok());
+ assert!(HotplugWindow::plan(&boot, 256, 2 * GUEST_PLUGGABLE_END, 2).is_err());
+ assert!(HotplugWindow::plan(&[(GuestAddress(u64::MAX), 1)], 128, u64::MAX, 1).is_err());
+ assert!(HotplugWindow::plan(&[(GuestAddress(u64::MAX - 1), 1)], 128, u64::MAX, 1).is_err());
+}
+
+#[test]
+fn block_ranges_reject_empty_misaligned_and_outside_requests() {
+ let (_, _, memory) = window(MockVm::new(), 128);
+ let last = HOTPLUG_START + SLOT_SIZE - BLOCK_SIZE;
+ assert_eq!(memory.blocks(HOTPLUG_START, 1), Some(0..1));
+ assert_eq!(memory.blocks(last, 1), Some(63..64));
+ assert_eq!(memory.blocks(last, 2), None);
+ assert_eq!(memory.blocks(HOTPLUG_START, 0), None);
+ assert_eq!(memory.blocks(HOTPLUG_START + 4096, 1), None);
+ assert_eq!(memory.blocks(HOTPLUG_START - BLOCK_SIZE, 1), None);
+ assert_eq!(memory.blocks(u64::MAX - 1, u16::MAX), None);
+}
+
+#[test]
+fn plug_maps_each_needed_slot_once_and_publishes_it() {
+ let (vm, view, mut memory) = window(MockVm::new(), 256);
+ let blocks = memory.blocks(SECOND_SLOT - BLOCK_SIZE, 2).unwrap();
+ memory.plug(blocks.clone()).unwrap();
+
+ assert_eq!(
+ slot_calls(&vm),
+ [(true, HOTPLUG_START, SLOT), (true, SECOND_SLOT, SLOT)]
+ );
+ assert_eq!(memory.state(blocks), BlockState::Plugged);
+ assert_eq!(memory.state(0..2), BlockState::Unplugged);
+ assert_eq!(memory.state(62..64), BlockState::Mixed);
+ assert_eq!(
+ (memory.plugged_bytes(), memory.mapped_bytes()),
+ (4 * MIB, 256 * MIB)
+ );
+ view.memory()
+ .write_obj(7u8, GuestAddress(SECOND_SLOT))
+ .unwrap();
+
+ memory
+ .plug(memory.blocks(HOTPLUG_START, 1).unwrap())
+ .unwrap();
+ assert_eq!(slot_calls(&vm).len(), 2, "both slots were already mapped");
+}
+
+#[test]
+fn a_failed_slot_map_unregisters_the_slots_this_plug_added() {
+ // Call 0 maps the first slot; call 1, the second slot, fails.
+ let (vm, view, mut memory) = window(MockVm::failing_at(&[1]), 256);
+ let blocks = memory.blocks(SECOND_SLOT - BLOCK_SIZE, 2).unwrap();
+
+ memory.plug(blocks.clone()).unwrap_err();
+
+ assert_eq!(
+ slot_calls(&vm),
+ [
+ (true, HOTPLUG_START, SLOT),
+ (true, SECOND_SLOT, SLOT),
+ (false, HOTPLUG_START, SLOT)
+ ]
+ );
+ assert_eq!(memory.state(blocks), BlockState::Unplugged);
+ assert_eq!((memory.plugged_bytes(), memory.mapped_bytes()), (0, 0));
+ assert!(!view.memory().address_in_range(GuestAddress(HOTPLUG_START)));
+}
+
+#[test]
+fn unplugging_part_of_a_mapped_slot_discards_those_blocks() {
+ let (vm, view, mut memory) = window(MockVm::new(), 128);
+ memory
+ .plug(memory.blocks(HOTPLUG_START, 2).unwrap())
+ .unwrap();
+ view.memory().write_obj(0x5au8, block_addr(1)).unwrap();
+
+ memory
+ .unplug(memory.blocks(block_addr(1).0, 1).unwrap())
+ .unwrap();
+
+ assert_eq!(slot_calls(&vm).len(), 1, "the slot stays registered");
+ assert_eq!(memory.mapped_bytes(), SLOT_SIZE);
+ assert_eq!(memory.plugged_bytes(), BLOCK_SIZE);
+ // Darwin's MADV_DONTNEED discards only under memory pressure.
+ #[cfg(target_os = "linux")]
+ assert_eq!(view.memory().read_obj::<u8>(block_addr(1)).unwrap(), 0);
+}
+
+#[test]
+fn unplugging_a_slot_unregisters_it_and_a_held_snapshot_keeps_it_readable() {
+ let (vm, view, mut memory) = window(MockVm::new(), 128);
+ memory
+ .plug(memory.blocks(HOTPLUG_START, 1).unwrap())
+ .unwrap();
+ view.memory().write_obj(9u8, block_addr(0)).unwrap();
+ let held = view.memory();
+
+ memory.unplug_all().unwrap();
+
+ assert_eq!(
+ slot_calls(&vm),
+ [(true, HOTPLUG_START, SLOT), (false, HOTPLUG_START, SLOT)]
+ );
+ assert_eq!((memory.plugged_bytes(), memory.mapped_bytes()), (0, 0));
+ assert!(view.memory().read_obj::<u8>(block_addr(0)).is_err());
+ assert_eq!(held.read_obj::<u8>(block_addr(0)).unwrap(), 9);
+}
+
+#[test]
+fn a_failed_slot_unmap_keeps_the_slot_mapped_and_visible() {
+ // Call 0 maps the slot; call 1, its removal, fails.
+ let (_, view, mut memory) = window(MockVm::failing_at(&[1]), 128);
+ let blocks = memory.blocks(HOTPLUG_START, 1).unwrap();
+ memory.plug(blocks.clone()).unwrap();
+
+ memory.unplug(blocks.clone()).unwrap_err();
+
+ assert_eq!(memory.state(blocks), BlockState::Unplugged);
+ assert_eq!(memory.mapped_bytes(), SLOT_SIZE);
+ assert!(view.memory().address_in_range(GuestAddress(HOTPLUG_START)));
+}
+
+#[test]
+fn drop_unregisters_every_mapped_slot() {
+ let (vm, _, mut memory) = window(MockVm::new(), 256);
+ memory
+ .plug(memory.blocks(HOTPLUG_START, 1).unwrap())
+ .unwrap();
+ memory.plug(memory.blocks(SECOND_SLOT, 1).unwrap()).unwrap();
+
+ drop(memory);
+
+ assert_eq!(
+ slot_calls(&vm),
+ [
+ (true, HOTPLUG_START, SLOT),
+ (true, SECOND_SLOT, SLOT),
+ (false, HOTPLUG_START, SLOT),
+ (false, SECOND_SLOT, SLOT)
+ ]
+ );
+}
+
+#[test]
+fn unplug_after_a_poisoned_view_lock_still_removes_the_slot_everywhere() {
+ let (vm, view, mut memory) = window(MockVm::new(), 128);
+ let blocks = memory.blocks(HOTPLUG_START, 1).unwrap();
+ memory.plug(blocks.clone()).unwrap();
+ let poisoner = view.clone();
+ std::thread::spawn(move || {
+ let _guard = poisoner.lock().unwrap();
+ panic!("poison the view lock");
+ })
+ .join()
+ .unwrap_err();
+
+ memory.unplug(blocks).unwrap();
+
+ assert_eq!(
+ slot_calls(&vm),
+ [(true, HOTPLUG_START, SLOT), (false, HOTPLUG_START, SLOT)]
+ );
+ assert_eq!(memory.mapped_bytes(), 0);
+ assert!(!view.memory().address_in_range(GuestAddress(HOTPLUG_START)));
+}
diff --git a/src/vmm/tests/memory/mod.rs b/src/vmm/tests/memory/mod.rs
index 9a1091f04..bf3492bab 100644
--- a/src/vmm/tests/memory/mod.rs
+++ b/src/vmm/tests/memory/mod.rs
@@ -7,7 +7,7 @@
use std::{error::Error as _, io, sync::Arc};
use boxlite_hypervisor::{Error as HypervisorError, Vm};
-use vm_memory::{Bytes, GuestAddress, GuestMemoryBackend};
+use vm_memory::{Bytes, GuestAddress, GuestAddressSpace, GuestMemoryBackend};
use super::{ARM64_LAYOUT, GuestRam, RAM_START, X86_LAYOUT, check_ram_end, ram_ranges};
use crate::{
@@ -144,21 +144,21 @@ fn ram_layout_rejects_end_gpa_overflow() {
#[test]
fn allocated_ram_is_zeroed_and_mirrors_its_ranges() {
let ram = GuestRam::new(&ram_ranges(2)).unwrap();
- let regions: Vec<_> = ram.regions().collect();
- assert_eq!(regions.len(), 1);
- assert_eq!(regions[0].guest_addr, RAM_START);
- assert_eq!(regions[0].size, 2 * MIB);
+ let [region] = ram.regions().collect::<Vec<_>>().try_into().unwrap();
+ assert_eq!(region.guest_addr, RAM_START);
+ assert_eq!(region.size, 2 * MIB);
let host = ram
+ .memory()
.memory()
.get_host_address(GuestAddress(RAM_START))
.unwrap();
- assert_eq!(regions[0].host_addr.as_ptr(), host);
+ assert_eq!(region.host_addr.as_ptr(), host);
assert_eq!(host as usize % 4096, 0, "mmap returns page-aligned memory");
let last = GuestAddress(RAM_START + 2 * MIB as u64 - 1);
- assert_eq!(ram.memory().read_obj::<u8>(last).unwrap(), 0);
- ram.memory().write_obj(0x4bu8, last).unwrap();
- assert_eq!(ram.memory().read_obj::<u8>(last).unwrap(), 0x4b);
+ assert_eq!(ram.memory().memory().read_obj::<u8>(last).unwrap(), 0);
+ ram.memory().memory().write_obj(0x4bu8, last).unwrap();
+ assert_eq!(ram.memory().memory().read_obj::<u8>(last).unwrap(), 0x4b);
}
#[test]
@@ -187,14 +187,14 @@ fn maps_ascending_and_unmaps_descending_with_the_backing_addresses() {
[
(
1 << 32,
- ram.memory()
+ ram.boot_memory()
.get_host_address(GuestAddress(1 << 32))
.unwrap() as usize,
MIB,
),
(
0,
- ram.memory().get_host_address(GuestAddress(0)).unwrap() as usize,
+ ram.boot_memory().get_host_address(GuestAddress(0)).unwrap() as usize,
MIB,
),
]
@@ -205,7 +205,7 @@ fn maps_ascending_and_unmaps_descending_with_the_backing_addresses() {
fn a_rejected_mapping_returns_the_hypervisor_error_and_keeps_no_registration() {
let mut ram = GuestRam::new(&ram_ranges(16)).unwrap();
let vm = MockVm::failing_at(&[0]);
- let backing = Arc::downgrade(ram.memory());
+ let backing = Arc::downgrade(ram.boot_memory());
assert!(matches!(
ram.map(&vm),
@@ -320,7 +320,7 @@ fn failed_rollback_keeps_the_backing_alive() {
let mut ram = two_regions();
let vm = MockVm::failing_at(&[2, 4]);
seed_second_registration(&ram, &vm);
- let weak = Arc::downgrade(ram.memory());
+ let weak = Arc::downgrade(ram.boot_memory());
let [(map0, unmap0), (map1, unmap1)] = expected_calls(&ram)[..] else {
panic!("two regions")
};
@@ -346,7 +346,7 @@ fn a_map_failure_cleans_up_slices_before_returning() {
let mut ram = two_regions();
let vm = MockVm::failing_at(&[2]);
seed_second_registration(&ram, &vm);
- let weak = Arc::downgrade(ram.memory());
+ let weak = Arc::downgrade(ram.boot_memory());
let [(map0, unmap0), (map1, unmap1)] = expected_calls(&ram)[..] else {
panic!("two regions")
};
@@ -367,7 +367,7 @@ fn a_failed_cleanup_keeps_the_backing_alive() {
(3, io::ErrorKind::NotFound),
]);
seed_second_registration(&ram, &vm);
- let weak = Arc::downgrade(ram.memory());
+ let weak = Arc::downgrade(ram.boot_memory());
let [(map0, _), (map1, unmap1)] = expected_calls(&ram)[..] else {
panic!("two regions")
};
@@ -391,7 +391,7 @@ fn failed_unmap_keeps_state_and_retry_unmaps_only_the_remainder() {
let [(map0, unmap0), (map1, unmap1)] = expected_calls(&ram)[..] else {
panic!("two regions")
};
- let weak = Arc::downgrade(ram.memory());
+ let weak = Arc::downgrade(&ram.memory().memory().into_inner());
ram.map(&vm).unwrap();
let error = ram.unmap(&vm).unwrap_err();
@@ -406,14 +406,14 @@ fn failed_unmap_keeps_state_and_retry_unmaps_only_the_remainder() {
[
(
1 << 32,
- ram.memory()
+ ram.boot_memory()
.get_host_address(GuestAddress(1 << 32))
.unwrap() as usize,
MIB,
),
(
0,
- ram.memory().get_host_address(GuestAddress(0)).unwrap() as usize,
+ ram.boot_memory().get_host_address(GuestAddress(0)).unwrap() as usize,
MIB,
),
]
@@ -439,7 +439,7 @@ fn failed_unmap_keeps_state_and_retry_unmaps_only_the_remainder() {
#[test]
fn drop_without_unmap_leaks_the_backing() {
let mut ram = two_regions();
- let weak = Arc::downgrade(ram.memory());
+ let weak = Arc::downgrade(&ram.memory().memory().into_inner());
ram.map(&MockVm::new()).unwrap();
drop(ram);
@@ -611,3 +611,25 @@ fn reporting_rejects_shared_and_non_owned_backing() {
.unwrap();
assert!(super::ReclaimRange::new(&raw, GuestAddress(0), page, page).is_err());
}
+
+#[test]
+fn registrations_cover_only_the_boot_regions_a_view_update_leaves_alone() {
+ let mut ram = GuestRam::new(&ram_ranges(2)).unwrap();
+ let extra = Arc::new(
+ vm_memory::GuestRegionMmap::from_range(GuestAddress(1 << 32), 4096, None).unwrap(),
+ );
+ let grown = ram.memory().memory().insert_region(extra).unwrap();
+ ram.memory().lock().unwrap().replace(grown);
+ let vm = MockVm::new();
+
+ ram.map(&vm).unwrap();
+ ram.unmap(&vm).unwrap();
+
+ let [boot] = ram.regions().collect::<Vec<_>>().try_into().unwrap();
+ assert_eq!(boot.guest_addr, RAM_START);
+ assert_eq!(
+ vm.calls(),
+ [Call::map(&boot), Call::unmap(&boot)],
+ "the published hotplug region is never registered by GuestRam"
+ );
+}
diff --git a/src/vmm/tests/net/mod.rs b/src/vmm/tests/net/mod.rs
index 91cd08477..cfe803add 100644
--- a/src/vmm/tests/net/mod.rs
+++ b/src/vmm/tests/net/mod.rs
@@ -188,9 +188,15 @@ impl Harness {
})
.collect();
ActivationContext {
- memory: self.memory.clone(),
- queues: VirtQueues::prepare(queues, SPEC.queue_max, false, false, self.memory.clone())
- .unwrap(),
+ memory: self.memory.clone().into(),
+ queues: VirtQueues::prepare(
+ queues,
+ SPEC.queue_max,
+ false,
+ false,
+ self.memory.clone().into(),
+ )
+ .unwrap(),
interrupt: self.interrupt.clone(),
events: self.registrar.clone(),
waker: Arc::new(|| {}),
@@ -890,7 +896,7 @@ fn tx_disconnect_and_invalid_activation_do_not_leave_a_source() {
&[QUEUE_SIZE],
false,
false,
- h.memory.clone(),
+ h.memory.clone().into(),
)
.unwrap();
} else {
@@ -902,7 +908,7 @@ fn tx_disconnect_and_invalid_activation_do_not_leave_a_source() {
SPEC.queue_max,
false,
false,
- h.memory.clone(),
+ h.memory.clone().into(),
)
.unwrap();
}
diff --git a/src/vmm/tests/virtio/balloon.rs b/src/vmm/tests/virtio/balloon.rs
index d2bb030d6..72fff77c5 100644
--- a/src/vmm/tests/virtio/balloon.rs
+++ b/src/vmm/tests/virtio/balloon.rs
@@ -111,11 +111,11 @@ fn context(
SPEC.queue_max,
false,
false,
- Arc::clone(memory),
+ Arc::clone(memory).into(),
)
.unwrap();
ActivationContext {
- memory: Arc::clone(memory),
+ memory: Arc::clone(memory).into(),
queues,
interrupt,
events: Arc::new(NoSources),
@@ -808,8 +808,14 @@ fn report_hva_aliasing_control_gpa_is_rejected_before_any_reclaim() {
queues[0]
.try_set_desc_table_address(GuestAddress(alias_gpa))
.unwrap();
- ctx.queues =
- VirtQueues::prepare(queues, SPEC.queue_max, false, false, Arc::clone(&memory)).unwrap();
+ ctx.queues = VirtQueues::prepare(
+ queues,
+ SPEC.queue_max,
+ false,
+ false,
+ Arc::clone(&memory).into(),
+ )
+ .unwrap();
let mut balloon = VirtioBalloon::new(ReclaimPolicy::Immediate).unwrap();
balloon.set_features(REPORTING).unwrap();
balloon.activate(ctx).unwrap();
@@ -853,8 +859,14 @@ fn activation_rejects_a_control_table_spanning_adjacent_regions() {
queues[0]
.try_set_desc_table_address(GuestAddress(RAM_LEN as u64 - 64))
.unwrap();
- ctx.queues =
- VirtQueues::prepare(queues, SPEC.queue_max, false, false, Arc::clone(&memory)).unwrap();
+ ctx.queues = VirtQueues::prepare(
+ queues,
+ SPEC.queue_max,
+ false,
+ false,
+ Arc::clone(&memory).into(),
+ )
+ .unwrap();
let mut balloon = VirtioBalloon::new(ReclaimPolicy::Immediate).unwrap();
balloon.set_features(REPORTING).unwrap();
assert!(matches!(
diff --git a/src/vmm/tests/virtio/blk/mod.rs b/src/vmm/tests/virtio/blk/mod.rs
index fd1e3c6b0..0d5da4a28 100644
--- a/src/vmm/tests/virtio/blk/mod.rs
+++ b/src/vmm/tests/virtio/blk/mod.rs
@@ -359,11 +359,11 @@ impl Fixture {
QUEUE_MAXIMUM,
false,
false,
- Arc::clone(&self.memory),
+ Arc::clone(&self.memory).into(),
)
.unwrap();
ActivationContext {
- memory: Arc::clone(&self.memory),
+ memory: Arc::clone(&self.memory).into(),
queues,
interrupt: Arc::clone(&self.interrupt) as Arc<dyn VirtioInterrupt>,
events: Arc::clone(&self.registrar) as Arc<dyn EventRegistrar>,
diff --git a/src/vmm/tests/virtio/fs_device.rs b/src/vmm/tests/virtio/fs_device.rs
index dc69e3010..fe447088c 100644
--- a/src/vmm/tests/virtio/fs_device.rs
+++ b/src/vmm/tests/virtio/fs_device.rs
@@ -139,13 +139,13 @@ impl Guest {
.collect();
self.device
.activate(ActivationContext {
- memory: Arc::clone(&self.memory),
+ memory: Arc::clone(&self.memory).into(),
queues: VirtQueues::prepare(
queues,
&[SIZE, SIZE],
event_idx,
false,
- Arc::clone(&self.memory),
+ Arc::clone(&self.memory).into(),
)
.unwrap(),
interrupt: self.interrupt.clone(),
@@ -809,9 +809,15 @@ fn fs_device_rejects_each_missing_queue_without_partial_activation() {
})
.collect();
let context = ActivationContext {
- memory: guest.memory.clone(),
- queues: VirtQueues::prepare(queues, &[SIZE, SIZE], false, false, guest.memory.clone())
- .unwrap(),
+ memory: guest.memory.clone().into(),
+ queues: VirtQueues::prepare(
+ queues,
+ &[SIZE, SIZE],
+ false,
+ false,
+ guest.memory.clone().into(),
+ )
+ .unwrap(),
interrupt: guest.interrupt.clone(),
events: Arc::new(Registrar),
waker: Arc::new(|| {}),
diff --git a/src/vmm/tests/virtio/fs_worker.rs b/src/vmm/tests/virtio/fs_worker.rs
index b8e33662f..a74b35736 100644
--- a/src/vmm/tests/virtio/fs_worker.rs
+++ b/src/vmm/tests/virtio/fs_worker.rs
@@ -228,7 +228,7 @@ impl Guest {
device,
interrupt,
MmioResources {
- memory: memory.clone(),
+ memory: memory.clone().into(),
sender: events.sender(),
worker: worker.clone(),
},
diff --git a/src/vmm/tests/virtio/mmio.rs b/src/vmm/tests/virtio/mmio.rs
index 1a3283c7e..1ac9e63ec 100644
--- a/src/vmm/tests/virtio/mmio.rs
+++ b/src/vmm/tests/virtio/mmio.rs
@@ -259,7 +259,7 @@ fn make(spec: DeviceSpec) -> Fixture {
device,
Arc::clone(&interrupt),
MmioResources {
- memory,
+ memory: memory.into(),
sender: events.sender(),
worker: Arc::clone(&worker) as Arc<dyn WorkerControl>,
},
@@ -287,7 +287,7 @@ fn try_make(spec: DeviceSpec) -> crate::error::Result<MmioTransport> {
device,
interrupt,
MmioResources {
- memory,
+ memory: memory.into(),
sender: events.sender(),
worker,
},
@@ -833,7 +833,7 @@ fn a_chipset_dispatches_mmio_to_the_transport() {
device,
interrupt,
MmioResources {
- memory,
+ memory: memory.into(),
sender: resources.event_sender(),
worker,
},
@@ -970,7 +970,7 @@ fn add_device_puts_each_device_in_its_own_slot() {
let workers = VirtioWorkers::new(events.sender()).unwrap();
let mut controls = crate::control::ControlRegistry::default();
let ctx = DeviceContext {
- memory: &memory,
+ memory: &memory.clone().into(),
workers: &workers,
controls: &mut controls,
};
diff --git a/src/vmm/tests/virtio/mod.rs b/src/vmm/tests/virtio/mod.rs
index 0b5f954e6..730c04ab3 100644
--- a/src/vmm/tests/virtio/mod.rs
+++ b/src/vmm/tests/virtio/mod.rs
@@ -12,6 +12,7 @@ use std::{
atomic::{AtomicU8, AtomicU32, AtomicUsize, Ordering},
},
};
+use vm_memory::GuestAddressSpace as _;
use mio::{Interest, Registry, Token, event::Source};
use virtio_queue::{Queue, QueueT};
@@ -208,11 +209,11 @@ fn activation_with(events: Arc<dyn EventRegistrar>, waker: Waker) -> ActivationC
&[8],
false,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
ActivationContext {
- memory,
+ memory: memory.into(),
queues,
interrupt: Arc::new(TestInterrupt::default()),
events,
@@ -278,7 +279,7 @@ fn activation_takes_the_context_and_reset_clears_it() {
assert_eq!(ctx.queues.len(), 1);
assert_eq!(ctx.queues.max_size(0), Some(8));
assert!(!ctx.queues.is_ready(0));
- assert_eq!(ctx.memory.iter().count(), 1);
+ assert_eq!(ctx.memory.memory().iter().count(), 1);
ctx.interrupt.raise();
assert_eq!(ctx.interrupt.interrupt_status(), 0x1);
ctx.interrupt.raise_config();
diff --git a/src/vmm/tests/virtio/queue.rs b/src/vmm/tests/virtio/queue.rs
index ebd428208..1375cdf23 100644
--- a/src/vmm/tests/virtio/queue.rs
+++ b/src/vmm/tests/virtio/queue.rs
@@ -76,7 +76,7 @@ fn prepared(
&[SIZE],
event_idx,
indirect,
- Arc::clone(memory),
+ Arc::clone(memory).into(),
)
.unwrap()
}
@@ -157,7 +157,7 @@ fn prepare_accepts_a_dense_ready_queue() {
&[SIZE],
true,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
let state = queues.state(0).expect("queue 0 exists");
@@ -177,7 +177,7 @@ fn prepare_requires_one_queue_per_slot() {
&[SIZE, SIZE],
false,
false,
- Arc::clone(&memory)
+ Arc::clone(&memory).into()
)
.err(),
Some(QueueError::Count {
@@ -196,7 +196,7 @@ fn prepare_checks_each_slot_max_size() {
&[SIZE],
false,
false,
- Arc::clone(&memory)
+ Arc::clone(&memory).into()
)
.err(),
Some(QueueError::MaxSize {
@@ -214,7 +214,7 @@ fn prepare_keeps_unready_queues_but_applies_event_idx() {
&[SIZE],
true,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
assert!(!queues.is_ready(0));
@@ -227,7 +227,14 @@ fn prepare_rejects_a_zero_avail_ring() {
let mut queue = ready_queue();
queue.try_set_avail_ring_address(GuestAddress(0)).unwrap();
assert_eq!(
- VirtQueues::prepare(vec![queue], &[SIZE], false, false, Arc::clone(&memory)).err(),
+ VirtQueues::prepare(
+ vec![queue],
+ &[SIZE],
+ false,
+ false,
+ Arc::clone(&memory).into()
+ )
+ .err(),
Some(QueueError::Invalid)
);
}
@@ -240,7 +247,14 @@ fn prepare_rejects_rings_outside_memory() {
.try_set_used_ring_address(GuestAddress(0x1_0000))
.unwrap();
assert_eq!(
- VirtQueues::prepare(vec![queue], &[SIZE], false, false, Arc::clone(&memory)).err(),
+ VirtQueues::prepare(
+ vec![queue],
+ &[SIZE],
+ false,
+ false,
+ Arc::clone(&memory).into()
+ )
+ .err(),
Some(QueueError::Memory)
);
}
@@ -252,8 +266,14 @@ fn prepare_reapplies_event_idx_after_reset() {
queue.set_event_idx(true);
queue.reset();
assert!(!queue.event_idx_enabled());
- let queues =
- VirtQueues::prepare(vec![queue], &[SIZE], true, false, Arc::clone(&memory)).unwrap();
+ let queues = VirtQueues::prepare(
+ vec![queue],
+ &[SIZE],
+ true,
+ false,
+ Arc::clone(&memory).into(),
+ )
+ .unwrap();
assert!(queues.state(0).unwrap().event_idx_enabled);
}
@@ -646,7 +666,7 @@ fn complete_rejects_a_completion_on_the_wrong_queue() {
&[SIZE, SIZE],
false,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
write_desc(&memory, 0, DATA, 4, 0, 0);
@@ -707,7 +727,7 @@ fn dense_multi_queue_indices_are_preserved() {
&[SIZE, SIZE],
false,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
assert_eq!(queues.len(), 2);
@@ -745,7 +765,7 @@ fn drain_and_complete_reject_a_not_ready_queue() {
&[SIZE],
false,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
assert_eq!(
@@ -790,11 +810,11 @@ fn restore_reports_snapshots_unsupported() {
.state(0)
.unwrap();
assert_eq!(
- VirtQueues::restore(&[state], &[SIZE], false, false, Arc::clone(&memory)).err(),
+ VirtQueues::restore(&[state], &[SIZE], false, false, Arc::clone(&memory).into()).err(),
Some(SnapshotError::Unsupported)
);
assert_eq!(
- VirtQueues::restore(&[], &[SIZE], false, false, Arc::clone(&memory)).err(),
+ VirtQueues::restore(&[], &[SIZE], false, false, Arc::clone(&memory).into()).err(),
Some(SnapshotError::Unsupported)
);
}
@@ -824,7 +844,7 @@ fn control_ranges_use_actual_sizes_include_events_and_skip_unready_slots() {
&[SIZE; 3],
false,
false,
- Arc::clone(&memory),
+ Arc::clone(&memory).into(),
)
.unwrap();
assert_eq!(
@@ -839,3 +859,71 @@ fn control_ranges_use_actual_sizes_include_events_and_skip_unready_slots() {
]
);
}
+
+/// Guest address of a region published only after the queues were prepared.
+const HOTPLUG: u64 = 0x10_0000;
+
+fn hotplug_region() -> Arc<vm_memory::GuestRegionMmap> {
+ Arc::new(vm_memory::GuestRegionMmap::from_range(GuestAddress(HOTPLUG), 0x1000, None).unwrap())
+}
+
+/// Drains one chain whose single descriptor reads four bytes at `HOTPLUG`,
+/// and returns the callback's read result.
+fn drain_hotplug_read(
+ queues: &mut VirtQueues,
+ memory: &GuestMemoryMmap,
+) -> Result<Result<[u8; 4], ()>, DeviceError> {
+ write_desc(memory, 0, HOTPLUG, 4, 0, 0);
+ add_chain(memory, 0);
+ let mut read = Err(());
+ queues
+ .drain(0, |chain| {
+ let mut bytes = [0; 4];
+ read = chain
+ .memory()
+ .read_slice(&mut bytes, GuestAddress(HOTPLUG))
+ .map(|()| bytes)
+ .map_err(|_| ());
+ match read {
+ Ok(_) => Ok(Completion::Used(0)),
+ Err(()) => Err(DeviceError::NeedsReset("unmapped descriptor")),
+ }
+ })
+ .map(|_| read)
+}
+
+#[test]
+fn drain_sees_a_region_published_after_prepare() {
+ let base = memory();
+ let view = crate::memory::GuestMemoryView::from(Arc::clone(&base));
+ let mut queues =
+ VirtQueues::prepare(vec![ready_queue()], &[SIZE], false, false, view.clone()).unwrap();
+
+ let grown = Arc::new(base.insert_region(hotplug_region()).unwrap());
+ grown.write_slice(b"plug", GuestAddress(HOTPLUG)).unwrap();
+ view.lock().unwrap().replace(GuestMemoryMmap::clone(&grown));
+
+ assert_eq!(
+ drain_hotplug_read(&mut queues, &base).unwrap(),
+ Ok(*b"plug")
+ );
+ assert_eq!(used_idx(&base), 1);
+}
+
+#[test]
+fn drain_rejects_a_region_removed_after_prepare() {
+ let base = memory();
+ let grown = Arc::new(base.insert_region(hotplug_region()).unwrap());
+ let view = crate::memory::GuestMemoryView::from(Arc::clone(&grown));
+ let mut queues =
+ VirtQueues::prepare(vec![ready_queue()], &[SIZE], false, false, view.clone()).unwrap();
+
+ let (shrunk, _removed) = grown.remove_region(GuestAddress(HOTPLUG), 0x1000).unwrap();
+ view.lock().unwrap().replace(shrunk);
+
+ assert_eq!(
+ drain_hotplug_read(&mut queues, &base),
+ Err(DeviceError::NeedsReset("unmapped descriptor"))
+ );
+ assert_eq!(used_idx(&base), 0);
+}
diff --git a/src/vmm/tests/virtio/worker.rs b/src/vmm/tests/virtio/worker.rs
index 42160db9b..effcbaa99 100644
--- a/src/vmm/tests/virtio/worker.rs
+++ b/src/vmm/tests/virtio/worker.rs
@@ -372,9 +372,10 @@ fn activation(
) -> ActivationContext {
let memory = Arc::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap());
let queues = QUEUES.iter().map(|&max| Queue::new(max).unwrap()).collect();
- let queues = VirtQueues::prepare(queues, QUEUES, false, false, Arc::clone(&memory)).unwrap();
+ let queues =
+ VirtQueues::prepare(queues, QUEUES, false, false, Arc::clone(&memory).into()).unwrap();
ActivationContext {
- memory,
+ memory: memory.into(),
queues,
interrupt,
events: worker.events,
@@ -1296,7 +1297,8 @@ fn a_fake_runtime_drives_the_transport() {
shared,
interrupt,
MmioResources {
- memory: Arc::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap()),
+ memory: Arc::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap())
+ .into(),
sender: events.sender(),
worker,
},
@@ -1335,7 +1337,8 @@ fn transport(dev: &Dev) -> MmioTransport {
device,
Arc::clone(&dev.interrupt),
MmioResources {
- memory: Arc::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap()),
+ memory: Arc::new(GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap())
+ .into(),
sender: dev.sender.clone(),
worker: Arc::clone(&dev.worker),
},
diff --git a/src/vmm/tests/virtio_console/mod.rs b/src/vmm/tests/virtio_console/mod.rs
index b8b58d91e..244699a21 100644
--- a/src/vmm/tests/virtio_console/mod.rs
+++ b/src/vmm/tests/virtio_console/mod.rs
@@ -192,11 +192,16 @@ impl Guest {
fn activation_with(&self, queues: Vec<Queue>, event_idx: bool) -> ActivationContext {
let maxima = vec![MAX_SIZE; queues.len()];
- let queues =
- VirtQueues::prepare(queues, &maxima, event_idx, false, Arc::clone(&self.memory))
- .unwrap();
+ let queues = VirtQueues::prepare(
+ queues,
+ &maxima,
+ event_idx,
+ false,
+ Arc::clone(&self.memory).into(),
+ )
+ .unwrap();
ActivationContext {
- memory: Arc::clone(&self.memory),
+ memory: Arc::clone(&self.memory).into(),
queues,
interrupt: self.interrupt.clone(),
events: Arc::new(Registrar),
diff --git a/src/vmm/tests/virtio_console/transport.rs b/src/vmm/tests/virtio_console/transport.rs
index 9613481db..4be5a187b 100644
--- a/src/vmm/tests/virtio_console/transport.rs
+++ b/src/vmm/tests/virtio_console/transport.rs
@@ -108,7 +108,7 @@ fn the_transport_discovers_tx_only_console_and_resets_it() {
Arc::clone(&device),
Arc::clone(&interrupt),
MmioResources {
- memory: Arc::clone(&memory),
+ memory: Arc::clone(&memory).into(),
sender: events.sender(),
worker: Arc::clone(&worker) as Arc<dyn WorkerControl>,
},
diff --git a/src/vmm/tests/vm/mod.rs b/src/vmm/tests/vm/mod.rs
index c99451d5a..e462d71e4 100644
--- a/src/vmm/tests/vm/mod.rs
+++ b/src/vmm/tests/vm/mod.rs
@@ -18,7 +18,7 @@ use std::{
use boxlite_hypervisor::{Error as HypervisorError, MemoryRegion, Vm as HostVm};
use tracing::{Event, Level, Metadata, Subscriber, field::Field, span};
-use vm_memory::{GuestAddress, GuestMemoryBackend};
+use vm_memory::{GuestAddress, GuestAddressSpace, GuestMemoryBackend};
use super::{BootRegisters, Vm};
use crate::{
@@ -100,7 +100,7 @@ fn maps_the_ram_layout_with_its_host_address_and_unmaps_on_drop() {
panic!("one region")
};
assert_eq!(start.0, RAM_START);
- let host_addr = vm.ram.memory().get_host_address(start).unwrap() as usize;
+ let host_addr = vm.ram.memory().memory().get_host_address(start).unwrap() as usize;
let map = Call::Map {
guest_addr: start.0,
host_addr,
@@ -126,7 +126,7 @@ fn blocked_fs_shutdown_keeps_vm_ram_registered_until_retry_and_drop() {
let mut vm = bare(config(1, 16), || Ok(MockVm::new())).unwrap();
let log = vm.host_vm.as_deref().unwrap().log();
- let memory = Arc::downgrade(vm.ram.memory());
+ let memory = Arc::downgrade(vm.ram.boot_memory());
vm.workers = Some(VirtioWorkers::with_runtime(Arc::new(
SharedRuntime::new(
vm.sender.clone(),
@@ -139,7 +139,7 @@ fn blocked_fs_shutdown_keeps_vm_ram_registered_until_retry_and_drop() {
)));
let workers = vm.workers.as_ref().unwrap();
crate::virtio::fs::worker_tests::with_blocked_vm_read(
- vm.ram.memory().clone(),
+ vm.ram.boot_memory().clone(),
workers,
&vm.events.lock().unwrap(),
|release| {
@@ -183,7 +183,7 @@ fn dropping_vm_during_blocked_fs_keeps_registration_and_backing() {
let mut vm = bare(config(1, 1), || Ok(MockVm::new())).unwrap();
let log = vm.host_vm.as_deref().unwrap().log();
- let memory = vm.ram.memory().clone();
+ let memory = vm.ram.boot_memory().clone();
let backing = Arc::downgrade(&memory);
let events = EventLoop::new().unwrap();
let runtime = Arc::new(
@@ -235,9 +235,10 @@ fn a_rejected_vm_mapping_releases_the_backing() {
|_, ctx| {
let host_addr = ctx
.memory
+ .memory()
.get_host_address(GuestAddress(RAM_START))
.unwrap() as usize;
- backing = Some((Arc::downgrade(ctx.memory), host_addr));
+ backing = Some((Arc::downgrade(&ctx.memory.memory().into_inner()), host_addr));
Ok(())
},
)
@@ -417,7 +418,9 @@ fn failed_vm_mapping_releases_backing_after_failed_rollback() {
},
|_, _| panic!("a rejected map must not reach boot"),
|chipset, ctx| {
- backing.set(Arc::downgrade(ctx.memory)).unwrap();
+ backing
+ .set(Arc::downgrade(&ctx.memory.memory().into_inner()))
+ .unwrap();
// The device's interrupt line holds a strong reference to the host VM.
chipset.add("device", |resources| {
Ok(MappingTestDevice {
@@ -463,7 +466,7 @@ fn failed_boot_keeps_backing_while_an_irq_line_owns_the_host_vm() {
let mut irq = None;
let error = with_fresh_backend(config(1, 16), backend, failed_boot, |chipset, ctx| {
- backing = Some(Arc::downgrade(ctx.memory));
+ backing = Some(Arc::downgrade(&ctx.memory.memory().into_inner()));
chipset.add("device", |resources| {
irq = Some(resources.line(4));
Ok(MappingTestDevice { _irq: None })
@@ -491,7 +494,7 @@ fn failed_boot_keeps_backing_without_a_fresh_backend() {
|| Ok(backend),
failed_boot,
|_, ctx| {
- backing = Some(Arc::downgrade(ctx.memory));
+ backing = Some(Arc::downgrade(&ctx.memory.memory().into_inner()));
Ok(())
},
)
@@ -603,7 +606,9 @@ fn failed_boot_releases_backing_after_failed_unmap() {
let (result, warnings) = capture_warnings(|| {
with_fresh_backend(config(1, 16), backend, failed_boot, |_, ctx| {
- backing.set(Arc::downgrade(ctx.memory)).unwrap();
+ backing
+ .set(Arc::downgrade(&ctx.memory.memory().into_inner()))
+ .unwrap();
Ok(())
})
});
@@ -683,7 +688,7 @@ fn failed_boot_keeps_registration_and_backing_when_workers_fail_to_join() {
|_| Ok(VirtioWorkers::with_runtime(runtime.clone())),
failed_boot,
|_, ctx, _| {
- backing = Some(Arc::downgrade(ctx.memory));
+ backing = Some(Arc::downgrade(&ctx.memory.memory().into_inner()));
Ok(())
},
)
@@ -721,7 +726,9 @@ fn panicking_boot_unmaps_ram_and_releases_backing_after_host_vm_closes() {
backend,
|_, _| panic!("boot panic"),
|chipset, ctx| {
- backing.set(Arc::downgrade(ctx.memory)).unwrap();
+ backing
+ .set(Arc::downgrade(&ctx.memory.memory().into_inner()))
+ .unwrap();
chipset.add("device", |resources| {
Ok(MappingTestDevice {
_irq: Some(resources.line(4)),
@@ -821,7 +828,7 @@ fn a_kvm_guest_reads_the_last_byte_of_the_mapped_layout() {
let prepared = KvmVm::prepare().unwrap();
preflight_x86(config.memory_mib, prepared.supported_cpuid(), BOOT_LEAF).unwrap();
let vm = bare(config, move || KvmVm::from_prepared(prepared)).unwrap();
- let memory = Arc::clone(vm.ram.memory());
+ let memory = Arc::clone(vm.ram.boot_memory());
let last = GuestAddress(MMIO_HOLE_START - 1);
// mov al,[0xBFFFFFFF]; mov dx,0x3f8; out dx,al; hlt
let program = [
@@ -969,7 +976,7 @@ fn a_kvm_guest_runs_64_bit_code_with_the_boot_cpu_state() {
let prepared = KvmVm::prepare().unwrap();
let leaf = preflight_x86(config.memory_mib, prepared.supported_cpuid(), BOOT_LEAF).unwrap();
let vm = bare(config, move || KvmVm::from_prepared(prepared)).unwrap();
- let memory = Arc::clone(vm.ram.memory());
+ let memory = Arc::clone(vm.ram.boot_memory());
memory.write_slice(&program, GuestAddress(ENTRY)).unwrap();
memory
.write_obj(PARAMS_MARKER, GuestAddress(BOOT_PARAMS))
@@ -1463,7 +1470,7 @@ mod lifecycle {
|| Ok(MockVm::with_scripts(vec![driver()])),
|_, _| Ok(BootRegisters::default()),
|chipset, ctx| {
- memory = Some(Arc::downgrade(ctx.memory));
+ memory = Some(Arc::downgrade(&ctx.memory.memory().into_inner()));
add(chipset, ctx, ResetOnKick::shared(Box::new(|| {})))
},
)
@@ -1520,6 +1527,7 @@ mod lifecycle {
assert_eq!(*sink.0.lock().unwrap(), b"final");
assert_eq!(
vm.ram
+ .memory()
.memory()
.read_obj::<u16>(GuestAddress(0x3002))
.unwrap(),
@@ -1533,7 +1541,7 @@ mod lifecycle {
// A writable TX descriptor is rejected by the final scan.
let (vm, sink) = console_vm(2, step);
let log = vm.host_vm.as_deref().unwrap().log();
- let memory = Arc::downgrade(vm.ram.memory());
+ let memory = Arc::downgrade(vm.ram.boot_memory());
let (exit, vm) = run(vm);
let error = exit.unwrap_err();
if clean {
@@ -1609,12 +1617,15 @@ mod lifecycle {
|_, _| Ok(BootRegisters::default()),
|chipset, ctx| {
ctx.memory
+ .memory()
.write_slice(b"final", GuestAddress(0x4000))
.unwrap();
ctx.memory
+ .memory()
.write_obj(Descriptor::new(0x4000, 5, flags, 0), GuestAddress(0x1000))
.unwrap();
ctx.memory
+ .memory()
.write_obj(1u16.to_le(), GuestAddress(0x2002))
.unwrap();
add(chipset, ctx, console)
@@ -1755,7 +1766,7 @@ fn a_kvm_vm_runs_until_its_guest_resets() {
let mut vm = Vm::with_backend(
config(2, 2),
boxlite_hypervisor::KvmVm::new,
- |ram, _| Ok(flat_guest::load(ram.memory(), &program)),
+ |ram, _| Ok(flat_guest::load(&ram.memory().memory(), &program)),
|chipset, _| {
chipset.add("i8042", |resources| {
resources.pio(0x64, 1);
diff --git a/src/vmm/tests/vsock/mod.rs b/src/vmm/tests/vsock/mod.rs
index 96abbf2b7..b04b2c048 100644
--- a/src/vmm/tests/vsock/mod.rs
+++ b/src/vmm/tests/vsock/mod.rs
@@ -236,13 +236,13 @@ impl Harness {
fn context(&self) -> ActivationContext {
let wakes = self.wakes.clone();
ActivationContext {
- memory: self.memory.clone(),
+ memory: self.memory.clone().into(),
queues: crate::virtio::queue::VirtQueues::prepare(
vec![self.rx.queue(), self.tx.queue(), Driver::new(2).queue()],
&[256, 256, 256],
false,
false,
- self.memory.clone(),
+ self.memory.clone().into(),
)
.unwrap(),
interrupt: self.interrupt.clone(),
@@ -817,7 +817,7 @@ impl TransportHarness {
device.clone(),
interrupt,
crate::virtio::mmio::MmioResources {
- memory: memory.clone(),
+ memory: memory.clone().into(),
sender: events.sender(),
worker,
},
@@ -1119,7 +1119,7 @@ fn activation_requires_three_ready_queues_and_preserves_the_active_backend() {
&[256; 3],
false,
false,
- h.memory.clone(),
+ h.memory.clone().into(),
)
.unwrap();
assert!(matches!(
@@ -1134,7 +1134,7 @@ fn activation_requires_three_ready_queues_and_preserves_the_active_backend() {
&[256; 2],
false,
false,
- h.memory.clone(),
+ h.memory.clone().into(),
)
.unwrap();
assert!(matches!(