diff --git a/CHANGELOG.md b/CHANGELOG.md index e4c94cada..f54b438a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). contents. Callers must keep blobs immutable. Use the new `Snapshot::checked_save` to recompute hashes, verify existing blobs, and atomically repair mismatched contents. +* **Breaking:** Snapshots use ABI 12. Guests must be rebuilt and existing + snapshots regenerated. Capture and restore provide full H2G bootstrap + capacity before guest entry, independent of retained buffers. Snapshot + capture runs on the host while the guest is stopped. + The checkpoint request, `prepare_snapshot`, and + `VirtqProducer::reclaim_slots` APIs are removed. * `Snapshot::save` no longer synchronously flushes files to stable storage. Callers requiring power-loss durability must sync the snapshot files and directory hierarchy themselves after saving. diff --git a/docs/snapshot-oci-format.md b/docs/snapshot-oci-format.md index 9d7319516..4dba1e38e 100644 --- a/docs/snapshot-oci-format.md +++ b/docs/snapshot-oci-format.md @@ -49,7 +49,7 @@ Four blob kinds per tag: binary image of the canonical G2H and H2G rings. Loading checks ring sizes and canonical state against the config. -The runtime queue protocol and canonical checkpoint are described in +The runtime queue protocol and snapshot bootstrap state are described in [Virtqueue host and guest communication](./virtio-host-guest-communication.md). Manifest layers are ordered data, then transport. diff --git a/docs/snapshot-versioning.md b/docs/snapshot-versioning.md index cca22ebc2..c4d9b884a 100644 --- a/docs/snapshot-versioning.md +++ b/docs/snapshot-versioning.md @@ -59,6 +59,12 @@ host page size, and log level. Earlier snapshots must be regenerated. ABI 11 encodes control data with postcard and carries its length in a 16-byte message header. Earlier snapshots must be regenerated. +ABI 12 stores deterministic queue bootstrap images. Capture and restore install +empty G2H and fully prefilled H2G rings. Guest entry reconstructs ownership +without changing host-written data. The mailbox reports initialization readiness. +Snapshot capture runs on the host while the guest is stopped. Earlier snapshots +must be regenerated. + The `OCI_LAYOUT_VERSION` constant is pinned by the OCI image-layout spec at `1.0.0`. diff --git a/docs/virtio-host-guest-communication.md b/docs/virtio-host-guest-communication.md index c89479604..d03d5c677 100644 --- a/docs/virtio-host-guest-communication.md +++ b/docs/virtio-host-guest-communication.md @@ -169,14 +169,16 @@ On the first VM entry, the guest: 2. Reconstructs `TransportArena`. 3. Converts each transport GPA into its scratch GVA. 4. Constructs a `GuestContext` and installs it with `set_global_context`. - H2G receives one writable descriptor per available slot, bounded by queue size. + Both rings are initialized empty. H2G receives one writable descriptor per + available slot, bounded by queue size. Dispatch starts with `transport::maybe_refresh`, before logging or tracing. Runtime operations borrow the context through `transport::with_ctx`. After user initialization and trace flushing, the guest calls -`transport::prepare_snapshot`, then halts. The host resets its consumers and -requires `MailboxValue::CheckpointComplete`. Initial snapshots include values +`transport::complete_initialization`, then halts. The host requires +`MailboxValue::InitComplete`. Both sides keep their queue cursors so traffic +during initialization remains valid. Initial snapshots include values retained during initialization. ## Wire format @@ -201,16 +203,14 @@ Every logical message has this byte layout: `payload_len` covers the control data and all external bytes. `control_len` covers the control data and never exceeds `payload_len`. The host reads it first so it can copy exactly the control data out of guest memory in one read -before parsing. RPC correlation -IDs are nonzero. Responses echo the request ID. Logs and snapshot checkpoints -use ID zero. +before parsing. Request IDs are nonzero. Responses echo the request ID. +Logs use ID zero. The active message kinds are: * `Request` * `Response` * `Log` -* `SnapshotCheckpoint` The control data holds the typed function call or result and the lengths of external byte values. It is one [postcard](https://docs.rs/postcard) value. @@ -389,23 +389,18 @@ external `ByteChunks`: * The final owner unmaps its alias and returns the virtual range for reuse. Its lease releases the slot in its original pool. -Producer reset releases allocations still owned by queue bookkeeping. After -both producers reset and before H2G prefill, every live pool slot belongs to -guest retained `Bytes`. H2G prefills free slots up to the queue size. - -Checkpoint preparation requires stopped host consumers with no live chain -handles. The host resets both consumers before processing more queue traffic. - ### Retained virtual addresses Both pools share one guest-global alias allocator. Its state is captured with -the mappings and keeps retained ranges reserved across pool swaps. +the mappings and keeps retained ranges reserved across transport generations. Each completed `GuestMapping` owns a separate page-aligned range. Mapping occurs when the guest receives the buffer. Capture, restore, and cloning preserve its pointer and contents. -Retained aliases reach captured memory after restore. The first transport -entry swaps allocators that hold retained slots, preserving posted reservations. +Capture installs independent backing for retained aliases in the source sandbox +and in restored sandboxes. The first transport entry in each generation +refreshes both producers in place. Private bookkeeping storage is reused with +fresh pools. Retained leases keep their original pools, so their release cannot free slots in the new pool. Retained values keep their aliases until their final owner drops. Reusing @@ -423,56 +418,46 @@ lengths as untrusted. size before the host writes to them. * G2H control and external values are copied into host owned storage before host code receives them. -* Capture and load require the canonical transport state described below. +* Loaded ring images must match the deterministic bootstrap state described below. -## Snapshot checkpoint +## Snapshot capture The transport arena lives in scratch and is not captured as ordinary guest memory. Guest producer and pool bookkeeping is normal guest state, while ring -and pool bytes live in scratch. Snapshot capture needs a canonical transport -state. Retained aliases map live payload pages outside the scratch map, so -capture copies them as ordinary memory. +and pool bytes live in scratch. Capture prepares deterministic bootstrap images +without reading the live rings. Retained aliases map live payload pages outside +the scratch map, so capture copies them as ordinary memory. -`Sandbox` tracks whether queue traffic occurred after the last -canonical boundary. A cached or clean snapshot needs no VM entry. A dirty -snapshot uses this flow: +Capture requires a stopped VM with no unfinished guest calls or live host +chain handles. It runs entirely on the host. An unchanged sandbox can reuse +its cached snapshot. Building a fresh snapshot follows this flow: ```text - Host Guest + Host Guest (stopped) | | - | mailbox = CheckpointPending | - | H2G SnapshotCheckpoint ------------>| - | enter VM | - | | reclaim completed G2H work - | | reset G2H producer - | | reset H2G producer - | | prefill free H2G slots - | | mailbox = CheckpointComplete - |<------------------------------------| halt - | reset both consumers | - | require CheckpointComplete | - | read and validate ring images | - | capture memory | + | prepare bootstrap images | + | capture memory and retained data | + | install captured memory | + | install bootstrap rings | + | attach fresh host consumers | ``` -Checkpoint preparation keeps retained leases and aliases intact without -payload copying. Capture leaves the source queues and allocator ready for -continued use, including when memory capture fails. +Bootstrap images stay separate from live scratch until memory +capture succeeds. A failed memory capture leaves the source transport usable. -The canonical state is: +The bootstrap state is: * G2H is empty at cursor zero. -* H2G starts at cursor zero with one writable descriptor per free slot, - bounded by queue size. Each descriptor names a distinct, configured-size - slot aligned relative to the pool start. Available descriptors form a prefix - followed by zeroed descriptors. -* Guest producer and pool bookkeeping matches the rings and current leases. -* Driver and device event suppression is normalized. +* H2G starts at cursor zero with one writable descriptor per configured pool + slot, bounded by queue size. Descriptor IDs and buffer addresses follow + fresh allocation order. Unposted descriptors are zero. +* Driver and device notifications are enabled at offset zero. * Host consumers start at cursor zero. -The snapshot stores normal guest memory plus the two canonical ring images. -Construction and loading validate the ring images against the finalized -layout. The layout and copied ring images remain immutable. +The snapshot stores normal guest memory plus the two generated ring images. +Loading requires an exact match to the shared initializer for the finalized +layout. Partial prefill and reordered IDs or buffers are rejected. +The layout and ring images remain immutable. The OCI representation places ring images in the [transport layer](./snapshot-oci-format.md). Retained payloads use the ordinary memory layer through their aliases. The mailbox and host consumer cursors are @@ -480,36 +465,42 @@ not stored. ### Restore -Capture and load validate ring lengths and canonical transport state against -the layout. Load also checks the scratch size the transport blob records. +Load validates ring lengths and bootstrap state against the layout. It also +checks the scratch size the transport blob records. Admitted images and their layout remain immutable. Transport admission precedes changes to sandbox status, the cached snapshot, and memory mappings. -Restore writes the arena GPA metadata, a `CheckpointComplete` mailbox value, +Restore writes the arena GPA metadata, an `InitComplete` mailbox value, and both ring images into fresh scratch. It attaches new host consumers at -cursor zero. Normal guest memory restores the matching producers, pools, -leases, and aliases. +cursor zero. Normal guest memory restores the captured producers, pools, +leases, and aliases. The first entry in the new generation refreshes producer +bookkeeping in place with fresh pools. Initialized `restore` and `from_snapshot` are ready for the first H2G request before guest entry. Pre-initialization snapshots use normal guest startup. -The first request after restore must fit the H2G capacity posted at checkpoint. -Retained buffers can reduce this prefill if their leases still belong to the -current pool generation. Buffers from retired generations do not consume current -pool slots. Framing, slot rounding, ring size, and the external-byte control -reserve still apply. +The first request can use the full configured H2G bootstrap capacity, regardless +of retained buffers. Framing, slot rounding, ring size, and the external-byte +control reserve still apply. -The first transport entry after restore recycles slots held by captured -leases. Posted chains keep their reservations, preserving the submitted -request. Descriptors and cursors stay unchanged. Retained aliases keep their -captured mappings without payload copying. +Guest entry uses `VirtqProducer::refresh` for both queues before +logging or receiving. `BootstrapInfo` holds a `PoolLayout` and an initial posted count. +`SlotPool::layout()` supplies geometry independent of live allocations. +Reconstruction uses bootstrap capacities, not consumer-written lengths. +Host completions and payloads stay untouched. Producers prepare fresh pool +reservations and private table capacity before releasing old queue-owned records. +Retained aliases keep their captured mappings and original leases. +Guest execution cannot resume if either producer refresh fails. -Source continuation keeps the pool instances and live scratch leases intact. -Checkpointing alone does not detach retained payloads from scratch. +Successful capture installs the same bootstrap in the source sandbox, including +when scratch size stays the same. Source continuation uses the same generation +transition as restore and cloning. Ordinary entries within a generation keep +their active queues. -Result completion prefills free H2G slots. This requires no preparatory guest -entry or application warmup for the checkpoint-posted capacity. +Result completion prefills free H2G slots. Retention within a generation still +occupies pool slots. Full bootstrap capacity requires no preparatory guest entry +or application warmup after capture or restore. ## Transport mailbox @@ -518,16 +509,14 @@ alignment gap. It is outside both rings and pools. Both sides derive its address from trusted arena geometry. The host accesses it before VM entry and after guest halt. -The mailbox avoids a G2H checkpoint response. G2H can remain empty in the -canonical image even when retained G2H slots reduce available capacity. +The mailbox reports initialization readiness without a G2H response. -Before a dirty checkpoint, the host writes `CheckpointPending`. -The guest writes `CheckpointComplete` after producer reset and free-slot H2G prefill. -The host reads the value after a successful guest halt and after resetting -both consumers. +Before initialization, the host writes `InitPending`. The guest writes +`InitComplete` after user initialization and trace flushing. The host reads +the value after a successful guest halt. Queue cursors remain unchanged. -* `CheckpointPending` (`0`) is a fatal incomplete checkpoint. -* `CheckpointComplete` (`1`) permits snapshot capture. +* `InitPending` (`0`) is a fatal incomplete initialization. +* `InitComplete` (`1`) permits normal guest calls. * Every other value is a fatal invalid status. ## Placement and relocation limitations diff --git a/src/hyperlight_common/src/layout.rs b/src/hyperlight_common/src/layout.rs index 731f73fe9..1b9efa142 100644 --- a/src/hyperlight_common/src/layout.rs +++ b/src/hyperlight_common/src/layout.rs @@ -209,7 +209,7 @@ impl QueueDims { } } -/// Addresses of both rings, the checkpoint mailbox, and pools in one fixed arena. +/// Addresses of both rings, the initialization mailbox, and pools in one fixed arena. /// /// The G2H ring begins at the arena base. The H2G ring is descriptor aligned. /// The mailbox is `u64` aligned. Both pools are page aligned. @@ -225,7 +225,7 @@ pub struct TransportArena { g2h_ring_addr: u64, /// Address of the H2G ring. h2g_ring_addr: u64, - /// Address of the snapshot checkpoint mailbox. + /// Address of the initialization mailbox. mbx_addr: u64, /// Address of the G2H pool. g2h_pool_addr: u64, @@ -291,12 +291,12 @@ impl TransportArena { self.h2g_ring_addr } - /// Address of the snapshot checkpoint mailbox. + /// Address of the initialization mailbox. pub const fn mbx_addr(&self) -> u64 { self.mbx_addr } - /// Byte offset of the snapshot checkpoint mailbox from the arena base. + /// Byte offset of the initialization mailbox from the arena base. pub const fn mbx_offset(&self) -> usize { // `new` proves this difference is nonnegative and fits in `usize`. (self.mbx_addr - self.g2h_ring_addr) as usize diff --git a/src/hyperlight_common/src/transport.rs b/src/hyperlight_common/src/transport.rs index b76d401e1..eb7d2da4e 100644 --- a/src/hyperlight_common/src/transport.rs +++ b/src/hyperlight_common/src/transport.rs @@ -31,8 +31,6 @@ pub enum MsgKind { Cancel = 0x05, /// A guest log message (GuestLogData payload follows). Log = 0x06, - /// Internal request to prepare canonical transport state for snapshotting. - SnapshotCheckpoint = 0x07, } impl TryFrom for MsgKind { @@ -46,7 +44,6 @@ impl TryFrom for MsgKind { 0x04 => Ok(Self::StreamEnd), 0x05 => Ok(Self::Cancel), 0x06 => Ok(Self::Log), - 0x07 => Ok(Self::SnapshotCheckpoint), other => Err(other), } } @@ -56,10 +53,10 @@ impl TryFrom for MsgKind { #[repr(u64)] #[derive(Debug, Clone, Copy, PartialEq, Eq, bytemuck::CheckedBitPattern, bytemuck::NoUninit)] pub enum MailboxValue { - /// Guest preparation is outstanding. - CheckpointPending = 0, - /// Both queues are reset and free H2G slots are prefilled. - CheckpointComplete = 1, + /// Guest initialization is outstanding. + InitPending = 0, + /// Guest initialization has completed. + InitComplete = 1, } impl MailboxValue { @@ -79,8 +76,8 @@ impl TryFrom for MailboxValue { fn try_from(value: u64) -> Result { match value { - 0 => Ok(Self::CheckpointPending), - 1 => Ok(Self::CheckpointComplete), + 0 => Ok(Self::InitPending), + 1 => Ok(Self::InitComplete), other => Err(other), } } @@ -159,19 +156,6 @@ impl<'a> EncodedMessage<'a> { }) } - // Build a snapshot checkpoint message with no payload. - pub fn new_snapshot_cp() -> Self { - let total_len = MsgHeader::SIZE; - let externals = ExternalValues::new(); - - Self { - header: MsgHeader::new(MsgKind::SnapshotCheckpoint, 0, 0, 0), - control: &[], - externals, - total_len, - } - } - /// Borrow the complete wire message as a zero-copy byte cursor. pub fn as_buf(&self) -> impl Buf + '_ { EncodedMessageBuf::new( @@ -460,8 +444,8 @@ mod tests { #[test] fn mailbox_value_wire_contract() { for (value, raw) in [ - (MailboxValue::CheckpointPending, 0u64), - (MailboxValue::CheckpointComplete, 1), + (MailboxValue::InitPending, 0u64), + (MailboxValue::InitComplete, 1), ] { assert_eq!(value.raw(), raw); assert_eq!(value.as_bytes(), raw.to_ne_bytes()); diff --git a/src/hyperlight_common/src/virtq/bootstrap.rs b/src/hyperlight_common/src/virtq/bootstrap.rs new file mode 100644 index 000000000..c1d1c8caf --- /dev/null +++ b/src/hyperlight_common/src/virtq/bootstrap.rs @@ -0,0 +1,245 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +//! Deterministic queue initialization shared by both peers. + +use bytemuck::Zeroable; + +use super::{DescFlags, Descriptor, Layout, MemOps, PoolLayout, RingError, SlotPool, ring}; + +/// Ring and pool geometry for empty or prefilled producer reconstruction. +#[derive(Clone, Copy, Debug)] +pub struct BootstrapInfo { + /// Descriptor table and event-suppression geometry. + layout: Layout, + /// Payload pool geometry. + pool: PoolLayout, + /// Initial prefix of writable single-buffer chains. + posted: u16, +} + +impl BootstrapInfo { + /// Describe an empty ring with all slots in its one- or two-tier pool free. + pub fn empty(layout: Layout, pool: PoolLayout) -> Result { + Self::new(layout, pool, 0) + } + + /// Describe a ring filled with as many slots as its descriptor count permits. + /// + /// Prefill follows lower-first, per-tier allocation order. + pub fn prefilled(layout: Layout, pool: PoolLayout) -> Result { + let posted = pool.slot_count().min(usize::from(layout.desc_table_len())) as u16; + Self::new(layout, pool, posted) + } + + /// Require every pool tier to be disjoint from the ring and its events. + fn new(layout: Layout, pool: PoolLayout, posted: u16) -> Result { + for slots in pool.tiers() { + if slots.base_addr() < layout.end_addr() && layout.desc_table_addr() < slots.end_addr() + { + return Err(RingError::InvalidLayout); + } + } + + Ok(Self { + layout, + pool, + posted, + }) + } + + /// Write descriptors and enable both peers' notifications without touching payloads. + /// + /// Both peers must stay stopped until initialization succeeds. An error can + /// leave a partial image, which must be reinitialized or discarded. + pub fn initialize(&self, mem: &M) -> Result<(), RingError> { + self.layout + .initialize_with(mem, |index| self.desc_at(index)) + } + + /// Number of buffers initially owned by the queue. + pub(crate) const fn avail(&self) -> u16 { + self.posted + } + + /// Original capacity and identity, independent of consumer-written used lengths. + pub(crate) fn desc_at(&self, index: u16) -> Descriptor { + if index >= self.posted { + return Descriptor::zeroed(); + } + + let Some(alloc) = SlotPool::alloc_for(self.pool, index as usize) else { + return Descriptor::zeroed(); + }; + + let desc_cnt = self.layout.desc_table_len(); + let Some(id) = ring::id_for(desc_cnt, index) else { + return Descriptor::zeroed(); + }; + + Descriptor::new( + alloc.addr, + alloc.len, + id, + DescFlags::WRITE | DescFlags::AVAIL, + ) + } + + /// Ring geometry used for initialization. + pub(crate) const fn layout(&self) -> Layout { + self.layout + } + + /// Normalized slot geometry for recreating the initial buffer pool. + pub(crate) const fn pool_layout(&self) -> PoolLayout { + self.pool + } +} + +#[cfg(test)] +mod tests { + use std::assert_matches; + + use super::*; + use crate::virtq::canonical::validate_canon_image; + use crate::virtq::ring::tests::{FaultMem, make_consumer, make_producer, make_ring}; + use crate::virtq::{MemOp, RingProducer, SlotLayout}; + + #[test] + fn bootstrap_matches_fresh_pool_submissions() { + let ring = make_ring(8); + let mem = ring.mem(); + let base = ring.layout().end_addr(); + let slots = SlotLayout::new(base, 64, 3).unwrap(); + let pool = SlotPool::new(slots).unwrap(); + + let mut producer = make_producer(&ring); + let mut consumer = make_consumer(&ring); + let mut expected = alloc::vec::Vec::new(); + + for index in 0..3 { + let alloc = pool.alloc(64).unwrap(); + producer.submit_one(alloc.addr, alloc.len, true).unwrap(); + + expected.push(ring.read_desc(index)); + } + + producer.disable_used_notifications().unwrap(); + consumer.disable_avail_notifications().unwrap(); + + mem.write(base, &[0xa5; 192]).unwrap(); + + BootstrapInfo::prefilled(ring.layout(), pool.layout()) + .unwrap() + .initialize(&mem) + .unwrap(); + + let chains = validate_canon_image(&mem, ring.layout(), 3, |_, elem| { + elem.writable && elem.len == 64 + }) + .unwrap(); + + assert_eq!(chains.len(), 3); + + for (index, desc) in expected.into_iter().enumerate() { + assert_eq!(ring.read_desc(index as u16), desc); + } + + let mut payloads = [0; 192]; + mem.read(base, &mut payloads).unwrap(); + assert_eq!(payloads, [0xa5; 192]); + } + + #[test] + fn empty_bootstrap_clears_descriptors_and_events() { + let ring = make_ring(4); + let slots = SlotLayout::new(ring.layout().end_addr(), 64, 2).unwrap(); + let info = BootstrapInfo::empty(ring.layout(), PoolLayout::single(slots)).unwrap(); + let mut producer = make_producer(&ring); + let mut consumer = make_consumer(&ring); + + producer.submit_one(0x1000, 64, true).unwrap(); + producer.enable_used_notifications_desc(2, false).unwrap(); + consumer.disable_avail_notifications().unwrap(); + + info.initialize(&ring.mem()).unwrap(); + + assert!( + validate_canon_image(&ring.mem(), ring.layout(), 0, |_, _| false) + .unwrap() + .is_empty() + ); + + let mut fresh = make_consumer(&ring); + assert_matches!(fresh.poll_available(), Err(RingError::WouldBlock)); + + let mut restored = RingProducer::from_bootstrap(info, ring.mem()); + + let id = restored.submit_one(0x1000, 64, false).unwrap(); + let (received_id, _) = fresh.poll_available().unwrap(); + + assert_eq!(received_id, id); + } + + #[test] + fn bootstrap_rejects_pool_overlapping_event_storage() { + let ring = make_ring(4); + let slots = SlotLayout::new(ring.layout().dev_evt_addr(), 64, 1).unwrap(); + + assert_matches!( + BootstrapInfo::prefilled(ring.layout(), PoolLayout::single(slots)), + Err(RingError::InvalidLayout) + ); + } + + #[test] + fn empty_bootstrap_rejects_lower_tier_overlapping_events() { + let ring = make_ring(4); + let lower = SlotLayout::new(ring.layout().dev_evt_addr(), 64, 1).unwrap(); + let upper = SlotLayout::new(lower.end_addr(), 128, 1).unwrap(); + let pool = PoolLayout::tiered(lower, upper).unwrap(); + + assert_matches!( + BootstrapInfo::empty(ring.layout(), pool), + Err(RingError::InvalidLayout) + ); + } + + #[test] + fn empty_bootstrap_rejects_upper_tier_overlapping_events() { + let ring = make_ring(4); + let upper = SlotLayout::new(ring.layout().dev_evt_addr(), 64, 1).unwrap(); + + assert_matches!( + BootstrapInfo::empty(ring.layout(), PoolLayout::single(upper)), + Err(RingError::InvalidLayout) + ); + } + + #[test] + fn bootstrap_can_retry_a_failed_write() { + let ring = make_ring(4); + let mem = FaultMem::new(ring.mem()); + let slots = SlotLayout::new(ring.layout().dev_evt_addr() + 0x100, 64, 2).unwrap(); + let info = BootstrapInfo::prefilled(ring.layout(), PoolLayout::single(slots)).unwrap(); + + mem.fail_write_at(5); + + assert_matches!( + info.initialize(&mem), + Err(RingError::MemError { + op: MemOp::WriteDesc, + .. + }) + ); + + mem.allow_writes(); + info.initialize(&mem).unwrap(); + + let len = validate_canon_image(&mem, ring.layout(), 2, |_, _| true) + .unwrap() + .len(); + + assert_eq!(len, 2); + } +} diff --git a/src/hyperlight_common/src/virtq/buffer.rs b/src/hyperlight_common/src/virtq/buffer.rs index cdd08bacc..ff1bdd338 100644 --- a/src/hyperlight_common/src/virtq/buffer.rs +++ b/src/hyperlight_common/src/virtq/buffer.rs @@ -310,7 +310,7 @@ mod tests { for _ in 0..3 { retained.push(BufferLease::new(pool.clone(), allocation)); - pool = pool.swap(core::iter::empty()).unwrap(); + pool = SlotPool::from_layout(pool.layout()).unwrap(); let reused = pool.alloc(4096).unwrap(); assert_eq!(reused.addr, allocation.addr); allocation = reused; @@ -322,26 +322,6 @@ mod tests { assert_eq!(pool.num_free(), 1); } - #[test] - fn swap_preserves_queue_reservations() { - let pool = SlotPool::new(SlotLayout::new(0x1000, 4096, 2).unwrap()).unwrap(); - let reserved = pool.alloc(4096).unwrap(); - let captured = pool.alloc(4096).unwrap(); - let retained = BufferLease::new(pool.clone(), captured); - - let swapped = pool.swap(core::iter::once(reserved.addr)).unwrap(); - assert_eq!(swapped.num_free(), 1); - assert_eq!(swapped.alloc(4096).unwrap().addr, captured.addr); - - drop(retained); - assert_eq!(swapped.num_free(), 0); - swapped.dealloc(reserved.addr).unwrap(); - swapped.dealloc(captured.addr).unwrap(); - assert_eq!(swapped.num_free(), 2); - pool.dealloc(reserved.addr).unwrap(); - assert_eq!(pool.num_free(), 2); - } - #[test] fn segments_cursor_advances_across_segments() { let segments = Segments::new([ diff --git a/src/hyperlight_common/src/virtq/mod.rs b/src/hyperlight_common/src/virtq/mod.rs index ee4eda5f4..335a8b6cb 100644 --- a/src/hyperlight_common/src/virtq/mod.rs +++ b/src/hyperlight_common/src/virtq/mod.rs @@ -148,6 +148,7 @@ //! ``` mod access; +mod bootstrap; mod buffer; mod consumer; mod desc; @@ -163,7 +164,9 @@ use alloc::vec::Vec; use core::num::NonZeroU16; pub use access::*; +pub use bootstrap::*; pub use buffer::*; +use bytemuck::Zeroable; pub use consumer::*; pub use desc::*; pub use event::*; @@ -257,7 +260,7 @@ impl From for VirtqError { /// 1. Descriptor table: `num_descs` × 16 bytes, aligned to 16 bytes /// 2. Driver event suppression: 4 bytes, aligned to 4 bytes /// 3. Device event suppression: 4 bytes, aligned to 4 bytes -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Layout { /// Packed ring descriptor table base in shared memory. desc_table_addr: u64, @@ -317,6 +320,33 @@ impl Layout { }) } + /// Write a descriptor image and reset both event structures in one pass. + pub(crate) fn initialize_with( + &self, + mem: &M, + desc_at: impl Fn(u16) -> Descriptor, + ) -> Result<(), RingError> { + for index in 0..self.desc_table_len() { + let addr = self.desc_table_addr() + u64::from(index) * Descriptor::SIZE as u64; + + desc_at(index) + .write_release(mem, addr) + .map_err(|_| RingError::mem_err(MemOp::WriteDesc, addr))?; + } + + for addr in [self.drv_evt_addr(), self.dev_evt_addr()] { + EventSuppression::clear(mem, addr) + .map_err(|_| RingError::mem_err(MemOp::WriteEvent, addr))?; + } + + Ok(()) + } + + /// Clear descriptors and enable both peers' notifications. + pub fn initialize(&self, mem: &M) -> Result<(), RingError> { + self.initialize_with(mem, |_| Descriptor::zeroed()) + } + /// Packed ring descriptor table base in shared memory. pub const fn desc_table_addr(&self) -> u64 { self.desc_table_addr @@ -337,6 +367,11 @@ impl Layout { self.dev_evt_addr } + /// Exclusive end of the ring, including both event-suppression structures. + pub const fn end_addr(&self) -> u64 { + self.dev_evt_addr + EventSuppression::SIZE as u64 + } + /// Calculate the memory size needed for a ring with `num_descs` descriptors, /// accounting for alignment requirements. pub const fn query_size(num_descs: usize) -> usize { @@ -433,7 +468,7 @@ const _: () = { assert!(layout.dev_evt_addr() >= layout.drv_evt_addr() + EventSuppression::SIZE as u64); // Total size from query_size covers entire layout - let layout_end = layout.dev_evt_addr() + EventSuppression::SIZE as u64; + let layout_end = layout.end_addr(); assert!(base + expected_size as u64 == layout_end); } diff --git a/src/hyperlight_common/src/virtq/pool.rs b/src/hyperlight_common/src/virtq/pool.rs index 0422e5393..d63de9674 100644 --- a/src/hyperlight_common/src/virtq/pool.rs +++ b/src/hyperlight_common/src/virtq/pool.rs @@ -6,7 +6,7 @@ use thiserror::Error; mod slot; -pub use slot::{SlotLayout, SlotPool}; +pub use slot::{PoolLayout, SlotLayout, SlotPool}; /// Buffer allocation failure. #[derive(Debug, Error, Copy, Clone)] diff --git a/src/hyperlight_common/src/virtq/pool/slot.rs b/src/hyperlight_common/src/virtq/pool/slot.rs index a2e21634d..8136d16c6 100644 --- a/src/hyperlight_common/src/virtq/pool/slot.rs +++ b/src/hyperlight_common/src/virtq/pool/slot.rs @@ -64,6 +64,15 @@ impl SlotLayout { }) } + /// Address of slot `index`, or `None` outside the layout. + pub const fn slot_addr(self, index: usize) -> Option { + if index >= self.slot_count { + return None; + } + + Some(self.base_addr + (index * self.slot_size()) as u64) + } + /// Start address of the first slot. pub const fn base_addr(self) -> u64 { self.base_addr @@ -90,6 +99,61 @@ impl SlotLayout { } } +/// Validated pool geometry independent of live allocations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PoolLayout { + lower: Option, + upper: SlotLayout, +} + +impl PoolLayout { + /// Describe a pool with one slot size. + pub const fn single(layout: SlotLayout) -> Self { + Self { + lower: None, + upper: layout, + } + } + + /// Validate ordered, non-overlapping tiers with nondecreasing slot sizes. + /// + /// Equal-sized tiers must be adjacent and are combined into one tier. + pub fn tiered(lower: SlotLayout, upper: SlotLayout) -> Result { + if lower.slot_size > upper.slot_size || lower.end_addr() > upper.base_addr { + return Err(AllocError::InvalidArg); + } + + if lower.slot_size == upper.slot_size { + if lower.end_addr() != upper.base_addr { + return Err(AllocError::InvalidArg); + } + + let count = lower + .slot_count + .checked_add(upper.slot_count) + .ok_or(AllocError::Overflow)?; + + let layout = SlotLayout::new(lower.base_addr, lower.slot_size(), count)?; + return Ok(Self::single(layout)); + } + + Ok(Self { + lower: Some(lower), + upper, + }) + } + + /// Pool tiers in lower-to-upper order. + pub fn tiers(self) -> impl Iterator { + self.lower.into_iter().chain(core::iter::once(self.upper)) + } + + /// Total number of slots across all tiers. + pub fn slot_count(self) -> usize { + self.tiers().map(SlotLayout::slot_count).sum() + } +} + /// Single-tier fixed-slot free list. /// /// Tracks a fixed set of equal-sized buffer slots. Allocation pops a free slot @@ -182,18 +246,6 @@ impl Tier { Ok(()) } - /// Keep one queue-owned slot unavailable for a pool swap. - fn reserve_addr(&mut self, addr: u64) -> Result<(), AllocError> { - let slot = self.slot_of(addr)?; - - if self.allocated.contains(slot) { - return Err(AllocError::InvalidArg); - } - - self.allocated.insert(slot); - Ok(()) - } - /// Populate the free list from the allocation bitmap. fn rebuild_free(&mut self) { self.free.clear(); @@ -210,7 +262,7 @@ impl Tier { } fn slot_addr(&self, index: usize) -> Option { - (index < self.count).then(|| self.base_addr + (index * self.slot_size as usize) as u64) + self.layout().slot_addr(index) } fn num_free(&self) -> usize { @@ -240,39 +292,10 @@ struct Inner { } impl Inner { - fn new(lower: Option, upper: SlotLayout) -> Result { - let Some(lower) = lower else { - return Ok(Self { - lower: None, - upper: Tier::from_layout(upper)?, - }); - }; - - if lower.slot_size > upper.slot_size || lower.end_addr() > upper.base_addr { - return Err(AllocError::InvalidArg); - } - - if lower.slot_size == upper.slot_size { - if lower.end_addr() != upper.base_addr { - return Err(AllocError::InvalidArg); - } - - let count = lower - .slot_count - .checked_add(upper.slot_count) - .ok_or(AllocError::Overflow)?; - - let layout = SlotLayout::new(lower.base_addr, lower.slot_size(), count)?; - - return Ok(Self { - lower: None, - upper: Tier::from_layout(layout)?, - }); - } - + fn new(layout: PoolLayout) -> Result { Ok(Self { - lower: Some(Tier::from_layout(lower)?), - upper: Tier::from_layout(upper)?, + lower: layout.lower.map(Tier::from_layout).transpose()?, + upper: Tier::from_layout(layout.upper)?, }) } @@ -349,8 +372,11 @@ impl Inner { self.count() - self.num_free() } - fn layouts(&self) -> (Option, SlotLayout) { - (self.lower.as_ref().map(Tier::layout), self.upper.layout()) + fn layout(&self) -> PoolLayout { + PoolLayout { + lower: self.lower.as_ref().map(Tier::layout), + upper: self.upper.layout(), + } } /// Byte span of both tiers, including any gap. @@ -370,37 +396,29 @@ pub struct SlotPool { } impl SlotPool { - /// Whether both handles share allocation state. - pub(crate) fn ptr_eq(&self, other: &Self) -> bool { - Rc::ptr_eq(&self.inner, &other.inner) + /// Create a single-tier recycling pool from exact slot placement. + pub fn new(layout: SlotLayout) -> Result { + Self::from_layout(PoolLayout::single(layout)) } - /// Create allocation state for a pool swap with the supplied live slots reserved. + /// Read-only allocation lookup, lower tier first and descending within each tier. /// - /// Invalid or duplicate reservations leave this pool unchanged. - pub(crate) fn swap(&self, reserved: impl Iterator) -> Result { - let current = self.inner.borrow(); - let (lower, upper) = current.layouts(); - let mut inner = Inner::new(lower, upper)?; - - for addr in reserved { - // this address is a valid allocation in the current pool - current.allocation_len(addr)?; - if let Some(lower) = &mut inner.lower - && lower.contains(addr) - { - lower.reserve_addr(addr)?; - } else { - inner.upper.reserve_addr(addr)?; + /// Allocating each slot at its returned capacity reproduces this order in a fresh pool. + pub(crate) fn alloc_for(layout: PoolLayout, mut index: usize) -> Option { + for tier in layout.tiers() { + if index < tier.slot_count() { + let slot = tier.slot_count() - index - 1; + + return Some(Allocation { + addr: tier.slot_addr(slot)?, + len: tier.slot_size, + }); } + + index -= tier.slot_count(); } - Ok(Self::from_inner(inner)) - } - - /// Create a single-tier recycling pool from exact slot placement. - pub fn new(layout: SlotLayout) -> Result { - Self::from_layouts(None, layout) + None } /// Create a two-tier recycling pool from exact lower and upper layouts. @@ -409,11 +427,12 @@ impl SlotPool { /// slot size must not exceed the upper slot size. Adjacent equal-sized /// layouts form one tier. pub fn new_tiered(lower: SlotLayout, upper: SlotLayout) -> Result { - Self::from_layouts(Some(lower), upper) + Self::from_layout(PoolLayout::tiered(lower, upper)?) } - fn from_layouts(lower: Option, upper: SlotLayout) -> Result { - Ok(Self::from_inner(Inner::new(lower, upper)?)) + /// Create fresh allocation state for a validated pool layout. + pub fn from_layout(layout: PoolLayout) -> Result { + Ok(Self::from_inner(Inner::new(layout)?)) } fn from_inner(mut inner: Inner) -> Self { @@ -432,9 +451,15 @@ impl SlotPool { self.inner.borrow().live_addrs() } + /// Pool geometry independent of current allocations. + pub fn layout(&self) -> PoolLayout { + self.inner.borrow().layout() + } + /// Return the lower and upper tier layouts. pub fn layouts(&self) -> (Option, SlotLayout) { - self.inner.borrow().layouts() + let layout = self.layout(); + (layout.lower, layout.upper) } /// Compute the address of slot `index`, with lower-tier slots first. diff --git a/src/hyperlight_common/src/virtq/pool/tests.rs b/src/hyperlight_common/src/virtq/pool/tests.rs index 9138e3422..2dba194e1 100644 --- a/src/hyperlight_common/src/virtq/pool/tests.rs +++ b/src/hyperlight_common/src/virtq/pool/tests.rs @@ -52,88 +52,6 @@ fn test_tiered_slot_pool_reports_layouts() { assert_eq!(pool.slot_addr(4), None); } -#[test] -fn swap_preserves_tier_layouts_and_reservations() { - for (lower_count, upper_count) in [(2, 2), (16, 11), (17, 17), (64, 65)] { - let pool = make_tiered_slot_pool(lower_count, upper_count); - let lower = pool.alloc(256).unwrap(); - let upper = pool.alloc(4096).unwrap(); - let retained = pool.alloc(256).unwrap(); - let original_live = pool.live_addrs(); - - let swapped = pool.swap([lower.addr, upper.addr].into_iter()).unwrap(); - - assert!(!swapped.ptr_eq(&pool)); - assert_eq!(swapped.layouts(), pool.layouts()); - assert_eq!(pool.live_addrs(), original_live); - assert_eq!(swapped.live_addrs(), vec![lower.addr, upper.addr]); - assert_eq!(swapped.num_free_lower(), lower_count - 1); - assert_eq!(swapped.num_free_upper(), upper_count - 1); - assert_eq!(swapped.alloc(256).unwrap().addr, retained.addr); - let free_upper = swapped.alloc(4096).unwrap(); - assert_ne!(free_upper.addr, upper.addr); - assert_eq!(swapped.num_free(), lower_count + upper_count - 4); - assert_eq!(pool.live_addrs(), original_live); - } -} - -#[test] -fn swap_preserves_free_order_across_inline_storage_boundary() { - for count in [1, 8, 11, 16, 17, 32, 64, 65] { - let pool = make_slot_pool(count, 256); - assert_eq!(pool.num_free(), count); - let allocations: Vec<_> = (0..count).map(|_| pool.alloc(256).unwrap()).collect(); - let reserved = allocations[0].addr; - let swapped = pool.swap(core::iter::once(reserved)).unwrap(); - assert_eq!(swapped.num_free(), count - 1); - - for allocation in &allocations[1..] { - assert_eq!(swapped.alloc(256).unwrap().addr, allocation.addr); - } - assert!(matches!(swapped.alloc(256), Err(AllocError::NoSpace))); - - for allocation in &allocations { - pool.dealloc(allocation.addr).unwrap(); - } - assert_eq!(pool.num_free(), count); - assert_eq!(swapped.num_free(), 0); - - swapped.dealloc(reserved).unwrap(); - assert_eq!(swapped.alloc(256).unwrap().addr, reserved); - for allocation in &allocations { - swapped.dealloc(allocation.addr).unwrap(); - } - assert_eq!(swapped.num_free(), count); - } -} - -#[test] -fn swap_rejects_invalid_reservations_without_mutation() { - let pool = make_slot_pool(2, 64); - let allocation = pool.alloc(64).unwrap(); - let original_live = pool.live_addrs(); - - assert!(matches!( - pool.swap([allocation.addr, allocation.addr].into_iter()), - Err(AllocError::InvalidArg) - )); - for addr in [ - 0, - pool.base_addr(), - allocation.addr + 1, - allocation.addr + 64, - ] { - assert!(matches!( - pool.swap(core::iter::once(addr)), - Err(AllocError::InvalidFree(_, _)) - )); - assert_eq!(pool.live_addrs(), original_live); - assert_eq!(pool.num_free(), 1); - } - pool.dealloc(allocation.addr).unwrap(); - assert_eq!(pool.num_free(), 2); -} - #[test] fn test_tiered_slot_pool_combines_contiguous_equal_sized_layouts() { let lower = SlotLayout::new(0x80000, 0x100, 2).unwrap(); diff --git a/src/hyperlight_common/src/virtq/producer.rs b/src/hyperlight_common/src/virtq/producer.rs index cfb18b742..f84368f19 100644 --- a/src/hyperlight_common/src/virtq/producer.rs +++ b/src/hyperlight_common/src/virtq/producer.rs @@ -7,7 +7,7 @@ use alloc::vec::Vec; use core::mem::ManuallyDrop; use bytes::Bytes; -use smallvec::SmallVec; +use smallvec::{SmallVec, smallvec}; use super::*; @@ -97,6 +97,17 @@ impl InflightTable { } } + /// Reserve `cap` live-chain records alongside the descriptor-ID index. + fn with_capacity(ring_len: usize, cap: usize) -> Result { + let mut table = Self::new(ring_len); + table + .live + .try_reserve_exact(cap) + .map_err(|_| VirtqError::Bookkeeping)?; + + Ok(table) + } + fn try_reserve_one(&mut self) -> Result<(), VirtqError> { if self.live.len() > self.by_id.len() { return Err(VirtqError::InvalidState); @@ -172,7 +183,7 @@ impl InflightTable { /// Dropping a producer does not stop its peer, so inflight owners are /// deliberately leaked to avoid freeing buffers the peer may still use. /// Drain completions for all submitted chains, or stop the peer and call -/// [`reset`](Self::reset), before dropping the producer. +/// [`retire`](Self::retire) to release its queue-owned allocations. /// /// # Example /// @@ -230,6 +241,45 @@ where } } + /// Reconstruct an empty or prefilled producer from [`BootstrapInfo::initialize`]. + /// + /// Creates a fresh pool and reserves posted slots before recreating in-flight + /// chains. Shared memory stays untouched. Completions remain pending for [`poll`](Self::poll). + /// + /// # Safety + /// + /// The ring must have been initialized from `info`, with no producer + /// activity since. Its pool storage must be exclusively available for reuse. + pub unsafe fn from_bootstrap( + info: BootstrapInfo, + mem: M, + notifier: N, + ) -> Result { + let desc_count = info.layout().desc_table_len() as usize; + let inflight = InflightTable::with_capacity(desc_count, usize::from(info.avail()))?; + let pool = SlotPool::from_layout(info.pool_layout())?; + + for index in 0..info.avail() { + let desc = info.desc_at(index); + pool.alloc(desc.len as usize)?; + } + + let inner = RingProducer::from_bootstrap(info, mem); + let next_token = u32::from(info.avail()); + + let mut producer = Self { + inner, + notifier, + pool, + inflight, + next_token, + pending: VecDeque::new(), + }; + + producer.restore_inflight(info); + Ok(producer) + } + /// Borrow the pool used for new chains. pub fn pool(&self) -> &SlotPool { &self.pool @@ -240,44 +290,9 @@ where self.inner.mem() } - /// Reclaim scratch slots held by retained views without changing in-flight chains. - /// - /// Retained views keep their original pools. Buffered completions or chains - /// from another allocator return [`VirtqError::InvalidState`]. - /// - /// # Safety - /// - /// Allocations held outside this producer must have backing independent of - /// reused scratch. After a swap, old pool handles must not allocate again. - /// No unsent chains or builders may remain. Peer accesses must be stopped. - pub unsafe fn reclaim_slots(&mut self) -> Result<(), VirtqError> { - let live = &mut self.inflight.live; - // All pending used chains must be drained before we can swap pools - if !self.pending.is_empty() { - return Err(VirtqError::InvalidState); - } - - // inflight chains must have the same pool as the producer before we swap - if live.iter().any(|inf| !self.pool.ptr_eq(&inf.chain.pool)) { - return Err(VirtqError::InvalidState); - } - - let reserved = live - .iter() - .flat_map(|inf| inf.chain.buffers.iter().map(|buf| buf.addr)); - - // No retained slots need reclaiming when all live slots are in-flight. - if self.pool.num_live() == reserved.clone().count() { - return Ok(()); - } - - let pool = self.pool.swap(reserved)?; - for inf in live { - inf.chain.pool = pool.clone(); - } - - self.pool = pool; - Ok(()) + /// Ring geometry independent of its current cursors. + pub fn layout(&self) -> Layout { + self.inner.layout() } /// Begin building a descriptor chain for submission. @@ -285,6 +300,7 @@ where /// The builder captures the current free-descriptor budget. /// Submission checks capacity again. pub fn chain(&self) -> ChainBuilder { + // TODO: Support owned refill buffers outside the fixed slot pool. ChainBuilder::new( self.inner.mem().clone(), self.pool.clone(), @@ -436,6 +452,106 @@ where self.inner.reset()?; self.next_token = 0; + self.release_inflight() + } + + /// Release queue-owned allocations without accessing shared memory. + /// + /// Returned payload views keep their original leases. Buffered completions + /// must be drained before retirement. + /// + /// # Safety + /// + /// All consumer-side chain handles must be dropped. No peer may access + /// this producer's allocations again. Surviving pool handles must not + /// allocate into backing owned by another producer. + pub unsafe fn retire(mut self) -> Result<(), VirtqError> { + if !self.pending.is_empty() { + return Err(VirtqError::InvalidState); + } + + self.release_inflight() + } + + /// Rebuild private state in place without accessing shared memory. + /// + /// Requires matching geometry and no buffered completions. Prepares resources + /// before retiring old owners. Retirement errors require discarding the producer. + /// + /// # Safety + /// + /// The old peer must have no live chain handles or future accesses. No producer + /// may have used the matching bootstrap. Pool backing must be exclusive. + /// Retained views need independent backing. Old pool handles must not allocate. + /// Resume only after success. + pub unsafe fn refresh(&mut self, info: BootstrapInfo) -> Result<(), VirtqError> { + if !self.pending.is_empty() { + return Err(VirtqError::InvalidState); + } + + // Check that the ring and pool layouts match the bootstrap info. + if self.layout() != info.layout() || self.pool.layout() != info.pool_layout() { + return Err(VirtqError::InvalidState); + } + + let posted = usize::from(info.avail()); + let inf_cnt = posted.saturating_sub(self.inflight.live.len()); + + self.inflight + .live + .try_reserve_exact(inf_cnt) + .map_err(|_| VirtqError::Bookkeeping)?; + + let pool = SlotPool::from_layout(info.pool_layout())?; + + for index in 0..info.avail() { + let desc = info.desc_at(index); + pool.alloc(desc.len as usize)?; + } + + self.pool = pool; + self.next_token = u32::from(info.avail()); + + self.release_inflight()?; + self.restore_inflight(info); + // Rebuild the ring's private state as well + self.inner.refresh(info.avail()); + + Ok(()) + } + + /// Install in-flight owners for the prepared pool's posted slots. + fn restore_inflight(&mut self, info: BootstrapInfo) { + for index in 0..info.avail() { + let desc = info.desc_at(index); + + let token = Token { + seq: u32::from(index), + id: desc.id, + }; + + let buffers = smallvec![BufferEntry { + addr: desc.addr, + capacity: desc.len, + written: 0, + }]; + + let chain = OwnedChain { + mem: self.memory().clone(), + pool: self.pool.clone(), + buffers, + readable: 0, + }; + + self.inflight.insert(Inflight { + token, + chain: ManuallyDrop::new(chain), + }); + } + } + + /// Release in-flight owners after the caller has stopped their peer. + fn release_inflight(&mut self) -> Result<(), VirtqError> { let mut maybe_err = None; while let Some(inflight) = self.inflight.pop() { @@ -1212,7 +1328,9 @@ fn checked_descriptor_len(len: usize) -> Result { mod tests { use alloc::rc::Rc; use alloc::sync::Arc; + use core::num::NonZeroU16; use core::sync::atomic::Ordering; + use std::assert_matches; use super::*; use crate::virtq::ring::tests::{FaultMem, OwnedRing, TestMem, make_consumer, make_ring}; @@ -1360,6 +1478,579 @@ mod tests { assert_eq!(producer.pending.capacity(), 0); } + #[test] + fn empty_single_tier_bootstrap_supports_first_submission() { + let ring = make_ring(4); + let slots = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 2).unwrap(); + let info = BootstrapInfo::empty(ring.layout(), PoolLayout::single(slots)).unwrap(); + info.initialize(&ring.mem()).unwrap(); + + // SAFETY: This is the only producer for the matching bootstrap and pool. + let mut producer = + unsafe { VirtqProducer::from_bootstrap(info, ring.mem(), TestNotifier::new()) } + .unwrap(); + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), TestNotifier::new()); + let mut chain = producer.chain().readable(32).build().unwrap(); + chain.write_all(b"first request").unwrap(); + + let token = producer.submit(chain).unwrap(); + let (recv, reply) = poll_received(&mut consumer); + consumer.complete(recv, reply).unwrap(); + + assert_matches!(producer.poll(), Ok(Some(UsedChain::Ack(ack))) if ack == token); + assert_eq!(producer.pool().num_free(), 2); + assert_eq!(producer.num_free(), ring.len()); + } + + #[test] + fn empty_bootstrap_refresh_reuses_bookkeeping_and_preserves_events() { + let ring = make_ring(4); + let mem = FaultMem::new(ring.mem()); + let lower = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 2).unwrap(); + let upper = SlotLayout::new(lower.end_addr(), 128, 2).unwrap(); + let old_pool = SlotPool::new_tiered(lower, upper).unwrap(); + let retained = BufferLease::new(old_pool.clone(), old_pool.alloc(32).unwrap()); + let notifier = TestNotifier::new(); + let mut producer = VirtqProducer::new( + ring.layout(), + mem.clone(), + notifier.clone(), + old_pool.clone(), + ); + let chain = producer.chain().readable(32).writable(96).build().unwrap(); + producer.submit(chain).unwrap(); + + let by_id = producer.inflight.by_id.as_ptr(); + let live = producer.inflight.live.as_ptr(); + let notifications = notifier.notification_count(); + let info = BootstrapInfo::empty(ring.layout(), old_pool.layout()).unwrap(); + info.initialize(&mem).unwrap(); + + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), TestNotifier::new()); + consumer + .set_avail_suppression(SuppressionKind::Disable) + .unwrap(); + + let mut before = vec![0; Layout::query_size(ring.len())]; + mem.read(ring.layout().desc_table_addr(), &mut before) + .unwrap(); + mem.fail_write_at(0); + + // SAFETY: The old peer has no handles. The retained lease has no views. + // Only the new consumer has accessed the matching bootstrap. + unsafe { producer.refresh(info) }.unwrap(); + + let mut after = vec![0; before.len()]; + mem.read(ring.layout().desc_table_addr(), &mut after) + .unwrap(); + + assert_eq!(before, after); + assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + assert_eq!(notifier.notification_count(), notifications); + assert_eq!(producer.inflight.by_id.as_ptr(), by_id); + assert_eq!(producer.inflight.live.as_ptr(), live); + assert_eq!(producer.num_inflight(), 0); + assert_eq!(producer.num_free(), ring.len()); + assert_eq!(producer.pool().num_free_lower(), 2); + assert_eq!(producer.pool().num_free_upper(), 2); + assert_matches!(producer.poll(), Ok(None)); + + mem.allow_writes(); + + let mut chain = producer.chain().readable(32).writable(96).build().unwrap(); + chain.write_all(b"request").unwrap(); + + drop(retained); + assert_eq!(old_pool.num_live(), 0); + assert_eq!(producer.pool().num_free_lower(), 1); + assert_eq!(producer.pool().num_free_upper(), 1); + + let token = producer.submit(chain).unwrap(); + assert_eq!(token.seq, 0); + assert_eq!(notifier.notification_count(), notifications); + + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + + reply.write_all(b"response").unwrap(); + consumer.complete(recv, reply).unwrap(); + + let used = producer.poll().unwrap().unwrap(); + assert_eq!(used.token(), token); + + let response = used.into_bytes().unwrap(); + assert_eq!(response.as_ref(), b"response"); + drop(response); + + assert_eq!(producer.pool().num_free_lower(), 2); + assert_eq!(producer.pool().num_free_upper(), 2); + assert_eq!(producer.num_free(), ring.len()); + } + + #[test] + fn prefilled_bootstrap_reserves_each_tiers_original_capacity() { + let ring = make_ring(2); + let mem = FaultMem::new(ring.mem()); + let lower = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 1).unwrap(); + let upper = SlotLayout::new(lower.end_addr(), 128, 2).unwrap(); + let layout = PoolLayout::tiered(lower, upper).unwrap(); + let info = BootstrapInfo::prefilled(ring.layout(), layout).unwrap(); + info.initialize(&mem).unwrap(); + + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), TestNotifier::new()); + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + + reply.write_all(b"small").unwrap(); + consumer.complete(recv, reply).unwrap(); + + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + + reply.write_all(&[0xa5; 96]).unwrap(); + consumer.complete(recv, reply).unwrap(); + mem.fail_write_at(0); + + // SAFETY: The pool is exclusive. Only the consumer has accessed the + // matching bootstrap, completing both posted buffers. + let mut producer = + unsafe { VirtqProducer::from_bootstrap(info, mem.clone(), TestNotifier::new()) } + .unwrap(); + + assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + assert_eq!(producer.num_inflight(), 2); + assert_eq!(producer.pool().num_free_lower(), 0); + assert_eq!(producer.pool().num_free_upper(), 1); + + let small = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + let large = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + assert_eq!(small.as_ref(), b"small"); + assert_eq!(large.as_ref(), &[0xa5; 96]); + + drop((small, large)); + assert_eq!(producer.pool().num_free_lower(), 1); + assert_eq!(producer.pool().num_free_upper(), 2); + assert_eq!(producer.num_free(), ring.len()); + + mem.allow_writes(); + + let mut chain = producer.chain().readable(32).build().unwrap(); + chain.write_all(b"after bootstrap").unwrap(); + let token = producer.submit(chain).unwrap(); + + let (recv, reply) = poll_received(&mut consumer); + consumer.complete(recv, reply).unwrap(); + + assert_matches!(producer.poll(), Ok(Some(UsedChain::Ack(ack))) if ack == token); + assert_eq!(producer.pool().num_free(), 3); + } + + #[test] + fn adoption_preserves_requests_completed_before_guest_entry() { + let ring = make_ring(4); + let mem = FaultMem::new(ring.mem()); + let slots = SlotLayout::new(ring.layout().dev_evt_addr() + 0x100, 64, 3).unwrap(); + let notifier = TestNotifier::new(); + + let info = BootstrapInfo::prefilled(ring.layout(), PoolLayout::single(slots)).unwrap(); + info.initialize(&mem).unwrap(); + + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), TestNotifier::new()); + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + reply.write_all(b"first").unwrap(); + consumer.complete(recv, reply).unwrap(); + + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + reply.write_all(b"second request").unwrap(); + consumer.complete(recv, reply).unwrap(); + + let mut before = vec![0; Layout::query_size(ring.len())]; + mem.read(ring.layout().desc_table_addr(), &mut before) + .unwrap(); + mem.fail_write_at(0); + + // SAFETY: The matching bootstrap owns these slots. Only the consumer + // has accessed the ring, completing two of its three buffers. + let mut producer = + unsafe { VirtqProducer::from_bootstrap(info, mem.clone(), notifier.clone()) }.unwrap(); + + let mut after = vec![0; before.len()]; + mem.read(ring.layout().desc_table_addr(), &mut after) + .unwrap(); + + assert_eq!(before, after); + assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + assert_eq!(notifier.notification_count(), 0); + assert_eq!(producer.num_inflight(), 3); + assert_matches!( + producer.chain().writable(64).build().err(), + Some(VirtqError::Backpressure) + ); + + let first = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + let second = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + + assert_eq!(first.as_ref(), b"first"); + assert_eq!(second.as_ref(), b"second request"); + assert!(producer.poll().unwrap().is_none()); + assert_eq!(producer.pool().num_free(), 0); + + drop((first, second)); + assert_eq!(producer.pool().num_free(), 2); + + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + reply.write_all(&[0x5a; 64]).unwrap(); + consumer.complete(recv, reply).unwrap(); + + let third = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + assert_eq!(third.as_ref(), &[0x5a; 64]); + drop(third); + + assert_eq!(producer.pool().num_free(), 3); + assert_eq!(producer.num_free(), ring.len()); + } + + #[test] + fn adoption_uses_original_capacity_to_reject_oversized_completion() { + let ring = make_ring(1); + let slots = SlotLayout::new(ring.layout().dev_evt_addr() + 0x100, 64, 1).unwrap(); + + let info = BootstrapInfo::prefilled(ring.layout(), PoolLayout::single(slots)).unwrap(); + info.initialize(&ring.mem()).unwrap(); + + let mut used = ring.read_desc(0); + used.len = 65; + used.mark_used(true); + ring.write_desc(0, used); + + // SAFETY: This is the only producer for the matching bootstrap. + // The forged completion did not write past the owned buffer. + let mut producer = + unsafe { VirtqProducer::from_bootstrap(info, ring.mem(), TestNotifier::new()) } + .unwrap(); + + assert_matches!(producer.poll(), Err(VirtqError::InvalidState)); + assert_eq!(producer.pool().num_free(), 1); + assert_eq!(producer.num_free(), 1); + } + + #[test] + fn adopted_full_ring_refills_across_wrap_with_event_suppression() { + let ring = make_ring(2); + let slots = SlotLayout::new(ring.layout().dev_evt_addr() + 0x100, 64, 3).unwrap(); + let notifier = TestNotifier::new(); + + let info = BootstrapInfo::prefilled(ring.layout(), PoolLayout::single(slots)).unwrap(); + info.initialize(&ring.mem()).unwrap(); + + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), TestNotifier::new()); + consumer + .set_avail_suppression(SuppressionKind::Disable) + .unwrap(); + + // SAFETY: The pool is exclusively owned and only the consumer has + // accessed the matching bootstrap's event structure. + let mut producer = + unsafe { VirtqProducer::from_bootstrap(info, ring.mem(), notifier.clone()) }.unwrap(); + + assert_eq!(producer.num_free(), 0); + assert_eq!(producer.pool().num_free(), 1); + + let (recv, reply) = poll_received(&mut consumer); + consumer.complete(recv, reply).unwrap(); + let (recv, reply) = poll_received(&mut consumer); + consumer.complete(recv, reply).unwrap(); + + let first = producer.poll().unwrap().unwrap(); + let second = producer.poll().unwrap().unwrap(); + assert_ne!(first.token(), second.token()); + drop((first, second)); + + assert_eq!(producer.pool().num_free(), 3); + + let chain = producer.chain().writable(64).build().unwrap(); + let token = producer.submit(chain).unwrap(); + + assert_eq!(token.seq, 2); + assert_eq!(notifier.notification_count(), 0); + + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + reply.write_all(b"wrapped").unwrap(); + consumer.complete(recv, reply).unwrap(); + + let used = producer.poll().unwrap().unwrap(); + assert_eq!(used.token(), token); + assert_eq!(used.into_bytes().unwrap().as_ref(), b"wrapped"); + + consumer + .set_avail_suppression(SuppressionKind::Descriptor(consumer.avail_cursor())) + .unwrap(); + + let chain = producer.chain().writable(64).build().unwrap(); + let token = producer.submit(chain).unwrap(); + + assert_eq!(notifier.notification_count(), 1); + + let (recv, reply) = poll_received(&mut consumer); + consumer.complete(recv, reply).unwrap(); + + assert_eq!(producer.poll().unwrap().unwrap().token(), token); + assert_eq!(producer.pool().num_free(), 3); + assert_eq!(producer.num_free(), ring.len()); + } + + #[test] + fn retirement_preserves_new_generation_requests_and_leases() { + let ring = make_ring(4); + let mem = FaultMem::new(ring.mem()); + let slots = SlotLayout::new(ring.layout().dev_evt_addr() + 0x100, 64, 3).unwrap(); + let old_pool = SlotPool::new(slots).unwrap(); + let retained = BufferLease::new(old_pool.clone(), old_pool.alloc(64).unwrap()); + let notif = TestNotifier::new(); + + let mut old = + VirtqProducer::new(ring.layout(), mem.clone(), notif.clone(), old_pool.clone()); + + let chain = old.chain().writable(64).build().unwrap(); + old.submit(chain).unwrap(); + + let info = BootstrapInfo::prefilled(ring.layout(), old_pool.layout()).unwrap(); + info.initialize(&mem).unwrap(); + + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), notif.clone()); + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + + reply.write_all(b"next generation").unwrap(); + consumer.complete(recv, reply).unwrap(); + + // SAFETY: The old peer has no handles. The retained lease has no views. + // Only this consumer has accessed the fresh bootstrap. + let mut producer = + unsafe { VirtqProducer::from_bootstrap(info, mem.clone(), notif) }.unwrap(); + + let mut before = vec![0; Layout::query_size(ring.len())]; + let table_addr = ring.layout().desc_table_addr(); + mem.read(table_addr, &mut before).unwrap(); + mem.fail_write_at(0); + + // SAFETY: The old queue has no consumer handles or future peer accesses. + // The retained lease can only return its slot to the old pool. + unsafe { old.retire() }.unwrap(); + + let mut after = vec![0; before.len()]; + mem.read(table_addr, &mut after).unwrap(); + + assert_eq!(before, after); + assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + assert_eq!(old_pool.num_live(), 1); + assert_eq!(producer.pool().num_live(), 3); + + drop(retained); + assert_eq!(old_pool.num_live(), 0); + assert_eq!(producer.pool().num_live(), 3); + + let received = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + assert_eq!(received.as_ref(), b"next generation"); + drop(received); + assert_eq!(producer.pool().num_free(), 1); + + // SAFETY: The consumer has no live handles and stays stopped. + unsafe { producer.retire() }.unwrap(); + } + + #[test] + fn prefilled_bootstrap_refresh_reuses_bookkeeping_and_preserves_requests() { + let ring = make_ring(4); + let mem = FaultMem::new(ring.mem()); + let slots = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 3).unwrap(); + let old_pool = SlotPool::new(slots).unwrap(); + let retained = BufferLease::new(old_pool.clone(), old_pool.alloc(64).unwrap()); + let notifier = TestNotifier::new(); + let mut producer = VirtqProducer::new( + ring.layout(), + mem.clone(), + notifier.clone(), + old_pool.clone(), + ); + producer.inflight.live.try_reserve_exact(3).unwrap(); + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), notifier.clone()); + + let chain = producer.chain().writable(64).build().unwrap(); + producer.submit(chain).unwrap(); + let chain = producer.chain().writable(64).build().unwrap(); + producer.submit(chain).unwrap(); + + let (recv, reply) = poll_received(&mut consumer); + consumer.complete(recv, reply).unwrap(); + drop(producer.poll().unwrap().unwrap()); + drop(consumer); + + let by_id = producer.inflight.by_id.as_ptr(); + let live = producer.inflight.live.as_ptr(); + let live_capacity = producer.inflight.live.capacity(); + let info = BootstrapInfo::prefilled(ring.layout(), old_pool.layout()).unwrap(); + info.initialize(&mem).unwrap(); + + let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), notifier.clone()); + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + + reply.write_all(b"next generation").unwrap(); + consumer.complete(recv, reply).unwrap(); + + let notifications = notifier.notification_count(); + let mut before = vec![0; Layout::query_size(ring.len())]; + mem.read(ring.layout().desc_table_addr(), &mut before) + .unwrap(); + mem.fail_write_at(0); + + // SAFETY: The old peer is gone. The retained lease has no views. + // Only the new consumer has accessed the matching bootstrap. + unsafe { producer.refresh(info) }.unwrap(); + + let mut after = vec![0; before.len()]; + mem.read(ring.layout().desc_table_addr(), &mut after) + .unwrap(); + + assert_eq!(before, after); + assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + assert_eq!(notifier.notification_count(), notifications); + assert_eq!(producer.inflight.by_id.as_ptr(), by_id); + assert_eq!(producer.inflight.live.as_ptr(), live); + assert_eq!(producer.inflight.live.capacity(), live_capacity); + assert_eq!(old_pool.num_live(), 1); + assert_eq!(producer.pool().num_live(), 3); + + drop(retained); + assert_eq!(old_pool.num_live(), 0); + assert_eq!(producer.pool().num_live(), 3); + + let received = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + assert_eq!(received.as_ref(), b"next generation"); + drop(received); + + mem.allow_writes(); + let chain = producer.chain().writable(64).build().unwrap(); + let token = producer.submit(chain).unwrap(); + assert_eq!(token.seq, 3); + + // SAFETY: The consumer has no live handles and stays stopped. + unsafe { producer.retire() }.unwrap(); + } + + #[test] + fn bootstrap_refresh_rejects_buffered_completion() { + let ring = make_ring(4); + let backing = Rc::new(ring.mem()); + let mem = CopyingMem(&backing); + let slots = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 2).unwrap(); + let pool = SlotPool::new(slots).unwrap(); + let info = BootstrapInfo::empty(ring.layout(), pool.layout()).unwrap(); + let mut producer = + VirtqProducer::new(ring.layout(), mem.clone(), TestNotifier::new(), pool); + let mut consumer = VirtqConsumer::new(ring.layout(), mem.clone(), TestNotifier::new()); + + let chain = producer.chain().writable(64).build().unwrap(); + producer.submit(chain).unwrap(); + let (recv, ReplyChain::Writable(mut reply)) = poll_received(&mut consumer) else { + panic!("expected writable buffer"); + }; + + reply.write_all(b"buffered").unwrap(); + consumer.complete(recv, reply).unwrap(); + producer.reclaim().unwrap(); + drop(consumer); + info.initialize(&mem).unwrap(); + + // SAFETY: The old peer is gone. CopyingMem gives buffered data independent + // backing, and no producer has accessed the matching bootstrap. + assert_matches!( + unsafe { producer.refresh(info) }, + Err(VirtqError::InvalidState) + ); + + let buffered = producer.poll().unwrap().unwrap().into_bytes().unwrap(); + assert_eq!(buffered.as_ref(), b"buffered"); + drop(buffered); + + // SAFETY: The peer remains stopped and the matching bootstrap is untouched. + unsafe { producer.refresh(info) }.unwrap(); + assert_matches!(producer.poll(), Ok(None)); + } + + #[test] + fn bootstrap_refresh_rejects_changed_ring_layout() { + let ring = make_ring(4); + let (mut producer, _consumer, _) = make_test_producer(&ring); + let chain = producer.chain().readable(16).build().unwrap(); + producer.submit(chain).unwrap(); + let pool = producer.pool().clone(); + // SAFETY: The smaller ring fits within the existing aligned ring storage. + let layout = unsafe { + Layout::from_base(ring.layout().desc_table_addr(), NonZeroU16::new(2).unwrap()) + } + .unwrap(); + let info = BootstrapInfo::empty(layout, pool.layout()).unwrap(); + info.initialize(&ring.mem()).unwrap(); + + // SAFETY: The old peer has no handles or future accesses. The matching + // bootstrap owns the pool storage and has had no producer activity. + assert_matches!( + unsafe { producer.refresh(info) }, + Err(VirtqError::InvalidState) + ); + + assert_eq!(producer.layout(), ring.layout()); + assert_eq!(producer.num_inflight(), 1); + assert_eq!(pool.num_live(), 1); + + // SAFETY: The peer remains stopped with no live handles. + unsafe { producer.retire() }.unwrap(); + } + + #[test] + fn bootstrap_refresh_rejects_changed_pool_layout() { + let ring = make_ring(4); + let slots = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 2).unwrap(); + let pool = SlotPool::new(slots).unwrap(); + let mut producer = + VirtqProducer::new(ring.layout(), ring.mem(), TestNotifier::new(), pool.clone()); + let chain = producer.chain().readable(16).build().unwrap(); + producer.submit(chain).unwrap(); + + let changed = SlotLayout::new(slots.base_addr(), 64, 3).unwrap(); + let info = BootstrapInfo::empty(ring.layout(), PoolLayout::single(changed)).unwrap(); + info.initialize(&ring.mem()).unwrap(); + + // SAFETY: No peer has accessed either generation. The matching bootstrap + // owns the pool storage and has had no producer activity. + assert_matches!( + unsafe { producer.refresh(info) }, + Err(VirtqError::InvalidState) + ); + + assert_eq!(producer.pool().layout(), pool.layout()); + assert_eq!(producer.num_inflight(), 1); + assert_eq!(pool.num_live(), 1); + + // SAFETY: The peer has no live handles or future accesses. + unsafe { producer.retire() }.unwrap(); + } + #[test] fn full_ring_still_reports_backpressure() { let ring = make_ring(4); @@ -1600,13 +2291,6 @@ mod tests { producer.submit(chain).unwrap(); - // SAFETY: No views exist and the consumer has not accessed the ring. - assert!(matches!( - unsafe { producer.reclaim_slots() }, - Err(VirtqError::InvalidState) - )); - assert!(producer.pool().ptr_eq(&replacement)); - assert!(orig_gen.upgrade().is_some()); let (recv, reply) = poll_received(&mut consumer); @@ -1832,104 +2516,6 @@ mod tests { assert!(producer.poll().unwrap().is_none()); } - #[test] - fn pool_swap_skips_pools_without_retained_allocations() { - let ring = make_ring(8); - let (mut producer, _consumer) = make_virtq_pair(&ring, 64); - let pool = producer.pool().clone(); - - // SAFETY: No allocations or peer accesses exist. - unsafe { producer.reclaim_slots() }.unwrap(); - assert!(producer.pool().ptr_eq(&pool)); - - let chain = producer.chain().writable(64).build().unwrap(); - producer.submit(chain).unwrap(); - // SAFETY: Only the posted chain owns an allocation. The peer stays stopped. - unsafe { producer.reclaim_slots() }.unwrap(); - assert!(producer.pool().ptr_eq(&pool)); - - // SAFETY: The consumer has not accessed the ring and stays inactive. - unsafe { producer.reset() }.unwrap(); - assert_eq!(pool.num_live(), 0); - } - - #[test] - fn pool_swap_preserves_posted_requests_and_ring_state() { - let ring = make_ring(8); - let mem = ring.mem(); - let (mut producer, mut consumer) = make_virtq_pair(&ring, 64); - - let original = producer.pool().clone(); - let allocation = original.alloc(64).unwrap(); - let mut retained = vec![BufferLease::new(original.clone(), allocation)]; - - let mut tokens = Vec::new(); - for _ in 0..2 { - let chain = producer.chain().writable(64).build().unwrap(); - tokens.push(producer.submit(chain).unwrap()); - } - - let (recv, reply) = poll_received(&mut consumer); - let ReplyChain::Writable(mut reply) = reply else { - panic!("expected writable reply"); - }; - reply.write_all(b"first").unwrap(); - consumer.complete(recv, reply).unwrap(); - - let mut ring_before = vec![0; Layout::query_size(ring.len())]; - mem.read(mem.base_addr(), &mut ring_before).unwrap(); - - for round in 0..2 { - let previous = producer.pool().clone(); - if round != 0 { - let allocation = previous.alloc(64).unwrap(); - retained.push(BufferLease::new(previous.clone(), allocation)); - } - // SAFETY: The retained lease has no views. No peer handles remain, - // and the consumer stays stopped during the swap. - unsafe { producer.reclaim_slots() }.unwrap(); - assert!(!producer.pool().ptr_eq(&previous)); - - let mut ring_after = vec![0; ring_before.len()]; - mem.read(mem.base_addr(), &mut ring_after).unwrap(); - assert_eq!(ring_after, ring_before); - } - - let pool = producer.pool().clone(); - let reused = pool.alloc(64).unwrap(); - assert_eq!(reused.addr, allocation.addr); - - drop(retained); - assert_eq!(pool.num_live(), 3); - - let first = producer.poll().unwrap().unwrap(); - assert_eq!(first.token(), tokens[0]); - - let first = first.into_bytes().unwrap(); - assert_eq!(first.as_ref(), b"first"); - - drop(first); - assert_eq!(pool.num_live(), 2); - - let (recv, reply) = poll_received(&mut consumer); - let ReplyChain::Writable(mut reply) = reply else { - panic!("expected writable reply"); - }; - - reply.write_all(b"second").unwrap(); - consumer.complete(recv, reply).unwrap(); - - let second = producer.poll().unwrap().unwrap(); - assert_eq!(second.token(), tokens[1]); - - let second = second.into_bytes().unwrap(); - assert_eq!(second.as_ref(), b"second"); - - drop(second); - pool.dealloc(reused.addr).unwrap(); - assert_eq!(pool.num_live(), 0); - } - #[test] fn reset_reclaims_inflight_slots_and_reuses_ring() { let ring = make_ring(8); @@ -2004,7 +2590,7 @@ mod tests { } #[test] - fn reset_and_pool_swap_reject_buffered_writable_completion() { + fn reset_rejects_buffered_writable_completion() { let ring = make_ring(8); let (mut producer, mut consumer, _notifier) = make_test_producer(&ring); let chain = producer.chain().writable(64).build().unwrap(); @@ -2019,20 +2605,8 @@ mod tests { consumer.complete(recv, reply).unwrap(); producer.reclaim().unwrap(); - let pool = producer.pool().clone(); - // SAFETY: No allocations are held outside the producer. The consumer - // completed its handles and stays inactive. - assert!(matches!( - unsafe { producer.reclaim_slots() }, - Err(VirtqError::InvalidState) - )); - assert!(producer.pool().ptr_eq(&pool)); - // SAFETY: The consumer completed its handles and stays inactive. - assert!(matches!( - unsafe { producer.reset() }, - Err(VirtqError::InvalidState) - )); + assert_matches!(unsafe { producer.reset() }, Err(VirtqError::InvalidState)); drop(producer.poll().unwrap().unwrap()); diff --git a/src/hyperlight_common/src/virtq/ring.rs b/src/hyperlight_common/src/virtq/ring.rs index b866312d7..af4cb9003 100644 --- a/src/hyperlight_common/src/virtq/ring.rs +++ b/src/hyperlight_common/src/virtq/ring.rs @@ -73,7 +73,7 @@ use thiserror::Error; use super::desc::{DescFlags, DescTable, Descriptor}; use super::event::{EventFlags, EventSuppression}; -use super::{Layout, MemOps}; +use super::{BootstrapInfo, Layout, MemOps}; /// A single buffer element in a scatter-gather list. /// @@ -198,7 +198,7 @@ pub enum RingError { impl RingError { #[inline] - fn mem_err(op: MemOp, addr: u64) -> Self { + pub(crate) fn mem_err(op: MemOp, addr: u64) -> Self { let len = match op { MemOp::ReadDesc | MemOp::WriteDesc => Descriptor::SIZE, MemOp::ReadEvent | MemOp::WriteEvent => EventSuppression::SIZE, @@ -500,6 +500,11 @@ pub(super) struct Checkpoint { num_inflight: usize, } +/// Read-only ID lookup at allocation position `index` in a fresh producer. +pub(crate) fn id_for(ring_len: u16, index: u16) -> Option { + ring_len.checked_sub(index)?.checked_sub(1) +} + /// Producer (driver) side of a packed virtqueue. /// /// The producer submits buffer chains for the device to process and polls @@ -539,32 +544,38 @@ pub struct RingProducer { impl RingProducer { /// Create a new producer from a memory layout and accessor. pub fn new(layout: Layout, mem: M) -> Self { - let size = layout.desc_table_len() as usize; + Self::with_inflight(layout, mem, 0) + } + + /// Reconstruct private state for a bootstrapped ring without accessing shared memory. + pub fn from_bootstrap(info: BootstrapInfo, mem: M) -> Self { + Self::with_inflight(info.layout(), mem, info.avail()) + } + + /// Create private bookkeeping for initially posted single-buffer chains. + fn with_inflight(layout: Layout, mem: M, posted: u16) -> Self { + let size = usize::from(layout.desc_table_len()); let raw = layout.desc_table_addr(); // SAFETY: Layout fields are private and from_base validates ring geometry. let table = unsafe { DescTable::from_raw_parts(raw, size) }; let cursor = RingCursor::new(size); - const DEFAULT_LEN: usize = DescTable::default_len(); - let id_free = (0..size as u16).collect::>(); - let id_num = SmallVec::<[_; DEFAULT_LEN]>::from_elem(0, size); - - // Notification enabled by default - let event_flags_shadow = EventFlags::ENABLE; - - Self { + let mut producer = Self { mem, avail_cursor: cursor, used_cursor: cursor, num_free: size, desc_table: table, - id_free, - id_num, - event_flags_shadow, + id_free: SmallVec::with_capacity(size), + id_num: SmallVec::with_capacity(size), + event_flags_shadow: EventFlags::ENABLE, drv_evt_addr: layout.drv_evt_addr(), dev_evt_addr: layout.dev_evt_addr(), - } + }; + + producer.refresh(posted); + producer } /// Fast path: submit exactly one descriptor @@ -843,6 +854,16 @@ impl RingProducer { self.desc_table.len() } + /// Ring geometry independent of its current cursors. + pub(crate) fn layout(&self) -> Layout { + Layout { + desc_table_addr: self.desc_table.base_addr(), + desc_table_len: self.desc_table.len() as u16, + drv_evt_addr: self.drv_evt_addr, + dev_evt_addr: self.dev_evt_addr, + } + } + /// Get memory accessor reference #[inline] pub fn mem(&self) -> &M { @@ -987,7 +1008,6 @@ impl RingProducer { /// on error. pub fn reset(&mut self) -> Result<(), RingError> { let table_addr = self.desc_table.base_addr(); - let size = self.desc_table.len(); self.desc_table .clear(&self.mem) @@ -996,15 +1016,32 @@ impl RingProducer { EventSuppression::clear(&self.mem, self.drv_evt_addr) .map_err(|_| RingError::mem_err(MemOp::WriteEvent, self.drv_evt_addr))?; + self.refresh(0); + Ok(()) + } + + /// Rebuild private cursors and IDs without accessing shared memory. + pub(crate) fn refresh(&mut self, posted: u16) { + let size = self.len(); + let len = size as u16; + + debug_assert!(posted <= len); + + let free = size - usize::from(posted); self.avail_cursor.reset(); + self.avail_cursor.advance_by(posted); self.used_cursor.reset(); + self.num_free = free; - self.num_free = size; self.id_free.clear(); - self.id_free.extend(0..size as u16); - self.id_num.iter_mut().for_each(|n| *n = 0); + self.id_free + .extend((posted..len).rev().filter_map(|i| id_for(len, i))); + + self.id_num.clear(); + self.id_num.resize(free, 0); + self.id_num.resize(size, 1); + self.event_flags_shadow = EventFlags::ENABLE; - Ok(()) } } @@ -1526,7 +1563,7 @@ pub(crate) mod tests { use super::super::align_up; use super::*; use crate::virtq::event::EventSuppression; - use crate::virtq::{BufferLease, BufferMap}; + use crate::virtq::{BufferLease, BufferMap, PoolLayout, SlotLayout}; /// Test MemOps implementation that maintains pointer provenance. /// @@ -3537,6 +3574,33 @@ pub(crate) mod tests { assert!(cursor.wrap()); } + #[test] + fn bootstrap_refresh_reuses_id_storage_without_writing_shared_memory() { + let ring = make_ring(DescTable::default_len() * 2); + let mem = FaultMem::new(ring.mem()); + let mut producer = RingProducer::new(ring.layout(), mem.clone()); + producer.submit_one(0x1000, 64, false).unwrap(); + + let id_free = producer.id_free.as_ptr(); + let id_num = producer.id_num.as_ptr(); + let slots = SlotLayout::new(ring.layout().end_addr() + 0x100, 64, 3).unwrap(); + let info = BootstrapInfo::prefilled(ring.layout(), PoolLayout::single(slots)).unwrap(); + info.initialize(&mem).unwrap(); + mem.fail_write_at(0); + + producer.refresh(info.avail()); + let fresh = RingProducer::from_bootstrap(info, ring.mem()); + + assert_eq!(producer.id_free.as_ptr(), id_free); + assert_eq!(producer.id_num.as_ptr(), id_num); + assert_eq!(producer.id_free, fresh.id_free); + assert_eq!(producer.id_num, fresh.id_num); + assert_eq!(producer.avail_cursor, fresh.avail_cursor); + assert_eq!(producer.used_cursor, fresh.used_cursor); + assert_eq!(producer.event_flags_shadow, fresh.event_flags_shadow); + assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + } + #[test] fn test_ring_producer_reset_matches_new() { let ring = make_ring(8); diff --git a/src/hyperlight_guest/src/transport/backing.rs b/src/hyperlight_guest/src/transport/backing.rs index fc47d05e0..c3332a295 100644 --- a/src/hyperlight_guest/src/transport/backing.rs +++ b/src/hyperlight_guest/src/transport/backing.rs @@ -15,7 +15,7 @@ use itertools::Itertools; use super::SyncWrap; use crate::paging; -/// Reservations are captured with their aliases and survive pool swaps. +/// Reservations are captured with their aliases and survive transport generations. static ALLOCATOR: SyncWrap> = SyncWrap(RefCell::new(AliasAllocator::new())); // Permissions for transport alias mappings. const PERMISSIONS: BasicMapping = BasicMapping { diff --git a/src/hyperlight_guest/src/transport/context.rs b/src/hyperlight_guest/src/transport/context.rs index 223216fb4..039766ade 100644 --- a/src/hyperlight_guest/src/transport/context.rs +++ b/src/hyperlight_guest/src/transport/context.rs @@ -16,8 +16,8 @@ use hyperlight_common::transport::{ EncodedMessage, ExternalValues, MailboxValue, MsgHeader, MsgKind, }; use hyperlight_common::virtq::{ - AllocError, G2H_LOWER_SLOT_COUNT, G2H_LOWER_SLOT_SIZE, Layout, Notifier, QueueStats, SendChain, - SlotLayout, SlotPool, Token, UsedChain, VirtqError, VirtqProducer, + AllocError, BootstrapInfo, G2H_LOWER_SLOT_COUNT, G2H_LOWER_SLOT_SIZE, Layout, Notifier, + QueueStats, SendChain, SlotLayout, SlotPool, Token, UsedChain, VirtqError, VirtqProducer, }; use hyperlight_common::vmem::PAGE_SIZE; @@ -55,8 +55,7 @@ type H2gProducer = VirtqProducer; pub enum DispatchAction { /// Invoke one guest function and return its correlation ID. Call(u32, FunctionCall), - /// Prepare canonical transport state for snapshot capture. - SnapshotCheckpoint, + // TODO: Add Progress for task and stream rounds. } /// Configuration for one queue passed to [`GuestContext::new`]. @@ -110,7 +109,7 @@ pub struct GuestContext { } impl GuestContext { - /// Create a new context with G2H and H2G queues. + /// Initialize G2H and H2G queues and post receive buffers. /// /// # Safety /// @@ -119,8 +118,9 @@ impl GuestContext { /// at `mbx_gva`. The mailbox must lie in scratch, disjoint from both queues /// and pools. Both rings and pools must lie in the transport arena, which /// starts at the G2H ring and ends below the reserved scratch-top pages, - /// with the pools after the rings. Scratch must remain mapped while the - /// context or any returned buffer views exist. + /// with the pools after the rings. Host consumers must be at their initial + /// cursors. Scratch must remain mapped while the context or any returned + /// buffer views exist. pub unsafe fn new(g2h: QueueConfig, h2g: QueueConfig, mbx_gva: u64) -> Result { // SAFETY: Generation has been initialized by host. let generation = unsafe { layout::snapshot_generation_gva().read_volatile() }; @@ -133,6 +133,9 @@ impl GuestContext { // SAFETY: The caller owns the pool's scratch pages. let mem = unsafe { pool_mem(&g2h_pool, arena_gva, scratch_gva) } .with_context(|| "failed to initialize G2H pool access")?; + g2h.layout + .initialize(&mem) + .with_context(|| "failed to initialize G2H ring")?; let g2h_producer = VirtqProducer::new(g2h.layout, mem, OutbNotifier, g2h_pool); let h2g_pool = h2g_pool(h2g.pool_gva, h2g.pool_pages, h2g.buffer_size) @@ -140,6 +143,9 @@ impl GuestContext { // SAFETY: The caller owns this disjoint pool. let mem = unsafe { pool_mem(&h2g_pool, arena_gva, scratch_gva) } .with_context(|| "failed to initialize H2G pool access")?; + h2g.layout + .initialize(&mem) + .with_context(|| "failed to initialize H2G ring")?; // H2G prefill supplies writable buffers for host-initiated messages. let h2g_producer = VirtqProducer::new(h2g.layout, mem, NoopNotifier, h2g_pool); @@ -265,12 +271,8 @@ impl GuestContext { bail!("H2G buffer has an invalid message header"); }; - match header.kind { - MsgKind::SnapshotCheckpoint => { - return Ok(DispatchAction::SnapshotCheckpoint); - } - MsgKind::Request if header.cid != 0 => {} - _ => bail!("H2G buffer has invalid request framing"), + if header.kind != MsgKind::Request || header.cid == 0 { + bail!("H2G buffer has invalid request framing"); } let payload_len = @@ -334,47 +336,17 @@ impl GuestContext { self.prefill_h2g() } - /// Reset stopped queues while retained values keep their pool slots. - /// - /// The mailbox is complete only after free H2G slots are prefilled. - /// - /// # Safety - /// - /// All host consumer chain handles must be dropped. - /// Both consumers must stay stopped until they are reset or replaced. - pub unsafe fn prepare_snapshot(&mut self) -> Result<()> { - let pending = MailboxValue::CheckpointPending.raw(); - // SAFETY: The host has initialized the mailbox. - unsafe { (self.mbx_gva as *mut u64).write_volatile(pending) }; - - // Read all acks from host - self.g2h_producer - .reclaim() - .with_context(|| "G2H snapshot reclaim failed")?; - - // SAFETY: The caller keeps host consumers quiescent until reset or replacement. - unsafe { - self.g2h_producer - .reset() - .with_context(|| "G2H snapshot reset failed")?; - self.h2g_producer - .reset() - .with_context(|| "H2G snapshot reset failed")?; - } - - self.prefill_h2g()?; - - let compl = MailboxValue::CheckpointComplete.raw(); - // SAFETY: The host has initialized the writable mailbox. - unsafe { (self.mbx_gva as *mut u64).write_volatile(compl) }; - - Ok(()) + /// Publish successful guest initialization at the startup halt. + pub fn complete_initialization(&mut self) { + let status = MailboxValue::InitComplete.raw(); + // SAFETY: Construction requires an exclusively owned, mapped mailbox. + unsafe { (self.mbx_gva as *mut u64).write_volatile(status) }; } - /// Reclaim retained scratch slots after restore without changing the rings. + /// Reconstruct transport ownership for the host's current generation. /// - /// Retained owners keep their captured aliases. Posted chains keep their - /// scratch reservations, including a request written before guest entry. + /// Retained owners keep captured aliases and old pool leases. Private storage + /// is reused without touching requests written by the host before guest entry. pub fn maybe_refresh(&mut self) { // SAFETY: Construction requires initialized guest scratch metadata. let generation = unsafe { layout::snapshot_generation_gva().read_volatile() }; @@ -383,15 +355,24 @@ impl GuestContext { return; } - // SAFETY: Restore gives retained views independent captured backing. - // Only posted chains access scratch. Guest entry excludes peer access. + let g2h = &self.g2h_producer; + let g2h_info = + BootstrapInfo::empty(g2h.layout(), g2h.pool().layout()).expect("invalid G2H bootstrap"); + + let h2g = &self.h2g_producer; + let h2g_info = BootstrapInfo::prefilled(h2g.layout(), h2g.pool().layout()) + .expect("invalid H2G bootstrap"); + + // SAFETY: The host discarded the old queues and installed the matching + // bootstrap with no live chain handles. No producer has run. Retained + // views have captured backing and old pool handles only release leases. unsafe { self.g2h_producer - .reclaim_slots() - .expect("G2H pool recovery failed"); + .refresh(g2h_info) + .expect("G2H ownership reconstruction failed"); self.h2g_producer - .reclaim_slots() - .expect("H2G pool recovery failed"); + .refresh(h2g_info) + .expect("H2G ownership reconstruction failed"); } self.generation = generation; diff --git a/src/hyperlight_guest/src/transport/mod.rs b/src/hyperlight_guest/src/transport/mod.rs index df6f56138..1e0e5eeab 100644 --- a/src/hyperlight_guest/src/transport/mod.rs +++ b/src/hyperlight_guest/src/transport/mod.rs @@ -4,7 +4,7 @@ //! Guest transport context and memory access. //! //! Global context is installed once via [`set_global_context`]. -//! Dispatch starts with [`maybe_refresh`]. Checkpointing uses [`prepare_snapshot`]. +//! Dispatch starts with [`maybe_refresh`]. mod backing; mod codec; @@ -17,8 +17,6 @@ use core::sync::atomic::{AtomicU8, Ordering}; pub use context::{DispatchAction, GuestContext, QueueConfig}; pub(crate) use mem::GuestMemOps; -use crate::error::Result; - const UNINITIALIZED: u8 = 0; const INITIALIZED: u8 = 1; @@ -66,21 +64,14 @@ pub fn set_global_context(context: GuestContext) { *GLOBAL_CONTEXT.0.borrow_mut() = Some(context); } -/// Prepare pool aliases before dispatch, logging, or tracing. +/// Reconstruct generation ownership before dispatch, logging, or tracing. #[inline] pub fn maybe_refresh() { with_ctx(GuestContext::maybe_refresh); } -/// Reset stopped queues and publish snapshot readiness. -/// -/// # Safety -/// -/// The caller must satisfy [`GuestContext::prepare_snapshot`]'s requirements. +/// Publish successful guest initialization at the startup halt. #[inline] -pub unsafe fn prepare_snapshot() -> Result<()> { - with_ctx(|ctx| { - // SAFETY: The caller upholds the checkpoint preconditions. - unsafe { ctx.prepare_snapshot() } - }) +pub fn complete_initialization() { + with_ctx(GuestContext::complete_initialization); } diff --git a/src/hyperlight_guest_bin/src/guest_function/call.rs b/src/hyperlight_guest_bin/src/guest_function/call.rs index dab42d8d8..952899396 100644 --- a/src/hyperlight_guest_bin/src/guest_function/call.rs +++ b/src/hyperlight_guest_bin/src/guest_function/call.rs @@ -86,20 +86,15 @@ pub(crate) fn internal_dispatch_function() { tracing::span!(tracing::Level::INFO, "internal_dispatch_function").entered() }); - let dispatch = transport::with_ctx(|ctx| ctx.recv_h2g_dispatch()) + let DispatchAction::Call(cid, call) = transport::with_ctx(|ctx| ctx.recv_h2g_dispatch()) .expect("H2G dispatch deserialization failed"); - let result = match dispatch { - DispatchAction::Call(cid, fc) => { - // Reseed the libc PRNG if requested by the host. - #[cfg(feature = "libc")] - crate::refresh_libc_rng(); + // Reseed the libc PRNG if requested by the host. + #[cfg(feature = "libc")] + crate::refresh_libc_rng(); - let res = call_guest_function(fc).map_err(|err| GuestError::new(err.kind, err.message)); - Some((cid, FunctionCallResult::new(res))) - } - DispatchAction::SnapshotCheckpoint => None, - }; + let result = call_guest_function(call).map_err(|err| GuestError::new(err.kind, err.message)); + let result = FunctionCallResult::new(result); // All this tracing logic shall be done right before the call to `hlt` which is done after this // function returns @@ -120,16 +115,8 @@ pub(crate) fn internal_dispatch_function() { hyperlight_guest_tracing::flush(); } - match result { - Some((cid, result)) => transport::with_ctx(|ctx| { - ctx.send_h2g_result(cid, result) - .expect("Failed to send function call result"); - }), - None => { - // SAFETY: Host chain accesses are complete. The checkpoint protocol - // keeps consumers stopped until the host resets them. - unsafe { transport::prepare_snapshot() } - .expect("Failed to prepare transport for snapshot"); - } - } + transport::with_ctx(|ctx| { + ctx.send_h2g_result(cid, result) + .expect("Failed to send function call result"); + }); } diff --git a/src/hyperlight_guest_bin/src/lib.rs b/src/hyperlight_guest_bin/src/lib.rs index 8fd9cff22..9dcb8d2e9 100644 --- a/src/hyperlight_guest_bin/src/lib.rs +++ b/src/hyperlight_guest_bin/src/lib.rs @@ -333,10 +333,7 @@ pub(crate) extern "C" fn generic_init(_seed: u64, ops: u64, max_log_level: u64) hyperlight_guest_tracing::flush(); } - // SAFETY: Host calls have returned with no live chain handles. The host - // resets consumers before the next dispatch refreshes aliases. - unsafe { hyperlight_guest::transport::prepare_snapshot() } - .expect("failed to prepare initial transport snapshot"); + hyperlight_guest::transport::complete_initialization(); dispatch_function as *const () as usize as u64 } diff --git a/src/hyperlight_host/src/hypervisor/hyperlight_vm/test_support.rs b/src/hyperlight_host/src/hypervisor/hyperlight_vm/test_support.rs index 08d4c65ff..fa41a258b 100644 --- a/src/hyperlight_host/src/hypervisor/hyperlight_vm/test_support.rs +++ b/src/hyperlight_host/src/hypervisor/hyperlight_vm/test_support.rs @@ -15,6 +15,7 @@ use crate::hypervisor::virtual_machine::{HypervisorError, VirtualMachine}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum VmOperation { + RunVcpu, Map(MemoryRegionType), Unmap(MemoryRegionType), #[cfg(target_arch = "x86_64")] @@ -128,6 +129,10 @@ impl VirtualMachine for FaultInjectingVirtualMachine { &mut self, #[cfg(feature = "trace_guest")] tc: &mut crate::sandbox::trace::TraceContext, ) -> std::result::Result { + if self.should_fail(VmOperation::RunVcpu) { + return Err(RunVcpuError::Unknown(Self::injected_error())); + } + self.inner_mut().run_vcpu( #[cfg(feature = "trace_guest")] tc, diff --git a/src/hyperlight_host/src/mem/layout.rs b/src/hyperlight_host/src/mem/layout.rs index 0543e5abc..a0d0a0c62 100644 --- a/src/hyperlight_host/src/mem/layout.rs +++ b/src/hyperlight_host/src/mem/layout.rs @@ -222,7 +222,7 @@ impl SandboxMemoryLayout { - hyperlight_common::layout::scratch_base_gpa(self.scratch_size)) as usize } - /// Scratch offset of the checkpoint mailbox. + /// Scratch offset of the initialization mailbox. pub(crate) fn mbx_scratch_offset(&self) -> usize { self.arena_scratch_offset() + self.transport_arena.mbx_offset() } diff --git a/src/hyperlight_host/src/mem/mgr.rs b/src/hyperlight_host/src/mem/mgr.rs index 0d28c67b9..0aaafce3d 100644 --- a/src/hyperlight_host/src/mem/mgr.rs +++ b/src/hyperlight_host/src/mem/mgr.rs @@ -347,15 +347,6 @@ impl<'a> GuestVirtualMemoryReader<'a> { } } -/// Guest operations the host accepts during a VM entry. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum ExecutionMode { - /// Guest initialization and guest function calls. - Unrestricted, - /// Snapshot checkpoint preparation. Host function calls are rejected. - Restricted, -} - /// Scratch-top slots the host writes and the guest applies and clears on its /// next entry. const GUEST_REQUEST_OFFSETS: [u64; 2] = [ @@ -381,8 +372,6 @@ pub(crate) struct SandboxMemoryManager { pub(crate) original_entrypoint: u64, /// Buffer for accumulating guest abort messages pub(crate) abort_buffer: Vec, - /// Guest operations the host accepts during the current VM entry. - pub(crate) execution_mode: ExecutionMode, /// Generation counter: how many snapshots have been taken from /// this sandbox's execution path from init to here. Incremented /// on each `snapshot` call; on `restore_snapshot` we inherit the @@ -406,7 +395,6 @@ impl Clone for SandboxMemoryManager { next_action: self.next_action, original_entrypoint: self.original_entrypoint, abort_buffer: self.abort_buffer.clone(), - execution_mode: self.execution_mode, snapshot_count: self.snapshot_count, g2h_consumer: None, h2g_consumer: None, @@ -552,7 +540,6 @@ where next_action, original_entrypoint: 0, abort_buffer: Vec::new(), - execution_mode: ExecutionMode::Unrestricted, snapshot_count: 0, g2h_consumer: None, h2g_consumer: None, @@ -607,7 +594,6 @@ impl SandboxMemoryManager { next_action: self.next_action, original_entrypoint: self.original_entrypoint, abort_buffer: self.abort_buffer, - execution_mode: self.execution_mode, snapshot_count: self.snapshot_count, g2h_consumer: None, h2g_consumer: None, @@ -620,7 +606,6 @@ impl SandboxMemoryManager { next_action: self.next_action, original_entrypoint: self.original_entrypoint, abort_buffer: Vec::new(), // Guest doesn't need abort buffer - execution_mode: self.execution_mode, snapshot_count: self.snapshot_count, g2h_consumer: None, h2g_consumer: None, @@ -629,10 +614,10 @@ impl SandboxMemoryManager { host_mgr.update_scratch_bookkeeping()?; if matches!(host_mgr.next_action, NextAction::Initialise(_)) { - let cp = MailboxValue::CheckpointPending.as_bytes(); + let status = MailboxValue::InitPending.as_bytes(); let mbx = host_mgr.layout.mbx_scratch_offset(); - host_mgr.scratch_mem.copy_from_slice(cp, mbx)?; + host_mgr.scratch_mem.copy_from_slice(status, mbx)?; host_mgr.create_virtq_consumers()?; } @@ -680,8 +665,9 @@ impl SandboxMemoryManager { host_functions: HostFunctionDetails, scratch_size: usize, ) -> Result { + let target = self.layout.with_scratch_size(scratch_size)?; let virtq = match (&self.g2h_consumer, &self.h2g_consumer) { - (Some(_), Some(_)) => Some(VirtqSnapshot::capture(&self.layout, &self.scratch_mem)?), + (Some(_), Some(_)) => Some(VirtqSnapshot::bootstrap(&target)?), (None, None) => None, _ => return Err(new_error!("virtqueue consumer ownership is incomplete")), }; @@ -906,43 +892,20 @@ impl SandboxMemoryManager { } } - /// Publish an internal request for guest-side snapshot canonicalization. - /// - /// The pending marker distinguishes a completed checkpoint from an early halt. - pub(crate) fn begin_snapshot_checkpoint(&mut self) -> Result<()> { - let offset = self.layout.mbx_scratch_offset(); - let cp = MailboxValue::CheckpointPending.as_bytes(); - self.scratch_mem.copy_from_slice(cp, offset)?; - - let message = EncodedMessage::new_snapshot_cp(); - self.write_h2g_message(&message) - } - - /// Reset consumers and require the guest's completion status. - pub(crate) fn finish_snapshot_checkpoint(&mut self) -> Result<()> { - let Some(g2h) = self.g2h_consumer.as_mut() else { - return Err(new_error!("G2H consumer is not attached")); - }; - - let Some(h2g) = self.h2g_consumer.as_mut() else { - return Err(new_error!("H2G consumer is not attached")); - }; - - g2h.reset()?; - h2g.reset()?; - + /// Require successful guest initialization at the startup halt. + pub(crate) fn require_initialization_complete(&self) -> Result<()> { let status = self .scratch_mem .read::(self.layout.mbx_scratch_offset()) .map_err(|error| HyperlightError::TransportError(error.to_string()))?; match MailboxValue::try_from(status) { - Ok(MailboxValue::CheckpointComplete) => Ok(()), - Ok(MailboxValue::CheckpointPending) => Err(HyperlightError::TransportError( - "Guest did not publish snapshot checkpoint status".into(), + Ok(MailboxValue::InitComplete) => Ok(()), + Ok(MailboxValue::InitPending) => Err(HyperlightError::TransportError( + "Guest did not complete initialization".into(), )), Err(_) => Err(HyperlightError::TransportError(format!( - "Guest published invalid snapshot checkpoint status {status:#x}" + "Guest published invalid initialization status {status:#x}" ))), } } @@ -970,7 +933,7 @@ impl SandboxMemoryManager { self.original_entrypoint = snapshot.original_entrypoint(); } - /// Installs memory produced by a capture without restoring runtime state. + /// Install captured memory and fresh transport ownership. /// /// A capture with another scratch size moves the scratch base and page /// tables. It gets new scratch, which the caller maps. @@ -987,11 +950,21 @@ impl SandboxMemoryManager { self.set_guest_requests(requests)?; return Ok(memory); } + + let virtq = snapshot + .virtq() + .ok_or_else(|| new_error!("running snapshot has no canonical transport state"))?; + let used_scratch_end = self.used_scratch_end_gpa()?; let gsnapshot = self.replace_snapshot_memory(snapshot)?; + + self.g2h_consumer = None; + self.h2g_consumer = None; self.apply_snapshot_metadata(snapshot); self.update_snapshot_scratch_bookkeeping()?; self.zero_freed_scratch(used_scratch_end)?; + self.restore_virtq(virtq)?; + Ok((gsnapshot, None)) } @@ -1046,10 +1019,6 @@ impl SandboxMemoryManager { self.g2h_consumer = None; self.h2g_consumer = None; - self.execution_mode = ExecutionMode::Unrestricted; - - // A panic during restricted dispatch can skip the mode reset. - self.execution_mode = ExecutionMode::Unrestricted; let gsnapshot = self.replace_snapshot_memory(snapshot)?; let new_scratch_size = snapshot.layout().get_scratch_size(); @@ -1074,7 +1043,7 @@ impl SandboxMemoryManager { self.restore_virtq(virtq)?; } else if matches!(snapshot.next_action(), NextAction::Initialise(_)) { self.scratch_mem.copy_from_slice( - MailboxValue::CheckpointPending.as_bytes(), + MailboxValue::InitPending.as_bytes(), self.layout.mbx_scratch_offset(), )?; self.create_virtq_consumers()?; @@ -1306,12 +1275,13 @@ impl SandboxMemoryManager { #[cfg(test)] mod tests { + use std::assert_matches; use std::sync::Arc; use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCallType; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; use hyperlight_common::transport::MsgHeader; - use hyperlight_common::virtq::DescFlags; + use hyperlight_common::virtq::{DescFlags, SlotLayout, SlotPool, VirtqProducer}; use hyperlight_common::vmem::{self, BasicMapping, Mapping, MappingKind, PAGE_SIZE}; #[cfg(target_arch = "x86_64")] use hyperlight_testing::sandbox_sizes::{ @@ -1326,6 +1296,7 @@ mod tests { use crate::mem::layout::SandboxMemoryLayout; use crate::mem::memory_region::MemoryRegionType; use crate::mem::shared_mem::{ExclusiveSharedMemory, ReadonlySharedMemory}; + use crate::mem::virtq::HostNotifier; use crate::mem::virtq::tests::{H2G_BUFFER_SIZE, SCRATCH_SIZE, TestCase, memory_layout}; use crate::sandbox::SandboxConfiguration; #[cfg(target_arch = "x86_64")] @@ -1476,73 +1447,72 @@ mod tests { } #[test] - fn writes_header_only_snapshot_checkpoint() { + fn incomplete_initialization_is_fatal() { let case = TestCase::new(); - let mut mgr = manager(&case); - let buffer = case.h2g_desc(0).addr; - - let mbx = mgr.layout.mbx_scratch_offset(); - let cp = MailboxValue::CheckpointComplete.as_bytes(); + let mgr = manager(&case); - mgr.scratch_mem.copy_from_slice(cp, mbx).unwrap(); - mgr.begin_snapshot_checkpoint().unwrap(); + let error = mgr.require_initialization_complete().unwrap_err(); - let wire = case.h2g_buffer(0, buffer); - let header = MsgHeader::from_bytes(&wire).unwrap(); - - assert_eq!(wire.len(), MsgHeader::SIZE); - assert_eq!(header.kind, MsgKind::SnapshotCheckpoint); - assert_eq!(header.cid, 0); - assert_eq!(header.payload_len, 0); - assert_eq!(mgr.next_guest_cid, 1); - - assert_eq!( - MailboxValue::try_from(mgr.scratch_mem.read::(mbx).unwrap()).unwrap(), - MailboxValue::CheckpointPending - ); + assert_matches!(error, HyperlightError::TransportError(_)); + assert!(error.is_poison_error()); } #[test] - fn incomplete_snapshot_checkpoint_is_fatal() { + fn initialization_status_preserves_consumer_cursors() { let case = TestCase::new(); let mut mgr = manager(&case); mgr.g2h_consumer = Some(case.g2h_consumer()); - mgr.begin_snapshot_checkpoint().unwrap(); + mgr.write_guest_function_call(&h2g_call(0)).unwrap(); - let error = mgr.finish_snapshot_checkpoint().unwrap_err(); + let pool = SlotPool::new(SlotLayout::new(case.g2h_pool_base, 64, 1).unwrap()).unwrap(); + let mut producer = + VirtqProducer::new(case.g2h_layout, case.mem.clone(), HostNotifier, pool); + let chain = producer.chain().writable(64).build().unwrap(); + producer.submit(chain).unwrap(); - assert!(matches!(error, HyperlightError::TransportError(_))); - assert!(error.is_poison_error()); - } + let consumer = mgr.g2h_consumer.as_mut().unwrap(); + let (recv, reply) = consumer.poll(0).unwrap().unwrap(); + consumer.complete(recv, reply).unwrap(); + let g2h_avail = consumer.avail_cursor(); + let g2h_used = consumer.used_cursor(); + assert_ne!(g2h_avail.head(), 0); + + let consumer = mgr.h2g_consumer.as_ref().unwrap(); + let h2g_avail = consumer.avail_cursor(); + let h2g_used = consumer.used_cursor(); + assert_ne!(h2g_avail.head(), 0); - #[test] - fn reads_completed_snapshot_checkpoint_status() { - let case = TestCase::new(); - let mut mgr = manager(&case); - mgr.g2h_consumer = Some(case.g2h_consumer()); - mgr.begin_snapshot_checkpoint().unwrap(); let mbx = mgr.layout.mbx_scratch_offset(); mgr.scratch_mem - .copy_from_slice(MailboxValue::CheckpointComplete.as_bytes(), mbx) + .copy_from_slice(MailboxValue::InitComplete.as_bytes(), mbx) .unwrap(); - mgr.finish_snapshot_checkpoint().unwrap(); + mgr.require_initialization_complete().unwrap(); + + let consumer = mgr.g2h_consumer.as_ref().unwrap(); + assert_eq!(consumer.avail_cursor(), g2h_avail); + assert_eq!(consumer.used_cursor(), g2h_used); + let consumer = mgr.h2g_consumer.as_ref().unwrap(); - assert_eq!(consumer.avail_cursor().head(), 0); - assert_eq!(consumer.used_cursor().head(), 0); + assert_eq!(consumer.avail_cursor(), h2g_avail); + assert_eq!(consumer.used_cursor(), h2g_used); + assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 2); + + // SAFETY: All G2H chains are complete and the consumer is stopped. + unsafe { producer.retire() }.unwrap(); } #[test] - fn invalid_checkpoint_status_is_fatal() { + fn invalid_initialization_status_is_fatal() { for status in [2, 3, 0xa000, u64::MAX - 1, u64::MAX] { let queue = TestCase::new(); let mut mgr = manager(&queue); mgr.g2h_consumer = Some(queue.g2h_consumer()); let mbx = mgr.layout.mbx_scratch_offset(); mgr.scratch_mem.write::(mbx, status).unwrap(); - let error = mgr.finish_snapshot_checkpoint().unwrap_err(); + let error = mgr.require_initialization_complete().unwrap_err(); - assert!(matches!(error, HyperlightError::TransportError(_))); + assert_matches!(error, HyperlightError::TransportError(_)); assert!(error.is_poison_error(), "{error}"); } } @@ -1581,7 +1551,7 @@ mod tests { let case = TestCase::new(); let mut mgr = manager(&case); mgr.g2h_consumer = Some(case.g2h_consumer()); - let captured = VirtqSnapshot::capture(&mgr.layout, &mgr.scratch_mem).unwrap(); + let captured = VirtqSnapshot::bootstrap(&mgr.layout).unwrap(); assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 1); mgr.g2h_consumer = None; diff --git a/src/hyperlight_host/src/mem/virtq/mem.rs b/src/hyperlight_host/src/mem/virtq/mem.rs index c3599da61..e004d8a88 100644 --- a/src/hyperlight_host/src/mem/virtq/mem.rs +++ b/src/hyperlight_host/src/mem/virtq/mem.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2026 The Hyperlight Authors. -//! Host [`MemOps`] implementations for scratch and captured ring images. +//! Host [`MemOps`] implementations for scratch and private ring images. //! //! Live scratch operations use [`HostSharedMemory`]'s checked API and acquire //! its lifecycle read lock. This preserves exclusive-memory coordination but //! makes descriptor traversal pay for one lock acquisition per field access. +use core::cell::RefCell; use core::mem::{align_of, size_of}; +use core::ops::Range; use core::sync::atomic::{AtomicU16, Ordering}; use hyperlight_common::layout::scratch_base_gva; @@ -90,33 +92,51 @@ unsafe impl MemOps for HostMemOps { } } -/// Read-only ring image addressed by its guest virtual base. +/// Private ring image addressed by its guest virtual base. pub(super) struct ImageMem<'a> { base: u64, - bytes: &'a [u8], + bytes: RefCell<&'a mut [u8]>, } impl<'a> ImageMem<'a> { - pub(super) fn new(base: u64, bytes: &'a [u8]) -> Self { - Self { base, bytes } + /// Bind an exclusively borrowed image for single-threaded initialization. + pub(super) fn new(base: u64, bytes: &'a mut [u8]) -> Self { + Self { + base, + bytes: RefCell::new(bytes), + } } - fn slice(&self, addr: u64, len: usize) -> Result<&[u8]> { + /// Translate a guest address into a checked image range. + fn range(&self, addr: u64, len: usize) -> Result> { let out_of_bounds = || new_error!("image memory access is out of bounds"); let offset = addr.checked_sub(self.base).ok_or_else(out_of_bounds)?; let offset = usize::try_from(offset).map_err(|_| out_of_bounds())?; let end = offset.checked_add(len).ok_or_else(out_of_bounds)?; - self.bytes.get(offset..end).ok_or_else(out_of_bounds) + + if end > self.bytes.borrow().len() { + return Err(out_of_bounds()); + } + + Ok(offset..end) } } -// SAFETY: Reads stay within immutable host-owned bytes. Atomic loads check -// alignment, writes fail, and returned slices borrow the backing image. +// SAFETY: Copies stay within exclusively borrowed host storage. RefCell excludes +// concurrent access, so aligned flag operations need no cross-thread ordering. +// Borrowed slices are unsupported. unsafe impl MemOps for ImageMem<'_> { type Error = HyperlightError; fn read(&self, addr: u64, dst: &mut [u8]) -> Result<()> { - dst.copy_from_slice(self.slice(addr, dst.len())?); + let range = self.range(addr, dst.len())?; + dst.copy_from_slice(&self.bytes.borrow()[range]); + Ok(()) + } + + fn write(&self, addr: u64, src: &[u8]) -> Result<()> { + let range = self.range(addr, src.len())?; + self.bytes.borrow_mut()[range].copy_from_slice(src); Ok(()) } @@ -129,26 +149,28 @@ unsafe impl MemOps for ImageMem<'_> { Ok(u16::from_ne_bytes(bytes)) } - unsafe fn as_slice(&self, addr: u64, len: usize) -> Result<&[u8]> { - self.slice(addr, len) - } + fn store_release(&self, addr: u64, val: u16) -> Result<()> { + if !addr.is_multiple_of(align_of::() as u64) { + return Err(new_error!("image atomic access is unaligned")); + } - fn write(&self, _addr: u64, _src: &[u8]) -> Result<()> { - Err(new_error!("image memory is read-only")) + self.write(addr, &val.to_ne_bytes()) } - fn store_release(&self, _addr: u64, _val: u16) -> Result<()> { - Err(new_error!("image memory is read-only")) + unsafe fn as_slice(&self, _addr: u64, _len: usize) -> Result<&[u8]> { + Err(new_error!("borrowed image access is unsupported")) } #[allow(clippy::mut_from_ref)] unsafe fn as_mut_slice(&self, _addr: u64, _len: usize) -> Result<&mut [u8]> { - Err(new_error!("image memory is read-only")) + Err(new_error!("borrowed image access is unsupported")) } } #[cfg(test)] mod tests { + use std::assert_matches; + use hyperlight_common::virtq::MemOps; use super::*; @@ -209,9 +231,9 @@ mod tests { } #[test] - fn image_access_is_bounded_and_read_only() { - let bytes = [1, 2, 3, 4]; - let mem = ImageMem::new(0x1000, &bytes); + fn image_access_is_bounded() { + let mut bytes = [1, 2, 3, 4]; + let mem = ImageMem::new(0x1000, &mut bytes); let mut read = [0; 2]; mem.read(0x1002, &mut read).unwrap(); assert_eq!(read, [3, 4]); @@ -219,12 +241,20 @@ mod tests { mem.load_acquire(0x1000).unwrap(), u16::from_ne_bytes([1, 2]) ); - assert!(mem.load_acquire(0x1001).is_err()); - assert!(mem.read(0xfff, &mut read).is_err()); - assert!(mem.read(0x1003, &mut read).is_err()); - assert!(mem.read(u64::MAX, &mut read).is_err()); - assert!(mem.slice(0x1001, usize::MAX).is_err()); - assert!(mem.write(0x1000, &[0]).is_err()); - assert!(mem.store_release(0x1000, 0).is_err()); + assert_matches!(mem.load_acquire(0x1001), Err(_)); + assert_matches!(mem.read(0xfff, &mut read), Err(_)); + assert_matches!(mem.read(0x1003, &mut read), Err(_)); + assert_matches!(mem.read(u64::MAX, &mut read), Err(_)); + assert_matches!(mem.range(0x1001, usize::MAX), Err(_)); + + mem.write(0x1002, &[5, 6]).unwrap(); + mem.read(0x1002, &mut read).unwrap(); + assert_eq!(read, [5, 6]); + + mem.store_release(0x1000, 0x1234).unwrap(); + assert_eq!(mem.load_acquire(0x1000).unwrap(), 0x1234); + assert_matches!(mem.write(0x1003, &[5, 6]), Err(_)); + assert_matches!(mem.store_release(0x1001, 0), Err(_)); + assert_matches!(mem.store_release(0x1004, 0), Err(_)); } } diff --git a/src/hyperlight_host/src/mem/virtq/mod.rs b/src/hyperlight_host/src/mem/virtq/mod.rs index fd2c623a8..0bf62f76b 100644 --- a/src/hyperlight_host/src/mem/virtq/mod.rs +++ b/src/hyperlight_host/src/mem/virtq/mod.rs @@ -10,21 +10,20 @@ //! untrusted guest requests and results into host-owned values before use. //! Shared wire framing lives in `hyperlight_common::transport`. //! -//! Snapshots require canonical rings with empty G2H and H2G free-slot prefill. -//! Each H2G chain contains one writable descriptor naming a distinct, -//! configured-size slot aligned relative to the H2G pool start. +//! Snapshots contain deterministic bootstrap images with empty G2H and full +//! H2G prefill. Guest entry reconstructs their producer ownership. mod codec; mod mem; #[cfg(test)] pub(crate) mod tests; -use std::collections::HashSet; - pub(crate) use codec::{RecvMessage, try_write_response}; use hyperlight_common::transport::MailboxValue; -use hyperlight_common::virtq::canonical::{validate_canon_image, validate_canon_prefix}; -use hyperlight_common::virtq::{Layout as VirtqLayout, Notifier, QueueStats, VirtqConsumer}; +use hyperlight_common::virtq::{ + BootstrapInfo, Layout as VirtqLayout, Notifier, PoolLayout, QueueStats, SlotLayout, + VirtqConsumer, +}; use mem::{HostMemOps, ImageMem}; use super::layout::SandboxMemoryLayout; @@ -72,7 +71,7 @@ pub(crate) struct VirtqSnapshot { } impl VirtqSnapshot { - /// Validate captured or decoded rings against the final transport geometry. + /// Validate decoded rings against the final transport geometry. pub(crate) fn new( layout: &SandboxMemoryLayout, g2h_ring: Vec, @@ -84,28 +83,33 @@ impl VirtqSnapshot { Ok(snapshot) } - /// Capture and validate rings against the final transport geometry. - /// - /// The guest must stay stopped through memory capture. - pub(crate) fn capture( - layout: &SandboxMemoryLayout, - scratch_mem: &HostSharedMemory, - ) -> Result { - let (g2h_offset, h2g_offset) = ring_offsets(layout); + /// Build bootstrap images without accessing live guest memory. + pub(crate) fn bootstrap(layout: &SandboxMemoryLayout) -> Result { + let (g2h, h2g) = ring_layouts(layout)?; + let h2g_dims = layout.get_h2g_queue_dims(); + let buffer_size = layout.get_h2g_buffer_size(); - let g2h_ring = read_ring( - scratch_mem, - g2h_offset, - layout.get_g2h_queue_dims().ring_len(), - )?; + let (_, _, _, pool_offset, _) = layout.get_transport_arena().to_offsets(); + let slots = SlotLayout::new( + g2h.desc_table_addr() + pool_offset as u64, + buffer_size, + h2g_dims.pool_len() / buffer_size, + ) + .map_err(|error| new_error!("invalid H2G bootstrap pool: {error}"))?; + + let info = BootstrapInfo::prefilled(h2g, PoolLayout::single(slots)) + .map_err(|error| new_error!("invalid H2G bootstrap: {error}"))?; + + let mut g2h_ring = vec![0; layout.get_g2h_queue_dims().ring_len()]; + let mut h2g_ring = vec![0; h2g_dims.ring_len()]; + + g2h.initialize(&ImageMem::new(g2h.desc_table_addr(), &mut g2h_ring)) + .map_err(|error| new_error!("G2H bootstrap initialization failed: {error}"))?; - let h2g_ring = read_ring( - scratch_mem, - h2g_offset, - layout.get_h2g_queue_dims().ring_len(), - )?; + info.initialize(&ImageMem::new(h2g.desc_table_addr(), &mut h2g_ring)) + .map_err(|error| new_error!("H2G bootstrap initialization failed: {error}"))?; - Self::new(layout, g2h_ring, h2g_ring) + Ok(Self { g2h_ring, h2g_ring }) } /// Canonical guest-to-host ring bytes. @@ -126,17 +130,17 @@ impl VirtqSnapshot { ) -> Result<(G2hConsumer, H2gConsumer)> { let (g2h_offset, h2g_offset) = ring_offsets(layout); let mbx_offset = layout.mbx_scratch_offset(); - let cp = MailboxValue::CheckpointComplete.as_bytes(); + let status = MailboxValue::InitComplete.as_bytes(); write_published_arena_gpa(scratch_mem, layout.get_transport_arena().base_addr())?; scratch_mem.copy_from_slice(&self.g2h_ring, g2h_offset)?; scratch_mem.copy_from_slice(&self.h2g_ring, h2g_offset)?; - scratch_mem.copy_from_slice(cp, mbx_offset)?; + scratch_mem.copy_from_slice(status, mbx_offset)?; create_consumers(layout, scratch_mem) } - /// Check geometry, canonical rings, and distinct, aligned H2G pool slots. + /// Require the descriptor order, prefill depth, and events used by adoption. fn validate(&self, layout: &SandboxMemoryLayout) -> Result<()> { if self.g2h_ring.len() != layout.get_g2h_queue_dims().ring_len() || self.h2g_ring.len() != layout.get_h2g_queue_dims().ring_len() @@ -146,47 +150,17 @@ impl VirtqSnapshot { )); } - let (g2h, h2g) = ring_layouts(layout)?; - let g2h_mem = ImageMem::new(g2h.desc_table_addr(), &self.g2h_ring); - - validate_canon_image(&g2h_mem, g2h, 0, |_, _| false) - .map_err(|error| new_error!("invalid canonical G2H image: {error}"))?; + let expected = Self::bootstrap(layout)?; - let buffer_size = layout.get_h2g_buffer_size(); - let h2g_dims = layout.get_h2g_queue_dims(); - - let max_prefill = usize::from(h2g_dims.size().get()).min(h2g_dims.pool_len() / buffer_size); - let h2g_mem = ImageMem::new(h2g.desc_table_addr(), &self.h2g_ring); - - let (_, _, _, pool_offset, _) = layout.get_transport_arena().to_offsets(); - let pool_start = g2h.desc_table_addr() + pool_offset as u64; - let pool_end = pool_start + h2g_dims.pool_len() as u64; - let mut seen_slots = HashSet::with_capacity(max_prefill); - - let chains = validate_canon_prefix(&h2g_mem, h2g, max_prefill, |_, elem| { - if !elem.writable || usize::try_from(elem.len).ok() != Some(buffer_size) { - return false; - } - - let Some(offset) = elem.addr.checked_sub(pool_start) else { - return false; - }; - - let Some(end) = elem.addr.checked_add(u64::from(elem.len)) else { - return false; - }; - - if !offset.is_multiple_of(buffer_size as u64) || end > pool_end { - return false; - } - - seen_slots.insert(offset) - }) - .map_err(|error| new_error!("invalid canonical H2G image: {error}"))?; + if self.g2h_ring != expected.g2h_ring { + return Err(new_error!( + "invalid canonical G2H image: does not match bootstrap" + )); + } - if chains.iter().any(|chain| chain.buffers().len() != 1) { + if self.h2g_ring != expected.h2g_ring { return Err(new_error!( - "H2G snapshot chains must contain one descriptor" + "invalid canonical H2G image: does not match bootstrap" )); } @@ -217,12 +191,6 @@ fn write_published_arena_gpa(scratch_mem: &HostSharedMemory, arena_gpa: u64) -> Ok(scratch_mem.write::(scratch_mem.mem_size() - offset, arena_gpa)?) } -fn read_ring(scratch_mem: &HostSharedMemory, offset: usize, len: usize) -> Result> { - let mut bytes = vec![0; len]; - scratch_mem.copy_to_slice(&mut bytes, offset)?; - Ok(bytes) -} - fn ring_offsets(layout: &SandboxMemoryLayout) -> (usize, usize) { let g2h_offset = layout.arena_scratch_offset(); let (h2g_offset, ..) = layout.get_transport_arena().to_offsets(); diff --git a/src/hyperlight_host/src/mem/virtq/tests.rs b/src/hyperlight_host/src/mem/virtq/tests.rs index 9a847f2ab..87a91341f 100644 --- a/src/hyperlight_host/src/mem/virtq/tests.rs +++ b/src/hyperlight_host/src/mem/virtq/tests.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2026 The Hyperlight Authors. +use std::assert_matches; + use hyperlight_common::layout::SCRATCH_TOP_ALLOCATOR_OFFSET; use hyperlight_common::virtq::{ DescFlags, Descriptor, MemOps, RingError, SlotLayout, SlotPool, VirtqError, VirtqProducer, @@ -50,6 +52,8 @@ impl TestCase { } batch.finish_without_notify(); + // SAFETY: No consumer or payload views exist. The pool is only fixture setup. + unsafe { producer.retire() }.unwrap(); write_published_arena_gpa(&scratch, arena.base_addr()).unwrap(); Self { @@ -121,6 +125,20 @@ fn write_desc(mem: &HostMemOps, layout: VirtqLayout, index: u16, desc: Descripto .unwrap(); } +/// Read live rings to exercise snapshot-image admission. +fn read_snapshot( + layout: &SandboxMemoryLayout, + scratch: &HostSharedMemory, +) -> Result { + let (g2h_offset, h2g_offset) = ring_offsets(layout); + let mut g2h = vec![0; layout.get_g2h_queue_dims().ring_len()]; + let mut h2g = vec![0; layout.get_h2g_queue_dims().ring_len()]; + scratch.copy_to_slice(&mut g2h, g2h_offset)?; + scratch.copy_to_slice(&mut h2g, h2g_offset)?; + + VirtqSnapshot::new(layout, g2h, h2g) +} + #[test] fn snapshots_and_restores_rings() { let case = TestCase::new(); @@ -134,19 +152,20 @@ fn snapshots_and_restores_rings() { .copy_from_slice(&[0x5a; 16], spare_offset) .unwrap(); - let captured = VirtqSnapshot::capture(&layout, &case.scratch).unwrap(); + let captured = VirtqSnapshot::bootstrap(&layout).unwrap(); + assert_eq!(read_snapshot(&layout, &case.scratch).unwrap(), captured); let restored = host_scratch(); let allocator = layout.get_pt_base_gpa(); let allocator_offset = restored.mem_size() - SCRATCH_TOP_ALLOCATOR_OFFSET as usize; let mbx_offset = layout.mbx_scratch_offset(); - let cp = MailboxValue::CheckpointPending.as_bytes(); + let status = MailboxValue::InitPending.as_bytes(); restored.write::(allocator_offset, allocator).unwrap(); - restored.copy_from_slice(cp, mbx_offset).unwrap(); + restored.copy_from_slice(status, mbx_offset).unwrap(); let (mut g2h, mut h2g) = captured.restore(&layout, &restored).unwrap(); - let restored_snapshot = VirtqSnapshot::capture(&layout, &restored).unwrap(); + let restored_snapshot = read_snapshot(&layout, &restored).unwrap(); let restored_mem = HostMemOps::new(&restored); let mut pool_bytes = [0; 16]; restored_mem @@ -167,7 +186,7 @@ fn snapshots_and_restores_rings() { let mbx = restored.read::(mbx_offset).unwrap(); assert_eq!( MailboxValue::try_from(mbx).unwrap(), - MailboxValue::CheckpointComplete + MailboxValue::InitComplete ); assert!(g2h.poll(0).unwrap().is_none()); @@ -176,17 +195,14 @@ fn snapshots_and_restores_rings() { drop((g2h, h2g)); captured.restore(&layout, &restored).unwrap(); - assert_eq!( - VirtqSnapshot::capture(&layout, &restored).unwrap(), - captured - ); + assert_eq!(read_snapshot(&layout, &restored).unwrap(), captured); } #[test] fn rejects_snapshot_geometry_mismatches() { let case = TestCase::new(); let layout = memory_layout(); - let captured = VirtqSnapshot::capture(&layout, &case.scratch).unwrap(); + let captured = read_snapshot(&layout, &case.scratch).unwrap(); let g2h = captured.g2h_ring(); let h2g = captured.h2g_ring(); @@ -205,7 +221,7 @@ fn rejects_noncanonical_snapshot_images() { case.mem .write(case.g2h_layout.desc_table_addr(), &[1]) .unwrap(); - let error = VirtqSnapshot::capture(&layout, &case.scratch).unwrap_err(); + let error = read_snapshot(&layout, &case.scratch).unwrap_err(); assert!(error.to_string().contains("invalid canonical G2H image")); case.mem @@ -214,7 +230,7 @@ fn rejects_noncanonical_snapshot_images() { case.mem .write(case.h2g_layout.drv_evt_addr(), &[1]) .unwrap(); - let error = VirtqSnapshot::capture(&layout, &case.scratch).unwrap_err(); + let error = read_snapshot(&layout, &case.scratch).unwrap_err(); assert!(error.to_string().contains("invalid canonical H2G image")); } @@ -235,7 +251,7 @@ fn rejects_h2g_snapshot_buffer_attributes() { ..original }; case.set_h2g_desc(0, desc); - assert!(VirtqSnapshot::capture(&layout, &case.scratch).is_err()); + assert_matches!(read_snapshot(&layout, &case.scratch), Err(_)); } } @@ -251,13 +267,15 @@ fn rejects_h2g_snapshot_duplicate_slots() { second.addr = first.addr; case.set_h2g_desc(1, second); - let error = VirtqSnapshot::capture(&memory_layout(), &case.scratch).unwrap_err(); - assert!(error.to_string().contains("descriptor 1 buffer"), "{error}"); + let error = read_snapshot(&memory_layout(), &case.scratch).unwrap_err(); + assert!( + error.to_string().contains("does not match bootstrap"), + "{error}" + ); } -/// Slot alignment is relative to the pool, and free-list order may vary. #[test] -fn accepts_h2g_snapshot_slot_permutations() { +fn rejects_h2g_snapshot_slot_permutations() { let case = TestCase::new(); let mut first = case.h2g_desc(0); let mut second = case.h2g_desc(1); @@ -268,7 +286,28 @@ fn accepts_h2g_snapshot_slot_permutations() { case.set_h2g_desc(0, first); case.set_h2g_desc(1, second); - VirtqSnapshot::capture(&memory_layout(), &case.scratch).unwrap(); + let error = read_snapshot(&memory_layout(), &case.scratch).unwrap_err(); + assert!( + error.to_string().contains("does not match bootstrap"), + "{error}" + ); +} + +#[test] +fn rejects_h2g_snapshot_id_permutations() { + let case = TestCase::new(); + let mut first = case.h2g_desc(0); + let mut second = case.h2g_desc(1); + + std::mem::swap(&mut first.id, &mut second.id); + case.set_h2g_desc(0, first); + case.set_h2g_desc(1, second); + + let error = read_snapshot(&memory_layout(), &case.scratch).unwrap_err(); + assert!( + error.to_string().contains("does not match bootstrap"), + "{error}" + ); } #[test] @@ -282,9 +321,9 @@ fn rejects_h2g_snapshot_chain_shape() { case.set_h2g_desc(0, head); case.set_h2g_desc(1, tail); - let error = VirtqSnapshot::capture(&layout, &case.scratch).unwrap_err(); + let error = read_snapshot(&layout, &case.scratch).unwrap_err(); assert!( - error.to_string().contains("must contain one descriptor"), + error.to_string().contains("does not match bootstrap"), "{error}" ); } @@ -327,7 +366,7 @@ fn payload_bounds_are_checked_on_use() { let case = TestCase::new(); let layout = memory_layout(); let end = hyperlight_common::layout::scratch_base_gva(SCRATCH_SIZE) + SCRATCH_SIZE as u64; - let captured = VirtqSnapshot::capture(&layout, &case.scratch).unwrap(); + let captured = VirtqSnapshot::bootstrap(&layout).unwrap(); let restored = host_scratch(); let (mut g2h, mut h2g) = captured.restore(&layout, &restored).unwrap(); let mem = HostMemOps::new(&restored); @@ -372,24 +411,25 @@ fn malformed_descriptors_fail_when_polled() { } #[test] -fn restores_partially_prefilled_h2g_ring() { - for prefill in 0..=4 { - let case = TestCase::new(); - - for index in prefill..4 { - case.set_h2g_desc(index, Descriptor::new(0, 0, 0, DescFlags::empty())); - } +fn rejects_partially_prefilled_h2g_snapshot() { + let case = TestCase::new(); + case.set_h2g_desc(3, Descriptor::new(0, 0, 0, DescFlags::empty())); - let layout = memory_layout(); - let captured = VirtqSnapshot::capture(&layout, &case.scratch).unwrap(); - let restored = host_scratch(); - let (_, mut consumer) = captured.restore(&layout, &restored).unwrap(); + let error = read_snapshot(&memory_layout(), &case.scratch).unwrap_err(); + assert!( + error.to_string().contains("does not match bootstrap"), + "{error}" + ); +} - for _ in 0..prefill { - let (request, reply) = consumer.poll(0).unwrap().unwrap(); - consumer.complete(request, reply).unwrap(); - } +#[test] +fn rejects_empty_h2g_snapshot() { + let case = TestCase::new(); + case.h2g_layout.initialize(&case.mem).unwrap(); - assert!(consumer.poll(0).unwrap().is_none()); - } + let error = read_snapshot(&memory_layout(), &case.scratch).unwrap_err(); + assert!( + error.to_string().contains("does not match bootstrap"), + "{error}" + ); } diff --git a/src/hyperlight_host/src/sandbox/initialized.rs b/src/hyperlight_host/src/sandbox/initialized.rs index 6fe9ca3c9..f9018ed67 100644 --- a/src/hyperlight_host/src/sandbox/initialized.rs +++ b/src/hyperlight_host/src/sandbox/initialized.rs @@ -22,7 +22,7 @@ use crate::func::{ParameterTuple, SupportedReturnType}; use crate::hypervisor::InterruptHandle; use crate::hypervisor::hyperlight_vm::{HyperlightVm, HyperlightVmError}; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; -use crate::mem::mgr::{ExecutionMode, SandboxMemoryManager}; +use crate::mem::mgr::SandboxMemoryManager; use crate::mem::shared_mem::{HostSharedMemory, SharedMemory as _}; use crate::metrics::{ METRIC_GUEST_ERROR, METRIC_GUEST_ERROR_LABEL_CODE, maybe_time_and_emit_guest_call, @@ -89,8 +89,6 @@ pub struct Sandbox { /// If the current state of the sandbox has been captured in a snapshot, /// that snapshot is stored here. pub(crate) snapshot: Option>, - /// Whether the transport needs a checkpoint before snapshot capture. - transport_dirty: bool, /// Optional callback to discover page table roots from guest memory. /// Given (snapshot_mem, scratch_mem, cr3), returns a list of root GPAs. /// If not set, only CR3 is used as the single root. @@ -163,16 +161,12 @@ impl Sandbox { vm: HyperlightVm, config: crate::sandbox::SandboxConfiguration, ) -> Sandbox { - // Initialization can log or call the host before the first guest call. - let transport_dirty = matches!(mgr.next_action, super::snapshot::NextAction::Initialise(_)); - Self { status: SandboxStatus::Ready, host_funcs, mem_mgr: mgr, vm, snapshot: None, - transport_dirty, pt_root_finder: None, config, } @@ -339,7 +333,7 @@ impl Sandbox { snapshot.next_action(), super::snapshot::NextAction::Initialise(_) ) { - hshm.finish_snapshot_checkpoint()?; + hshm.require_initialization_complete()?; } if matches!(snapshot.next_action(), super::snapshot::NextAction::Call(_)) { @@ -492,7 +486,6 @@ impl Sandbox { return self.capture_snapshot(scratch_size); } - // Reject a bad size before the capture enters the guest. self.mem_mgr.layout.with_scratch_size(scratch_size)?; self.capture_snapshot(scratch_size) } @@ -500,9 +493,7 @@ impl Sandbox { /// Capture a snapshot whose scratch has `scratch_size` bytes. The sandbox /// continues from it. fn capture_snapshot(&mut self, scratch_size: usize) -> Result> { - if self.transport_dirty { - self.checkpoint_transport_for_snapshot()?; - } + self.mem_mgr.abort_buffer.clear(); let mapped_regions_iter = self.vm.get_mapped_regions(); let mapped_regions_vec: Vec = mapped_regions_iter.cloned().collect(); @@ -589,18 +580,6 @@ impl Sandbox { Ok(snapshot) } - fn checkpoint_transport_for_snapshot(&mut self) -> Result<()> { - self.with_guest_execution(|sbox| { - sbox.mem_mgr.begin_snapshot_checkpoint()?; - sbox.dispatch_guest_call_restricted()?; - - sbox.mem_mgr.finish_snapshot_checkpoint()?; - - sbox.transport_dirty = false; - Ok(()) - }) - } - fn remove_dynamic_mappings(&mut self) -> Result<()> { let regions = self.vm.get_mapped_regions().cloned().collect::>(); for region in ®ions { @@ -801,7 +780,6 @@ impl Sandbox { // The restored snapshot is now our most current snapshot self.snapshot = Some(snapshot.clone()); - self.transport_dirty = false; // Clear poison state when successfully restoring from snapshot. // @@ -1141,8 +1119,6 @@ impl Sandbox { ) -> Result { self.check_ready()?; self.with_guest_execution(|sbox| { - sbox.transport_dirty = true; - let fc = FunctionCall::new( function_name.to_string(), Some(args), @@ -1200,15 +1176,6 @@ impl Sandbox { }) } - /// Dispatch in restricted mode, then restore the previous mode. - fn dispatch_guest_call_restricted(&mut self) -> Result<()> { - let mode = std::mem::replace(&mut self.mem_mgr.execution_mode, ExecutionMode::Restricted); - let res = self.dispatch_guest_call(); - self.mem_mgr.execution_mode = mode; - - res - } - /// Returns a handle for interrupting guest execution. /// /// # Examples @@ -1451,10 +1418,9 @@ fn warn_on_layout_override( mod tests { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier}; - use std::thread; + use std::{assert_matches, thread}; use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, FunctionCallType}; - use hyperlight_common::flatbuffer_wrappers::function_types::ParameterValue; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_common::func::{Bytes, SupportedReturnType}; use hyperlight_testing::sandbox_sizes::{ @@ -1467,7 +1433,6 @@ mod tests { #[cfg(not(gdb))] use crate::hypervisor::hyperlight_vm::test_support::VmOperation; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags, MemoryRegionType}; - use crate::mem::mgr::ExecutionMode; use crate::mem::shared_mem::{ExclusiveSharedMemory, GuestSharedMemory, SharedMemory as _}; use crate::sandbox::SandboxConfiguration; use crate::sandbox::snapshot::{Snapshot, SnapshotOptions}; @@ -1555,14 +1520,10 @@ mod tests { sbox.snapshot_with_options(&scratch(32 << 30)), Err(HyperlightError::MemoryRequestTooBig(..)) )); - // Rejected sizes do not enter the guest: a pending transport - // checkpoint, which a capture would run, is still pending. let echo: String = sbox.call("Echo", "still".to_string()).unwrap(); assert_eq!(echo, "still"); - assert!(sbox.transport_dirty); assert!(sbox.snapshot_with_options(&scratch(4096)).is_err()); assert!(sbox.snapshot_with_options(&scratch(32 << 30)).is_err()); - assert!(sbox.transport_dirty); // A size with room for the transport but not the page tables fails // when the snapshot is built, and leaves the sandbox usable. @@ -1716,7 +1677,6 @@ mod tests { // After the churn the sandbox can still resize, back to 8 MiB, // and hold chunks there. let back = sbox.snapshot_with_options(&scratch(8 << 20)).unwrap(); - assert!(!sbox.transport_dirty); sbox.restore(back).unwrap(); assert_eq!(sbox.mem_mgr.scratch_mem.mem_size(), 8 << 20); let last = chunks(seed + 0x21); @@ -2166,41 +2126,56 @@ mod tests { } #[test] - fn snapshots_checkpoint_only_dirty_transport() { + fn snapshots_cache_until_guest_state_changes() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) .build() .unwrap(); - assert!(sandbox.transport_dirty); let initial = sandbox.snapshot().unwrap(); - assert!(!sandbox.transport_dirty); - let restored = SandboxBuilder::from_snapshot(initial).build().unwrap(); - assert!(!restored.transport_dirty); + sandbox.restore(initial.clone()).unwrap(); + assert!(Arc::ptr_eq(&initial, &sandbox.snapshot().unwrap())); sandbox.call::("AddToStatic", 5i32).unwrap(); - assert!(sandbox.transport_dirty); let first = sandbox.snapshot().unwrap(); - assert!(!sandbox.transport_dirty); + assert!(!Arc::ptr_eq(&initial, &first)); + let cached = sandbox.snapshot().unwrap(); assert!(Arc::ptr_eq(&first, &cached)); - assert!(!sandbox.transport_dirty); sandbox.call::("AddToStatic", 5i32).unwrap(); - assert!(sandbox.transport_dirty); - sandbox.snapshot().unwrap(); - assert!(!sandbox.transport_dirty); + + let next = sandbox.snapshot().unwrap(); + assert!(!Arc::ptr_eq(&first, &next)); + assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 10); } #[test] - fn snapshots_reject_noncanonical_transport_after_checkpoint() { + #[cfg(not(gdb))] + fn snapshot_capture_does_not_enter_guest() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) .build() .unwrap(); + sandbox.call::("AddToStatic", 42i32).unwrap(); - sandbox.checkpoint_transport_for_snapshot().unwrap(); - sandbox.snapshot = None; + let fault_plan = sandbox.vm.inject_vm_faults([VmOperation::RunVcpu]); + let snapshot = sandbox.snapshot().unwrap(); + assert!(!fault_plan.is_consumed()); + assert_eq!(sandbox.status(), SandboxStatus::Ready); + + assert!(sandbox.call::("GetStatic", ()).is_err()); + assert!(fault_plan.is_consumed()); + + let mut clone = SandboxBuilder::from_snapshot(snapshot).build().unwrap(); + assert_eq!(clone.call::("GetStatic", ()).unwrap(), 42); + } + + #[test] + fn snapshots_generate_bootstrap_independently_of_live_rings() { + let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) + .build() + .unwrap(); let generation = sandbox.mem_mgr.snapshot_count; let ring = sandbox.mem_mgr.layout.get_transport_arena().g2h_ring_addr(); @@ -2210,26 +2185,17 @@ mod tests { sandbox.mem_mgr.scratch_mem.write::(offset, 1).unwrap(); - let Err(error) = sandbox.snapshot() else { - panic!("expected invalid canonical transport"); - }; - - assert!( - error.to_string().contains("invalid canonical G2H image"), - "{error}" - ); - assert_eq!(sandbox.mem_mgr.snapshot_count, generation); - assert!(sandbox.snapshot.is_none()); + sandbox.snapshot().unwrap(); + assert_eq!(sandbox.mem_mgr.snapshot_count, generation + 1); + assert!(sandbox.snapshot.is_some()); - // Restore the canonical descriptor before continuing the source. - sandbox.mem_mgr.scratch_mem.write::(offset, 0).unwrap(); let expected = vec![0x5a; 2 * hyperlight_common::vmem::PAGE_SIZE + 137]; let actual: Vec = sandbox.call("EchoGuestVecBytes", expected.clone()).unwrap(); assert_eq!(actual, expected); } #[test] - fn snapshot_checkpoint_ignores_idle_cancellation() { + fn snapshot_ignores_idle_cancellation() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) .build() .unwrap(); @@ -2239,13 +2205,12 @@ mod tests { sandbox.snapshot().unwrap(); assert_eq!(sandbox.status(), SandboxStatus::Ready); - assert!(!sandbox.transport_dirty); assert!(!sandbox.interrupt_handle().kill()); assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 5); } #[test] - fn snapshot_checkpoint_clears_partial_abort_bytes() { + fn snapshot_clears_partial_abort_bytes() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) .build() .unwrap(); @@ -2259,45 +2224,6 @@ mod tests { assert_eq!(sandbox.status(), SandboxStatus::Ready); } - #[test] - fn restricted_dispatch_rejects_host_calls() { - let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) - .build() - .unwrap(); - - let call = FunctionCall::new( - "PrintOutput".into(), - Some(vec![ParameterValue::String("checkpoint".into())]), - FunctionCallType::Guest, - i32::TYPE, - ); - sandbox.mem_mgr.write_guest_function_call(&call).unwrap(); - - let error = sandbox.dispatch_guest_call_restricted().unwrap_err(); - - assert!( - error.to_string().contains("during a snapshot checkpoint"), - "{error}" - ); - assert_eq!(sandbox.status(), SandboxStatus::Poisoned); - assert_eq!(sandbox.mem_mgr.execution_mode, ExecutionMode::Unrestricted); - } - - #[test] - fn restore_resets_execution_mode() { - let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) - .build() - .unwrap(); - - let snapshot = sandbox.snapshot().unwrap(); - sandbox.mem_mgr.execution_mode = ExecutionMode::Restricted; - sandbox.restore(snapshot).unwrap(); - - sandbox - .call::("PrintOutput", "restored".to_string()) - .unwrap(); - } - #[test] fn guest_execution_preserves_pre_entry_cancellation() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) @@ -2308,13 +2234,15 @@ mod tests { let error = sandbox .with_guest_execution(|sandbox| { - sandbox.mem_mgr.begin_snapshot_checkpoint()?; + let call = + FunctionCall::new("GetStatic".into(), None, FunctionCallType::Guest, i32::TYPE); + sandbox.mem_mgr.write_guest_function_call(&call)?; assert!(!sandbox.interrupt_handle().kill()); sandbox.dispatch_guest_call() }) .unwrap_err(); - assert!(matches!(error, HyperlightError::ExecutionCanceledByHost())); + assert_matches!(error, HyperlightError::ExecutionCanceledByHost()); assert_eq!(sandbox.status(), SandboxStatus::Poisoned); assert!(sandbox.mem_mgr.abort_buffer.is_empty()); } @@ -2340,7 +2268,6 @@ mod tests { let snapshot = sandbox.snapshot().unwrap(); assert!(!sandbox.status().is_poisoned()); - assert!(!sandbox.transport_dirty); assert!(sandbox.mem_mgr.abort_buffer.is_empty()); assert_eq!(sandbox.call::(release, ()).unwrap(), retained_len); @@ -2348,12 +2275,11 @@ mod tests { sandbox.restore(snapshot).unwrap(); assert_eq!(sandbox.call::(release, ()).unwrap(), retained_len); sandbox.snapshot().unwrap(); - assert!(!sandbox.transport_dirty); } } #[test] - fn retained_restore_is_ready_for_first_request() { + fn retained_capture_is_ready_for_first_request() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) .build() .unwrap(); @@ -2363,35 +2289,69 @@ mod tests { vec![Bytes::from(vec![0x5a; 6 * 1024])], ) .unwrap(); - sandbox.checkpoint_transport_for_snapshot().unwrap(); let source_root = sandbox.vm.get_root_pt().unwrap(); - let snapshot = sandbox.snapshot().unwrap(); + sandbox.snapshot().unwrap(); assert_eq!(sandbox.vm.get_root_pt().unwrap(), source_root); - sandbox.restore(snapshot.clone()).unwrap(); + let expected = vec![0x3c; 24 * 1024]; + let actual: Vec = sandbox.call("EchoGuestVecBytes", expected.clone()).unwrap(); + assert_eq!(actual, expected); + + let retained: Vec = sandbox.call("ReadRetainedGuestByteChunks", ()).unwrap(); + assert_eq!(retained.concat(), vec![0x5a; 6 * 1024]); + assert_eq!( + sandbox.call::("ReleaseGuestByteChunks", ()).unwrap(), + 6 * 1024 + ); + } + + #[test] + fn retained_restore_is_ready_for_first_request() { + let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) + .build() + .unwrap(); + sandbox + .call::( + "RetainGuestByteChunks", + vec![Bytes::from(vec![0x5a; 6 * 1024])], + ) + .unwrap(); + let snapshot = sandbox.snapshot().unwrap(); + sandbox.restore(snapshot).unwrap(); + + let expected = vec![0x3c; 24 * 1024]; + let actual: Vec = sandbox.call("EchoGuestVecBytes", expected.clone()).unwrap(); + assert_eq!(actual, expected); + + let retained: Vec = sandbox.call("ReadRetainedGuestByteChunks", ()).unwrap(); + assert_eq!(retained.concat(), vec![0x5a; 6 * 1024]); + assert_eq!( + sandbox.call::("ReleaseGuestByteChunks", ()).unwrap(), + 6 * 1024 + ); + } + + #[test] + fn retained_clone_is_ready_for_first_request() { + let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) + .build() + .unwrap(); + sandbox + .call::( + "RetainGuestByteChunks", + vec![Bytes::from(vec![0x5a; 6 * 1024])], + ) + .unwrap(); + let snapshot = sandbox.snapshot().unwrap(); let mut clone = Sandbox::from_snapshot(snapshot, crate::HostFunctions::default(), None).unwrap(); - let expected = vec![0x3c; 3 * hyperlight_common::vmem::PAGE_SIZE + 117]; - let call = FunctionCall::new( - "EchoGuestVecBytes".into(), - Some(vec![ParameterValue::VecBytes(expected.clone())]), - FunctionCallType::Guest, - Vec::::TYPE, - ); - for restored in [&mut sandbox, &mut clone] { - restored.transport_dirty = true; - let cid = restored.mem_mgr.write_guest_function_call(&call).unwrap(); - restored.dispatch_guest_call().unwrap(); - let value = restored - .mem_mgr - .read_h2g_result_from_g2h(cid) - .unwrap() - .into_inner() - .unwrap(); - assert_eq!(Vec::::from_value(value).unwrap(), expected); - } + let expected = vec![0x3c; 24 * 1024]; + let actual: Vec = clone.call("EchoGuestVecBytes", expected.clone()).unwrap(); + assert_eq!(actual, expected); + let retained: Vec = clone.call("ReadRetainedGuestByteChunks", ()).unwrap(); + assert_eq!(retained.concat(), vec![0x5a; 6 * 1024]); assert_eq!( clone.call::("ReleaseGuestByteChunks", ()).unwrap(), 6 * 1024 @@ -3303,7 +3263,6 @@ mod tests { .evolve() .unwrap(); sandbox.call::("AddToStatic", 42i32).unwrap(); - sandbox.checkpoint_transport_for_snapshot().unwrap(); let mut options = SnapshotOptions::default(); if resize { options = scratch(sandbox.mem_mgr.layout.get_scratch_size() * 2); @@ -6310,13 +6269,10 @@ mod tests { } #[test] - fn rejects_noncanonical_transport_snapshot() { + fn cloning_uses_generated_bootstrap_images() { let mut sbox = make_sandbox(); sbox.call::("AddToStatic", 1i32).unwrap(); - // Checkpointing repairs the rings, so inject corruption afterward. - sbox.checkpoint_transport_for_snapshot().unwrap(); - let layout = &sbox.mem_mgr.layout; let scratch_base = layout::scratch_base_gpa(layout.get_scratch_size()); @@ -6328,11 +6284,9 @@ mod tests { .write::(ring_offset, 1) .unwrap(); - let Err(err) = sbox.snapshot() else { - panic!("noncanonical transport must fail snapshot creation"); - }; - - assert!(err.to_string().contains("invalid canonical G2H image")); + let snapshot = sbox.snapshot().unwrap(); + let mut clone = SandboxBuilder::from_snapshot(snapshot).build().unwrap(); + assert_eq!(clone.call::("GetStatic", ()).unwrap(), 1); } #[test] diff --git a/src/hyperlight_host/src/sandbox/outb.rs b/src/hyperlight_host/src/sandbox/outb.rs index 5e370b179..1a839fc80 100644 --- a/src/hyperlight_host/src/sandbox/outb.rs +++ b/src/hyperlight_host/src/sandbox/outb.rs @@ -16,7 +16,7 @@ use tracing::{Span, instrument}; use super::host_funcs::FunctionRegistry; #[cfg(feature = "mem_profile")] use crate::hypervisor::regs::CommonRegisters; -use crate::mem::mgr::{ExecutionMode, SandboxMemoryManager}; +use crate::mem::mgr::SandboxMemoryManager; use crate::mem::shared_mem::HostSharedMemory; use crate::mem::virtq; #[cfg(feature = "mem_profile")] @@ -36,8 +36,6 @@ pub enum HandleOutbError { InvalidPort(String), #[error("Failed to read host function call: {0}")] ReadHostFunctionCall(String), - #[error("Guest called a host function during a snapshot checkpoint")] - HostCallDuringCheckpoint, #[error("Failed to acquire lock at {0}:{1} - {2}")] LockFailed(&'static str, u32, String), #[error("Failed to write host function response: {0}")] @@ -214,7 +212,6 @@ fn outb_virtq_call( host_funcs: &Arc>, ) -> Result<(), HandleOutbError> { let max_recv_len = mem_mgr.layout.get_g2h_queue_dims().pool_len(); - let mode = mem_mgr.execution_mode; let Some(consumer) = mem_mgr.g2h_consumer.as_mut() else { return Err(HandleOutbError::ReadHostFunctionCall( @@ -236,10 +233,6 @@ fn outb_virtq_call( let mut message = virtq::RecvMessage::new(request) .map_err(|error| HandleOutbError::ReadHostFunctionCall(error.to_string()))?; - if mode == ExecutionMode::Restricted && message.kind() == MsgKind::Request { - return Err(HandleOutbError::HostCallDuringCheckpoint); - } - match message.kind() { MsgKind::Request => break (message, reply), MsgKind::Log => { diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs b/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs index a87eb1999..126cb0c17 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs @@ -27,7 +27,7 @@ pub(in crate::sandbox::snapshot) const MT_TRANSPORT_CURRENT: &str = MT_TRANSPORT /// ABI version for the snapshot memory blob. Bumped when the /// host-guest contract for the snapshot bytes changes. See /// docs/snapshot-versioning.md. -pub(in crate::sandbox::snapshot) const SNAPSHOT_ABI_VERSION: u32 = 11; +pub(in crate::sandbox::snapshot) const SNAPSHOT_ABI_VERSION: u32 = 12; /// OCI standard annotation key for a manifest's tag inside an image /// index. Set on the manifest descriptor in `index.json`, not on the diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/transport.rs b/src/hyperlight_host/src/sandbox/snapshot/file/transport.rs index 109f92834..1f202c9ee 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/transport.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/transport.rs @@ -141,11 +141,10 @@ mod tests { use super::*; use crate::mem::virtq::tests::{TestCase, memory_layout}; - /// Capture canonical rings for transport framing tests. + /// Build bootstrap images for transport framing tests. fn transport_snapshot() -> (SandboxMemoryLayout, VirtqSnapshot) { - let case = TestCase::new(); let layout = memory_layout(); - let snapshot = VirtqSnapshot::capture(&layout, &case.scratch).unwrap(); + let snapshot = VirtqSnapshot::bootstrap(&layout).unwrap(); (layout, snapshot) } @@ -328,7 +327,7 @@ mod tests { fn transport_blob_rejects_h2g_buffer_addresses() { let case = TestCase::new(); let layout = memory_layout(); - let snapshot = VirtqSnapshot::capture(&layout, &case.scratch).unwrap(); + let snapshot = VirtqSnapshot::bootstrap(&layout).unwrap(); let mut bytes = encode(&layout, &snapshot).unwrap(); let addr_offset = HEADER_LEN + snapshot.g2h_ring().len() + Descriptor::ADDR_OFFSET; @@ -341,7 +340,7 @@ mod tests { let msg = err.to_string(); assert!(msg.contains("invalid canonical H2G image"), "{msg}"); - assert!(err.to_string().contains("buffer"), "{err}"); + assert!(msg.contains("does not match bootstrap"), "{err}"); let duplicate_addr = case.h2g_desc(1).addr; bytes[addr_offset..addr_offset + size_of::()] @@ -351,6 +350,6 @@ mod tests { let msg = err.to_string(); assert!(msg.contains("invalid canonical H2G image"), "{msg}"); - assert!(msg.contains("buffer"), "{err}"); + assert!(msg.contains("does not match bootstrap"), "{err}"); } } diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 970bbf3b5..e9ead7f0a 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -74,6 +74,42 @@ fn retained_initial_data_survives_snapshots() { assert_eq!(actual.concat(), expected); } +#[test] +fn retained_h2g_bootstrap_survives_oci_round_trip() { + use hyperlight_common::flatbuffer_wrappers::function_types::Bytes; + + let mut sandbox = create_test_sandbox(); + sandbox + .call::( + "RetainGuestByteChunks", + vec![Bytes::from(vec![0x5a; 6 * 1024])], + ) + .unwrap(); + + let snapshot = sandbox.snapshot().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tag = OciTag::new("latest").unwrap(); + + snapshot.save(dir.path(), &tag).unwrap(); + drop(sandbox); + drop(snapshot); + + let loaded = Arc::new(Snapshot::checked_load(dir.path(), tag).unwrap()); + let mut restored = SandboxBuilder::from_snapshot(loaded).build().unwrap(); + + let length: i32 = restored + .call("ByteChunksLen", vec![Bytes::from(vec![0x3c; 24 * 1024])]) + .unwrap(); + + assert_eq!(length, 24 * 1024); + + let retained: Vec = restored.call("ReadRetainedGuestByteChunks", ()).unwrap(); + assert_eq!(retained.concat(), vec![0x5a; 6 * 1024]); + + let res = restored.call::("ReleaseGuestByteChunks", ()).unwrap(); + assert_eq!(res, 6 * 1024); +} + fn random_sequence(sandbox: &mut Sandbox) -> [i32; 4] { std::array::from_fn(|_| sandbox.call("NextRandom", ()).unwrap()) } @@ -336,7 +372,7 @@ fn layered_writer_preserves_blobs_and_transport_geometry() { manifest["artifactType"], "application/vnd.hyperlight.snapshot.config.v6+json" ); - assert_eq!(config["abi_version"], 11); + assert_eq!(config["abi_version"], 12); let blobs = snapshot.snapshot_memory().blobs().collect::>(); assert_eq!(layers.len(), blobs.len() + 1); for (index, blob) in blobs.iter().enumerate() { @@ -2520,7 +2556,7 @@ fn legacy_config_versions_rejected() { &path, OciTag::new("latest").unwrap(), )); - assert_err_contains(err, "incompatible with snapshot ABI 11"); + assert_err_contains(err, "incompatible with snapshot ABI 12"); } } diff --git a/src/hyperlight_host/src/sandbox/snapshot/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/mod.rs index bb24e0800..8e3bde7bb 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/mod.rs @@ -83,10 +83,9 @@ impl SnapshotOptions { /// /// A size larger than the maximum memory size (`MemoryRequestTooBig`), /// too small for the transport (`MemoryRequestTooSmall`), or not a - /// whole number of host pages is rejected before the guest is entered. + /// whole number of host pages is rejected before memory capture. /// Room for the page tables depends on the guest's mappings and is - /// checked when the snapshot is built, after a pending transport - /// checkpoint has run in the guest: a size without it fails then, with + /// checked when the snapshot is built. A size without that room fails with /// `MemoryRequestTooSmall`. A larger size whose scratch window would /// cover a guest mapping below the current one fails then too. Both /// failures leave the sandbox usable. Whether guest function calls fit diff --git a/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs b/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs index f7a56dc7a..7f0f5bbbc 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs @@ -18,7 +18,7 @@ use super::file::{ SNAPSHOT_ABI_VERSION, }; -const EXPECTED_ABI_VERSION: u32 = 11; +const EXPECTED_ABI_VERSION: u32 = 12; const EXPECTED_MT_CONFIG: &str = "application/vnd.hyperlight.snapshot.config.v6+json"; const EXPECTED_MT_SNAPSHOT: &str = "application/vnd.hyperlight.snapshot.memory.v2"; const EXPECTED_MT_TRANSPORT: &str = "application/vnd.hyperlight.snapshot.transport.v1"; diff --git a/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs b/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs index 19102f3c1..38f28c3de 100644 --- a/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs +++ b/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs @@ -74,7 +74,7 @@ pub(super) fn initialize_sandbox(u_sbox: UninitializedSandbox) -> Result| value) @@ -992,10 +992,10 @@ fn retained_byte_chunks_survive_pool_swap() { sandbox.restore(snapshot).unwrap(); let actual: i32 = sandbox - .call("ByteChunksLen", vec![Bytes::from(vec![0x5a; 12288])]) + .call("ByteChunksLen", vec![Bytes::from(vec![0x5a; 24 * 1024])]) .unwrap(); - assert_eq!(actual, 12288); + assert_eq!(actual, 24 * 1024); let actual: Vec = sandbox.call("ReadRetainedGuestByteChunks", ()).unwrap(); assert_eq!(actual.concat(), expected); @@ -1003,15 +1003,15 @@ fn retained_byte_chunks_survive_pool_swap() { let actual: Vec = sandbox.call("ReadRetainedHostByteChunks", ()).unwrap(); assert_eq!(actual.concat(), expected); - // Capture recovered pools while their older retained aliases remain live. + // Retained aliases outlive several transport generations. let snapshot = sandbox.snapshot().unwrap(); sandbox.restore(snapshot).unwrap(); let actual: i32 = sandbox - .call("ByteChunksLen", vec![Bytes::from(vec![0x5a; 12288])]) + .call("ByteChunksLen", vec![Bytes::from(vec![0x5a; 24 * 1024])]) .unwrap(); - assert_eq!(actual, 12288); + assert_eq!(actual, 24 * 1024); let actual: Vec = sandbox.call("ReadRetainedGuestByteChunks", ()).unwrap(); assert_eq!(actual.concat(), expected); diff --git a/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs b/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs index c1b3f149b..4fc6ca7f6 100644 --- a/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs +++ b/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs @@ -8,7 +8,7 @@ //! publish. See `docs/snapshot-versioning.md`. /// Goldens version, a `vMAJOR.MINOR` string. -pub(crate) const GOLDENS_VERSION: &str = "v11.0"; +pub(crate) const GOLDENS_VERSION: &str = "v12.0"; /// Old majors kept loadable through a compatibility path, verified /// alongside `GOLDENS_VERSION`. A backwards-compatible break (Option 2) diff --git a/src/tests/rust_guests/simpleguest/src/bin/simpleguest-incomplete-init.rs b/src/tests/rust_guests/simpleguest/src/bin/simpleguest-incomplete-init.rs new file mode 100644 index 000000000..e134441ed --- /dev/null +++ b/src/tests/rust_guests/simpleguest/src/bin/simpleguest-incomplete-init.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +#![no_std] +#![no_main] + +use hyperlight_common::outb::VmAction; +use hyperlight_guest_bin::main; + +/// Halt before the runtime publishes initialization readiness. +#[main] +fn main() { + #[cfg(target_arch = "x86_64")] + // SAFETY: The host handles this port as a VM halt. + unsafe { + core::arch::asm!( + "out dx, eax", + in("dx") VmAction::Halt as u16, + in("eax") 0u32, + options(nostack, preserves_flags), + ); + } + + #[cfg(target_arch = "aarch64")] + // SAFETY: The runtime maps the I/O page before user initialization. + unsafe { + let page = hyperlight_common::layout::io_page().unwrap().1 as *mut u64; + page.add(VmAction::Halt as usize).write_volatile(0); + } + + panic!("initialization resumed after early halt"); +}