diff --git a/CHANGELOG.md b/CHANGELOG.md index 532064b59..db39c0c4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). * Guest and host functions return tuples of 2 to 32 values, such as a stream with a future of its outcome. An element is any built-in return type except `()` and tuples. A result moves at most `MAX_TRANSFERS` readers. * Add virtqueue `ChainBuilder::keep_free(n)`. `build` leaves `n` ring descriptors and pool slots free for later single-slot chains, or reports `Backpressure`. * Add virtqueue `SlotPool::max_free_slot_size()`, the size of the largest free slot. +* Add virtqueue `SlotPool::add_slots(base_addr, count)`, an unsafe method that grows the upper tier with slots outside the pool's layout. ### Changed * `hyperlight-host` requires Rust 1.95. @@ -45,6 +46,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). * `Sandbox::snapshot` and `snapshot_with_options` fail with `HyperlightError::StreamsActive` while cross-boundary streams or guest tasks are live, and leave the sandbox unchanged. Guest initialization that leaves either live fails sandbox creation. * A guest function call fails with `HyperlightError::GuestError` and leaves the sandbox usable when its result exceeds the G2H virtqueue capacity, or when its returned stream reader cannot move to the host. * Restoring, recreating, or dropping a sandbox fails host readers of guest streams with `StreamError::Aborted` after their buffered bytes, unless the stream already ended. +* Guest code that retains H2G buffers, such as `ByteChunks` arguments, leaves the host's H2G capacity intact. The guest posts a free slot in place of each retained buffer, adds slots on scratch pages when none are free, and aborts when scratch runs out. +* Guest stream reads use H2G slots directly for DATA records larger than 128 bytes. ### Fixed * Fix surrogate process creation for Windows paths containing Unicode or spaces. diff --git a/docs/how-to-build-a-hyperlight-guest-binary.md b/docs/how-to-build-a-hyperlight-guest-binary.md index f8fe7a4d0..f937290ae 100644 --- a/docs/how-to-build-a-hyperlight-guest-binary.md +++ b/docs/how-to-build-a-hyperlight-guest-binary.md @@ -167,9 +167,11 @@ return value or the guest function's parameter decides: * `Vec` copies the data into guest memory and releases the transport buffers at once. -Retained buffers keep their pool slots, which reduces the capacity left for -later calls. Size the pool listed above for the retained data plus normal -traffic. See +Retained buffers keep their pool slots. Retained host function replies reduce +the G2H capacity left for later calls. Size `g2h_pool_pages` for the retained +data plus normal traffic. Retained guest function arguments hold H2G slots. The +guest posts free slots in their place, and adds slots on scratch pages when none +are free. Leave room for them in `SandboxBuilder::scratch_size`. See [Capacity and latency](./virtio-host-guest-communication.md#capacity-and-latency). ### Troubleshooting diff --git a/docs/virtio-host-guest-communication.md b/docs/virtio-host-guest-communication.md index a2d2a69f0..0c03c3fa8 100644 --- a/docs/virtio-host-guest-communication.md +++ b/docs/virtio-host-guest-communication.md @@ -77,7 +77,9 @@ when constructing rings and pools. Descriptor buffer addresses are GVAs. ### Buffer pools * **H2G** provides equal-sized buffers for host requests. The guest makes - them available before it knows the next message size. + them available before it knows the next message size. Retained buffers + grow the pool below the arena, as [Extra H2G slots](#extra-h2g-slots) + describes. * **G2H** allocates buffers for guest requests, results, and logs. Small control messages can use 256-byte buffers, leaving larger buffers free for data. @@ -157,6 +159,13 @@ reclaimed. The second row adds that work without carrying more data. Larger buffers reduce chunking, but each small message occupies more space. Measure the mix of message sizes your application actually uses. +Retained buffers keep their whole slots, whatever the size of their values. +Retained G2H replies hold G2H slots, so size `g2h_pool_pages` for them plus +normal traffic. Retained H2G buffers hold H2G slots. The guest posts free slots +in their place, adds slots on scratch pages when none are free, and aborts when +scratch runs out. Leave room in `scratch_size` for the most H2G buffers +retained at once. See [Extra H2G slots](#extra-h2g-slots). + ### Initialization The host writes the normalized queue sizes, pool page counts, buffer sizes, @@ -398,7 +407,8 @@ Guest `SlotPool` instances own all transport buffers. Pool clones share one allocation bitmap with each producer. Each producer pairs its backend with that pool. Completion leases carry the original slot addresses and full capacities. Backing owns alias allocation and -paging. The backend holds only the transport arena's bounds. +paging. Each backend holds only memory bounds. They cover the transport arena, +and for H2G the extra slots below it. Guest completion mapping checks those bounds. Allocation ownership and initialized lengths follow the `BufferMap` safety contract. @@ -406,17 +416,37 @@ initialized lengths follow the `BufferMap` safety contract. Free -> allocated -> published -> completed -> owner-backed Bytes -> Free ``` -Some stages are skipped by one-way messages. Final ownership matters for -external `ByteChunks`: +Some stages are skipped by one-way messages. * H2G `ByteChunks` can retain host written receive slots after a guest function - returns. + returns. The guest posts other slots in their place. +* The guest copies stream DATA records of up to 128 bytes. Larger records keep + their H2G slots until the last chunk drops, even after the reader returns credit. * G2H host responses can become owner-backed guest `Bytes`. * `VecBytes` values copy into a contiguous `Vec`. * Multiple `Bytes` clones or slices backed by one owner keep one slot live. * The final owner unmaps its alias and returns the virtual range for reuse. Its lease releases the slot in its original pool. +### Extra H2G slots + +Each guest entry ends with as many H2G buffers posted as at bootstrap. +Retained buffers keep their slots. When too few slots are free, the guest takes +pages from the scratch allocator and adds slots on them. The host keeps full +H2G capacity whatever the guest retains. + +Freed extra slots return to the pool. Their pages stay allocated until capture +or restore resets the scratch allocator, so scratch growth follows the most +buffers retained at once. A guest that runs out of scratch aborts with +`MallocFailed`, which poisons the sandbox. + +The scratch allocator hands out pages upward from its next free page and stops +at the arena. Extra slots therefore lie between the next free page at +generation start and the arena. The H2G backend's bounds start at that page. +Each generation rebuilds the pool from its layout, without extra slots, and +reads the next free page again. Retained aliases keep captured backing, so new +extra slots cannot overlap them. + ### Retained virtual addresses Both pools share one guest-global alias allocator. Its state is captured with @@ -532,9 +562,9 @@ 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. Retention within a generation still -occupies pool slots. Full bootstrap capacity requires no preparatory guest entry -or application warmup after capture or restore. +Full bootstrap capacity requires no preparatory guest entry or application +warmup after capture or restore. Each guest entry ends with that capacity +posted again, as [Extra H2G slots](#extra-h2g-slots) describes. ## Transport mailbox diff --git a/src/hyperlight_common/Cargo.toml b/src/hyperlight_common/Cargo.toml index 9b7261cb0..fed32b950 100644 --- a/src/hyperlight_common/Cargo.toml +++ b/src/hyperlight_common/Cargo.toml @@ -56,6 +56,10 @@ doctest = false # reduce noise in test output name = "buffer_pool" harness = false +[[bench]] +name = "stream_pipe" +harness = false + [[bench]] name = "virtq_api" harness = false diff --git a/src/hyperlight_common/benches/stream_pipe.rs b/src/hyperlight_common/benches/stream_pipe.rs new file mode 100644 index 000000000..f456f7d56 --- /dev/null +++ b/src/hyperlight_common/benches/stream_pipe.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +use std::hint::black_box; +use std::pin::pin; +use std::task::{Context, Poll, Waker}; + +use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use hyperlight_common::stream::{self, DEFAULT_WINDOW}; + +/// Each iteration starts with an empty pipe and writes at most one window. +fn ready(future: F) -> F::Output { + let Poll::Ready(output) = pin!(future).poll(&mut Context::from_waker(Waker::noop())) else { + panic!("local pipe operation blocked"); + }; + + output +} + +/// Compare copying and transferring an owned buffer. Input allocation is outside the timer. +fn bench_owned_writes(c: &mut Criterion) { + let mut group = c.benchmark_group("stream_pipe_write"); + + for size in [128, 4096, DEFAULT_WINDOW.get() as usize] { + let payload = vec![0x5a; size]; + group.throughput(Throughput::Bytes(size as u64)); + + group.bench_function(BenchmarkId::new("write_all", size), |b| { + let (mut reader, mut writer) = stream::new::(); + + b.iter_batched( + || payload.clone(), + |data| { + ready(writer.write_all(&data)).unwrap(); + black_box(ready(reader.read_chunk()).unwrap().unwrap()); + }, + BatchSize::LargeInput, + ); + }); + + group.bench_function(BenchmarkId::new("write_chunk", size), |b| { + let (mut reader, mut writer) = stream::new::(); + + b.iter_batched( + || payload.clone(), + |data| { + ready(writer.write_chunk(data.into())).unwrap(); + black_box(ready(reader.read_chunk()).unwrap().unwrap()); + }, + BatchSize::LargeInput, + ); + }); + } + + group.finish(); +} + +criterion_group!(benches, bench_owned_writes); +criterion_main!(benches); diff --git a/src/hyperlight_common/src/future/producer.rs b/src/hyperlight_common/src/future/producer.rs index 8b7f1d5b7..ef89e084b 100644 --- a/src/hyperlight_common/src/future/producer.rs +++ b/src/hyperlight_common/src/future/producer.rs @@ -84,7 +84,7 @@ mod tests { let (mut output, mut writer) = stream::new(); let (reader, task) = producer(async move { - writer.write_all(&data).await?; + writer.write_chunk(data.into()).await?; writer.close(); Ok::<_, StreamError>(()) }); diff --git a/src/hyperlight_common/src/stream/mod.rs b/src/hyperlight_common/src/stream/mod.rs index 96d9ae0ff..e33c10dc5 100644 --- a/src/hyperlight_common/src/stream/mod.rs +++ b/src/hyperlight_common/src/stream/mod.rs @@ -40,6 +40,8 @@ pub const MAX_TRANSFERS: usize = 16; pub const DEFAULT_WINDOW: NonZeroU32 = NonZeroU32::new(16384).unwrap(); /// Bytes copied by one copy write. pub const MAX_COPY_WRITE: usize = 65536; +/// Largest DATA record the guest copies out of an H2G slot. +pub const GOOD_COPY_LEN: usize = 128; /// Transfer metadata prepared for one message. pub(crate) type Transfers = SmallVec<[Transfer; 4]>; diff --git a/src/hyperlight_common/src/virtq/pool/slot.rs b/src/hyperlight_common/src/virtq/pool/slot.rs index 917a9daad..a764f19da 100644 --- a/src/hyperlight_common/src/virtq/pool/slot.rs +++ b/src/hyperlight_common/src/virtq/pool/slot.rs @@ -8,6 +8,9 @@ //! allocation bitmap. Eligible requests try the lower tier first and fall back //! to the upper tier only when the lower tier has no free slot. //! +//! [`SlotPool::add_slots`] grows the upper tier with slots outside the layout. +//! Requests take them once the layout's upper slots are allocated. +//! //! Each allocation occupies one slot. [`SlotPool::live_addrs`] reports ownership //! in deterministic index order. @@ -286,9 +289,106 @@ impl Tier { } } +/// Upper-size slots outside the pool's layout. +/// +/// Slots stay sorted by address, so binary search finds them and rejects double +/// frees and unknown addresses. +#[derive(Default)] +struct ExtraSlots { + /// Slot start addresses in ascending order, each with whether it is allocated. + slots: Vec<(u64, bool)>, + /// Free slot addresses, popped/pushed LIFO. + free: Vec, +} + +impl ExtraSlots { + /// Whether an extra slot of `slot_size` bytes overlaps `start..end`. + fn overlaps(&self, start: u64, end: u64, slot_size: u64) -> bool { + // Extra slots are disjoint and equal-sized, so only the last one that + // starts before `end` can reach into the range. + let before_end = self.slots.partition_point(|&(addr, _)| addr < end); + + self.slots[..before_end] + .last() + .is_some_and(|&(addr, _)| addr + slot_size > start) + } + + /// Add the free slots of `layout`, which overlaps no existing slot. + /// + /// Both lists reserve room first, so an error leaves them unchanged. The free + /// list keeps room for every slot, so frees never reallocate. + fn add(&mut self, layout: SlotLayout) -> Result<(), AllocError> { + let count = layout.slot_count(); + + self.slots + .try_reserve(count) + .map_err(|_| AllocError::Bookkeeping)?; + + // The reservation succeeded, so this sum cannot overflow. + let total = self.slots.len() + count; + + self.free + .try_reserve(total - self.free.len()) + .map_err(|_| AllocError::Bookkeeping)?; + + for addr in (0..count).filter_map(|index| layout.slot_addr(index)) { + self.slots.push((addr, false)); + self.free.push(addr); + } + + self.slots.sort_unstable_by_key(|&(addr, _)| addr); + Ok(()) + } + + /// Index of the extra slot starting at `addr`. + fn find(&self, addr: u64) -> Option { + self.slots + .binary_search_by_key(&addr, |&(slot, _)| slot) + .ok() + } + + fn alloc(&mut self, slot_size: u32) -> Result { + let addr = self.free.pop().ok_or(AllocError::NoSpace)?; + + // Free addresses always name extra slots, so this marks one allocated. + if let Some(index) = self.find(addr) { + self.slots[index].1 = true; + } + + Ok(Allocation { + addr, + len: slot_size, + }) + } + + fn dealloc_addr(&mut self, addr: u64) -> Result<(), AllocError> { + let index = self + .find(addr) + .filter(|&index| self.slots[index].1) + .ok_or(AllocError::InvalidFree(addr, 0))?; + + self.slots[index].1 = false; + self.free.push(addr); + Ok(()) + } + + fn is_live(&self, addr: u64) -> bool { + self.find(addr).is_some_and(|index| self.slots[index].1) + } + + fn append_live_addrs(&self, addrs: &mut Vec) { + addrs.extend( + self.slots + .iter() + .filter_map(|&(addr, live)| live.then_some(addr)), + ); + } +} + struct Inner { lower: Option, upper: Tier, + extra: ExtraSlots, } impl Inner { @@ -296,6 +396,7 @@ impl Inner { Ok(Self { lower: layout.lower.map(Tier::from_layout).transpose()?, upper: Tier::from_layout(layout.upper)?, + extra: ExtraSlots::default(), }) } @@ -314,7 +415,29 @@ impl Inner { } } - self.upper.alloc(len) + match self.upper.alloc(len) { + Err(AllocError::NoSpace) => self.extra.alloc(self.upper.slot_size), + res => res, + } + } + + /// Grow the upper tier by `count` slots at `base_addr`, outside every slot. + fn add_slots(&mut self, base_addr: u64, count: usize) -> Result<(), AllocError> { + let slot_size = self.upper.slot_size; + let layout = SlotLayout::new(base_addr, slot_size as usize, count)?; + let (start, end) = (layout.base_addr(), layout.end_addr()); + + let in_tier = self + .lower + .iter() + .chain(core::iter::once(&self.upper)) + .any(|tier| start < tier.end() && tier.base_addr < end); + + if in_tier || self.extra.overlaps(start, end, u64::from(slot_size)) { + return Err(AllocError::InvalidArg); + } + + self.extra.add(layout) } fn dealloc_addr(&mut self, addr: u64) -> Result<(), AllocError> { @@ -323,7 +446,12 @@ impl Inner { { return lower.dealloc_addr(addr); } - self.upper.dealloc_addr(addr) + + if self.upper.contains(addr) { + return self.upper.dealloc_addr(addr); + } + + self.extra.dealloc_addr(addr) } fn allocation_len(&self, addr: u64) -> Result { @@ -332,17 +460,33 @@ impl Inner { { return lower.allocation_len(addr); } - self.upper.allocation_len(addr) + + if self.upper.contains(addr) { + return self.upper.allocation_len(addr); + } + + if !self.extra.is_live(addr) { + return Err(AllocError::InvalidFree(addr, 0)); + } + + Ok(self.upper.slot_size as usize) } - fn slot_addr(&self, index: usize) -> Option { + fn slot_addr(&self, mut index: usize) -> Option { if let Some(lower) = &self.lower { if index < lower.count { return lower.slot_addr(index); } - return self.upper.slot_addr(index - lower.count); + + index -= lower.count; + } + + if index < self.upper.count { + return self.upper.slot_addr(index); } - self.upper.slot_addr(index) + + let extra = index - self.upper.count; + self.extra.slots.get(extra).map(|&(addr, _)| addr) } fn live_addrs(&self) -> Vec { @@ -351,6 +495,7 @@ impl Inner { lower.append_live_addrs(&mut addrs); } self.upper.append_live_addrs(&mut addrs); + self.extra.append_live_addrs(&mut addrs); addrs } @@ -361,11 +506,16 @@ impl Inner { } fn count(&self) -> usize { - self.lower.as_ref().map_or(0, |lower| lower.count) + self.upper.count + let lower = self.lower.as_ref().map_or(0, |lower| lower.count); + lower + self.upper.count + self.extra.slots.len() } fn num_free(&self) -> usize { - self.lower.as_ref().map_or(0, Tier::num_free) + self.upper.num_free() + self.lower.as_ref().map_or(0, Tier::num_free) + self.num_free_upper() + } + + fn num_free_upper(&self) -> usize { + self.upper.num_free() + self.extra.free.len() } fn num_live(&self) -> usize { @@ -379,7 +529,7 @@ impl Inner { } } - /// Byte span of both tiers, including any gap. + /// Byte span of the layout's tiers, including any gap. fn byte_len(&self) -> usize { (self.upper.layout().end_addr() - self.base_addr()) as usize } @@ -387,9 +537,9 @@ impl Inner { /// A buffer pool with one or two fixed-slot tiers. /// -/// Allocation and deallocation are O(1) per slot. Eligible allocations first -/// try the optional lower tier and fall back to the required upper tier when -/// the lower tier is full. +/// Allocation and deallocation are O(1) per layout slot and O(log n) per extra +/// slot. Eligible allocations first try the optional lower tier and fall back to +/// the required upper tier when the lower tier is full. #[derive(Clone)] pub struct SlotPool { inner: Rc>, @@ -451,7 +601,7 @@ impl SlotPool { self.inner.borrow().live_addrs() } - /// Pool geometry independent of current allocations. + /// Pool geometry independent of current allocations and extra slots. pub fn layout(&self) -> PoolLayout { self.inner.borrow().layout() } @@ -462,9 +612,10 @@ impl SlotPool { (layout.lower, layout.upper) } - /// Compute the address of slot `index`, with lower-tier slots first. + /// Compute the address of slot `index`. /// - /// Returns `None` if `index >= count`. + /// Lower-tier slots come first, then upper-tier slots, then extra slots in + /// address order. Returns `None` if `index >= count`. pub fn slot_addr(&self, index: usize) -> Option { self.inner.borrow().slot_addr(index) } @@ -484,9 +635,25 @@ impl SlotPool { self.inner.borrow().lower.as_ref().map_or(0, Tier::num_free) } - /// Total number of free slots in the upper tier. + /// Total number of free slots in the upper tier, including extra slots. pub fn num_free_upper(&self) -> usize { - self.inner.borrow().upper.num_free() + self.inner.borrow().num_free_upper() + } + + /// Grow the upper tier with `count` slots of the upper slot size at `base_addr`. + /// + /// The slots must not overlap the layout or existing extra slots. Requests take + /// them once the layout's upper slots are allocated, and they stay until the + /// pool drops. Returns [`AllocError::InvalidArg`] for an overlap, + /// [`AllocError::Bookkeeping`] when the slot lists cannot grow, and the errors + /// of [`SlotLayout::new`] for an invalid range. + /// + /// # Safety + /// + /// The range must be valid memory for the pool's producer. Nothing else may use + /// it while that producer allocates from the pool. + pub unsafe fn add_slots(&self, base_addr: u64, count: usize) -> Result<(), AllocError> { + self.inner.borrow_mut().add_slots(base_addr, count) } /// Free a previously allocated slot by address. @@ -499,7 +666,7 @@ impl SlotPool { self.inner.borrow().allocation_len(addr) } - /// Base address of the first managed tier. + /// Base address of the layout's first tier. pub fn base_addr(&self) -> u64 { self.inner.borrow().base_addr() } @@ -527,7 +694,7 @@ impl SlotPool { pub fn max_free_slot_size(&self) -> Option { let inner = self.inner.borrow(); - if inner.upper.num_free() != 0 { + if inner.num_free_upper() != 0 { return Some(inner.upper.slot_size as usize); } @@ -548,7 +715,7 @@ impl SlotPool { self.inner.borrow_mut().alloc(len) } - /// Byte span from the first slot to the last, including any gap between tiers. + /// Byte span of the layout, including any gap between tiers. pub fn byte_len(&self) -> usize { self.inner.borrow().byte_len() } diff --git a/src/hyperlight_common/src/virtq/pool/tests.rs b/src/hyperlight_common/src/virtq/pool/tests.rs index 5e69907a5..8f79ac447 100644 --- a/src/hyperlight_common/src/virtq/pool/tests.rs +++ b/src/hyperlight_common/src/virtq/pool/tests.rs @@ -14,6 +14,12 @@ fn make_tiered_slot_pool(lower_count: usize, upper_count: usize) -> SlotPool { SlotPool::new_tiered(lower, upper).unwrap() } +/// Add slots to a pool without a producer. +fn add_slots(pool: &SlotPool, base_addr: u64, count: usize) -> Result<(), AllocError> { + // SAFETY: Without a producer, nothing accesses the slots' memory. + unsafe { pool.add_slots(base_addr, count) } +} + #[test] fn test_slot_pool_preserves_exact_base() { let layout = SlotLayout::new(0x80001, 4096, 2).unwrap(); @@ -415,3 +421,216 @@ fn test_slot_pool_dealloc_order_independent_of_alloc_order() { assert_eq!(realloc_addrs, orig_addrs); } + +#[test] +fn test_extra_slots_serve_requests_after_the_layout() { + let pool = make_slot_pool(1, 4096); + add_slots(&pool, 0x10000, 2).unwrap(); + + let layout_slot = pool.alloc(4096).unwrap(); + assert_eq!(layout_slot.addr, 0x80000); + + let first = pool.alloc(1).unwrap(); + let second = pool.alloc(4096).unwrap(); + assert_eq!(first.len, 4096); + assert_eq!(second.len, 4096); + + let mut extra = [first.addr, second.addr]; + extra.sort(); + assert_eq!(extra, [0x10000, 0x11000]); + assert!(matches!(pool.alloc(4096), Err(AllocError::NoSpace))); +} + +#[test] +fn test_extra_slots_do_not_mask_request_errors() { + let pool = make_slot_pool(1, 4096); + add_slots(&pool, 0x10000, 1).unwrap(); + + assert!(matches!(pool.alloc(0), Err(AllocError::InvalidArg))); + assert!(matches!(pool.alloc(4097), Err(AllocError::OutOfMemory))); + assert_eq!(pool.num_free(), 2); +} + +#[test] +fn test_extra_slots_are_reused_after_free() { + let pool = make_slot_pool(1, 4096); + add_slots(&pool, 0x10000, 1).unwrap(); + let _layout_slot = pool.alloc(4096).unwrap(); + + let extra = pool.alloc(4096).unwrap(); + assert_eq!(pool.allocation_len(extra.addr).unwrap(), 4096); + + pool.dealloc(extra.addr).unwrap(); + assert!(matches!( + pool.allocation_len(extra.addr), + Err(AllocError::InvalidFree(0x10000, 0)) + )); + assert_eq!(pool.alloc(4096).unwrap().addr, extra.addr); +} + +#[test] +fn test_extra_slots_reject_double_free() { + let pool = make_slot_pool(1, 4096); + add_slots(&pool, 0x10000, 1).unwrap(); + let _layout_slot = pool.alloc(4096).unwrap(); + + let extra = pool.alloc(4096).unwrap(); + pool.dealloc(extra.addr).unwrap(); + + assert!(matches!( + pool.dealloc(extra.addr), + Err(AllocError::InvalidFree(0x10000, 0)) + )); + assert_eq!(pool.num_free(), 1); +} + +#[test] +fn test_extra_slots_reject_unknown_addresses() { + let pool = make_slot_pool(1, 4096); + add_slots(&pool, 0x10000, 2).unwrap(); + let _layout_slot = pool.alloc(4096).unwrap(); + let _first = pool.alloc(4096).unwrap(); + let _second = pool.alloc(4096).unwrap(); + + assert!(matches!( + pool.dealloc(0x10001), + Err(AllocError::InvalidFree(0x10001, 0)) + )); + assert!(matches!( + pool.dealloc(0x12000), + Err(AllocError::InvalidFree(0x12000, 0)) + )); + assert!(matches!( + pool.allocation_len(0x10001), + Err(AllocError::InvalidFree(0x10001, 0)) + )); + assert_eq!(pool.num_live(), 3); +} + +#[test] +fn test_add_slots_rejects_tier_overlap() { + // The lower tier spans 0x80000..0x80200, and the upper 0x90000..0x92000. + let pool = make_tiered_slot_pool(2, 2); + + assert!(matches!( + add_slots(&pool, 0x7f001, 1), + Err(AllocError::InvalidArg) + )); + assert!(matches!( + add_slots(&pool, 0x91fff, 1), + Err(AllocError::InvalidArg) + )); + assert_eq!(pool.count(), 4); + + add_slots(&pool, 0x7f000, 1).unwrap(); + add_slots(&pool, 0x80200, 1).unwrap(); + add_slots(&pool, 0x92000, 1).unwrap(); + assert_eq!(pool.count(), 7); +} + +#[test] +fn test_add_slots_rejects_extra_overlap() { + let pool = make_slot_pool(1, 4096); + add_slots(&pool, 0x10000, 2).unwrap(); + + assert!(matches!( + add_slots(&pool, 0x11000, 1), + Err(AllocError::InvalidArg) + )); + assert!(matches!( + add_slots(&pool, 0xf001, 1), + Err(AllocError::InvalidArg) + )); + assert!(matches!( + add_slots(&pool, 0x11fff, 1), + Err(AllocError::InvalidArg) + )); + assert!(matches!( + add_slots(&pool, 0x8000, 16), + Err(AllocError::InvalidArg) + )); + assert_eq!(pool.count(), 3); + + add_slots(&pool, 0xf000, 1).unwrap(); + add_slots(&pool, 0x12000, 1).unwrap(); + assert_eq!(pool.count(), 5); +} + +#[test] +fn test_add_slots_rejects_zero_slots() { + let pool = make_slot_pool(1, 4096); + + assert!(matches!( + add_slots(&pool, 0x10000, 0), + Err(AllocError::EmptyRegion) + )); + assert_eq!(pool.count(), 1); +} + +#[test] +fn test_add_slots_rejects_overflowing_range() { + let pool = make_slot_pool(1, 4096); + + assert!(matches!( + add_slots(&pool, u64::MAX - 4095, 1), + Err(AllocError::Overflow) + )); + assert_eq!(pool.count(), 1); + + add_slots(&pool, u64::MAX - 4096, 1).unwrap(); + assert_eq!(pool.count(), 2); +} + +#[test] +fn test_extra_slots_leave_the_layout_unchanged() { + let pool = make_tiered_slot_pool(1, 1); + let layout = pool.layout(); + + add_slots(&pool, 0x10000, 2).unwrap(); + + assert_eq!(pool.layout(), layout); + assert_eq!(pool.base_addr(), 0x80000); + assert_eq!(pool.byte_len(), 0x11000); +} + +#[test] +fn test_extra_slots_extend_counts_and_indices() { + let pool = make_tiered_slot_pool(1, 1); + add_slots(&pool, 0x12000, 1).unwrap(); + add_slots(&pool, 0x10000, 1).unwrap(); + + assert_eq!(pool.count(), 4); + assert_eq!(pool.num_free(), 4); + assert_eq!(pool.num_free_upper(), 3); + assert_eq!(pool.slot_addr(2), Some(0x10000)); + assert_eq!(pool.slot_addr(3), Some(0x12000)); + assert_eq!(pool.slot_addr(4), None); + + let lower = pool.alloc(128).unwrap(); + let upper = pool.alloc(4096).unwrap(); + let first = pool.alloc(4096).unwrap(); + let second = pool.alloc(4096).unwrap(); + + assert_eq!(pool.num_live(), 4); + assert_eq!(pool.num_free_upper(), 0); + assert_eq!( + pool.live_addrs(), + [lower.addr, upper.addr, 0x10000, 0x12000] + ); + + pool.dealloc(first.addr).unwrap(); + pool.dealloc(second.addr).unwrap(); + assert_eq!(pool.num_free_upper(), 2); +} + +#[test] +fn test_extra_slots_keep_max_free_slot_size_upper() { + let pool = make_tiered_slot_pool(1, 1); + add_slots(&pool, 0x10000, 1).unwrap(); + let _upper = pool.alloc(4096).unwrap(); + + assert_eq!(pool.max_free_slot_size(), Some(4096)); + + let _extra = pool.alloc(4096).unwrap(); + assert_eq!(pool.max_free_slot_size(), Some(256)); +} diff --git a/src/hyperlight_common/src/virtq/producer.rs b/src/hyperlight_common/src/virtq/producer.rs index 5aed7ea27..f3370bfe2 100644 --- a/src/hyperlight_common/src/virtq/producer.rs +++ b/src/hyperlight_common/src/virtq/producer.rs @@ -249,7 +249,6 @@ 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(), @@ -388,6 +387,37 @@ where /// 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> { + // SAFETY: The caller guarantees the bootstrap and old-owner preconditions. + unsafe { self.refresh_inner(info, None) } + } + + /// Refresh private state in place with a new memory backend. + /// + /// Reconstructed chains and the ring use `mem`. Retained owners are unchanged. + /// + /// # Safety + /// + /// The requirements of [`Self::refresh`] apply. `mem` must address the + /// bootstrapped ring and pool described by `info`. + pub unsafe fn refresh_with_memory( + &mut self, + info: BootstrapInfo, + mem: M, + ) -> Result<(), VirtqError> { + // SAFETY: The caller guarantees the bootstrap, old owners, and backend match. + unsafe { self.refresh_inner(info, Some(mem)) } + } + + /// Rebuild private state and optionally replace the memory backend. + /// + /// # Safety + /// + /// See [`Self::refresh`] and [`Self::refresh_with_memory`]. + unsafe fn refresh_inner( + &mut self, + info: BootstrapInfo, + mem: Option, + ) -> Result<(), VirtqError> { if !self.pending.is_empty() { return Err(VirtqError::InvalidState); } @@ -420,6 +450,11 @@ where self.next_token = u32::from(info.avail()); self.release_inflight()?; + + if let Some(mem) = mem { + self.inner.set_mem(mem); + } + self.restore_inflight(info); // Rebuild the ring's private state as well self.inner.refresh(info.avail()); @@ -1752,14 +1787,14 @@ mod tests { #[test] fn prefilled_bootstrap_refresh_reuses_bookkeeping_and_preserves_requests() { let ring = make_ring(4); - let mem = FaultMem::new(ring.mem()); + let old_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(), + old_mem.clone(), notifier.clone(), old_pool.clone(), ); @@ -1780,6 +1815,7 @@ mod tests { let live = producer.inflight.live.as_ptr(); let live_capacity = producer.inflight.live.capacity(); let info = BootstrapInfo::prefilled(ring.layout(), old_pool.layout()).unwrap(); + let mem = FaultMem::new(ring.mem()); info.initialize(&mem).unwrap(); let mut consumer = VirtqConsumer::new(ring.layout(), ring.mem(), notifier.clone()); @@ -1795,10 +1831,12 @@ mod tests { mem.read(ring.layout().desc_table_addr(), &mut before) .unwrap(); mem.fail_write_at(0); + old_mem.fail_write_at(0); + old_mem.deny_views(); // 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(); + // Only the new consumer has accessed the matching bootstrap in `mem`. + unsafe { producer.refresh_with_memory(info, mem.clone()) }.unwrap(); let mut after = vec![0; before.len()]; mem.read(ring.layout().desc_table_addr(), &mut after) @@ -1806,6 +1844,7 @@ mod tests { assert_eq!(before, after); assert_eq!(mem.0.writes.load(Ordering::Relaxed), 0); + assert_eq!(old_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); diff --git a/src/hyperlight_common/src/virtq/ring.rs b/src/hyperlight_common/src/virtq/ring.rs index 0de2c52bc..7ea60f544 100644 --- a/src/hyperlight_common/src/virtq/ring.rs +++ b/src/hyperlight_common/src/virtq/ring.rs @@ -861,6 +861,11 @@ impl RingProducer { &self.mem } + /// Use `mem` for subsequent ring operations. + pub(super) fn set_mem(&mut self, mem: M) { + self.mem = mem; + } + /// Get descriptor table reference #[inline] pub fn desc_table(&self) -> &DescTable { diff --git a/src/hyperlight_guest/src/transport/codec.rs b/src/hyperlight_guest/src/transport/codec.rs index d172f522d..488fddbe9 100644 --- a/src/hyperlight_guest/src/transport/codec.rs +++ b/src/hyperlight_guest/src/transport/codec.rs @@ -9,7 +9,7 @@ use alloc::vec::Vec; use hyperlight_common::flatbuffer_wrappers::ExternalValueSource; use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; use hyperlight_common::flatbuffer_wrappers::function_types::{Bytes, FunctionCallResult}; -use hyperlight_common::stream::Mux; +use hyperlight_common::stream::{GOOD_COPY_LEN, Mux}; use hyperlight_common::transport::{MsgHeader, MsgKind}; use hyperlight_common::virtq::Segments; @@ -56,31 +56,27 @@ pub(super) fn decode_response( } /// Apply one H2G `Stream` message payload to `mux`. -/// -/// DATA is copied to the heap, so its H2G slots can be reposted while readers hold the bytes. pub(super) fn recv_stream(control_len: u32, segments: Segments, mux: &mut Mux) -> Result<()> { let (control, payloads) = decode_payload(control_len, segments)?; - mux.recv_records(&control, &mut CopyingSource(payloads)) + mux.recv_records(&control, &mut StreamSource(payloads)) .with_context(|| "invalid H2G stream message") } -/// Supplies external values as heap copies of transport-backed segments. -/// -/// TODO: Remove this once the transport can support external values without copying. -struct CopyingSource(Segments); +/// Copies small DATA records so they do not pin a slot. Larger records keep their slot owners. +struct StreamSource(Segments); -impl ExternalValueSource for CopyingSource { +impl ExternalValueSource for StreamSource { fn take_bytes(&mut self, length: usize) -> anyhow::Result> { self.0.take_bytes(length) } fn take_chunks(&mut self, length: usize) -> anyhow::Result> { - if length == 0 { - return Ok(Vec::new()); + if (1..=GOOD_COPY_LEN).contains(&length) { + return Ok(vec![Bytes::from(self.0.take_bytes(length)?)]); } - Ok(vec![Bytes::from(self.0.take_bytes(length)?)]) + self.0.take_chunks(length) } fn finish(&mut self) -> anyhow::Result<()> { @@ -286,7 +282,7 @@ mod tests { #[cfg(feature = "streams")] #[test] - fn stream_data_is_copied_out_of_transport_storage() { + fn only_large_stream_records_pin_a_shared_slot() { use core::pin::pin; use core::task::{Context, Poll, Waker}; @@ -299,13 +295,26 @@ mod tests { let mut buffer = Vec::new(); let mut cx = Context::from_waker(Waker::noop()); - let (reader, mut writer) = stream::new::(); - let written = pin!(writer.write(b"data")).poll(&mut cx); - assert!(matches!(written, Poll::Ready(Ok(4)))); + let small_data = [0x5a; GOOD_COPY_LEN]; + let large_data = [0xa5; GOOD_COPY_LEN + 1]; + let (small, mut small_writer) = stream::new::(); + let (large, mut large_writer) = stream::new::(); + + assert_eq!( + pin!(small_writer.write(&small_data)).poll(&mut cx), + Poll::Ready(Ok(small_data.len())) + ); + assert_eq!( + pin!(large_writer.write(&large_data)).poll(&mut cx), + Poll::Ready(Ok(large_data.len())) + ); let call = FunctionCall::new( "read".into(), - Some(vec![ParameterValue::StreamReader(reader)]), + Some(vec![ + ParameterValue::StreamReader(small), + ParameterValue::StreamReader(large), + ]), FunctionCallType::Guest, ReturnType::Void, ); @@ -313,29 +322,46 @@ mod tests { let pending = PendingMessage::new_call(call, 1, &mut host).unwrap(); let msg = pending.encode(&mut buffer).unwrap(); let segments = Segments::single(Bytes::copy_from_slice(msg.control())); - let call = decode_request(msg.header().control_len, segments, &mut guest).unwrap(); + let mut call = decode_request(msg.header().control_len, segments, &mut guest).unwrap(); drop(msg); pending.settle(Ok(())).unwrap(); - let Some(ParameterValue::StreamReader(mut reader)) = call.parameters.unwrap().pop() else { - panic!("expected a reader parameter"); + let Some( + [ + ParameterValue::StreamReader(small), + ParameterValue::StreamReader(large), + ], + ) = call.parameters.as_deref_mut() + else { + panic!("expected two reader parameters"); }; let pending = PendingMessage::next_stream(&mut host, 4096).unwrap(); let msg = pending.encode(&mut buffer).unwrap(); - let external: Vec = msg.external_chunks().flatten().copied().collect(); - let external = Bytes::from(external); - let external_ptr = external.as_ptr(); - let segments = Segments::new([Bytes::copy_from_slice(msg.control()), external]); + let mut slot = msg.control().to_vec(); + + for chunk in msg.external_chunks() { + slot.extend_from_slice(chunk); + } + let slot = Bytes::from(slot); + let segments = Segments::single(slot.clone()); recv_stream(msg.header().control_len, segments, &mut guest).unwrap(); - let Poll::Ready(Ok(Some(chunk))) = pin!(reader.read_chunk()).poll(&mut cx) else { - panic!("expected a DATA chunk"); + let Poll::Ready(Ok(Some(small))) = pin!(small.read_chunk()).poll(&mut cx) else { + panic!("expected the small DATA record"); }; - assert_eq!(chunk.as_ref(), b"data"); - assert_ne!(chunk.as_ptr(), external_ptr); + let Poll::Ready(Ok(Some(large))) = pin!(large.read_chunk()).poll(&mut cx) else { + panic!("expected the large DATA record"); + }; + + assert_eq!(large.as_ref(), large_data); + assert!(slot.as_ptr_range().contains(&large.as_ptr())); + drop(large); + + assert!(slot.is_unique()); + assert_eq!(small.as_ref(), small_data); } } diff --git a/src/hyperlight_guest/src/transport/context.rs b/src/hyperlight_guest/src/transport/context.rs index 746af1f41..010566886 100644 --- a/src/hyperlight_guest/src/transport/context.rs +++ b/src/hyperlight_guest/src/transport/context.rs @@ -5,6 +5,7 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; +use core::ops::Range; use core::result; use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, FunctionCallType}; @@ -28,7 +29,7 @@ use hyperlight_common::vmem::PAGE_SIZE; use super::{GuestMemOps, codec}; use crate::error::{GuestErrorContext, Result}; use crate::exit::out32; -use crate::{bail, ensure, layout, task}; +use crate::{bail, ensure, layout, paging, prim_alloc, task}; /// Exits to the host to process available virtqueue work. #[derive(Clone, Copy)] @@ -144,7 +145,7 @@ impl GuestContext { let arena_gva = g2h.layout.desc_table_addr(); let scratch_gva = layout::scratch_base_gva(); // SAFETY: The caller owns the pool's scratch pages. - let mem = unsafe { pool_mem(&g2h_pool, arena_gva, scratch_gva) } + let mem = unsafe { pool_mem(&g2h_pool, arena_gva, arena_gva, scratch_gva) } .with_context(|| "failed to initialize G2H pool access")?; g2h.layout .initialize(&mem) @@ -155,8 +156,9 @@ impl GuestContext { .with_context(|| "invalid H2G pool geometry")?; let h2g_pool = SlotPool::from_layout(h2g_layout).with_context(|| "failed to create H2G slot pool")?; + let floor_gva = scratch_floor_gva()?; // SAFETY: The caller owns this disjoint pool. - let mem = unsafe { pool_mem(&h2g_pool, arena_gva, scratch_gva) } + let mem = unsafe { pool_mem(&h2g_pool, floor_gva, arena_gva, scratch_gva) } .with_context(|| "failed to initialize H2G pool access")?; h2g.layout .initialize(&mem) @@ -547,15 +549,24 @@ impl GuestContext { 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 or builders. No producer has run. - // Retained views have captured backing and old pool handles only release leases. + // New extra slots lie above the reset scratch allocator's floor. + let floor_gva = scratch_floor_gva().expect("invalid scratch allocator"); + let arena_gva = g2h.layout().desc_table_addr(); + let scratch_gva = layout::scratch_base_gva(); + + // SAFETY: The context owns the pool's scratch pages. + let h2g_mem = unsafe { pool_mem(h2g.pool(), floor_gva, arena_gva, scratch_gva) } + .expect("invalid H2G pool placement"); + + // SAFETY: The host replaced the queues with the matching bootstrap and no live chain + // handles or builders. No producer has run. Retained views have captured backing and + // old pools only release leases. h2g_mem covers the new H2G ring and pool. unsafe { self.g2h_producer .refresh(g2h_info) .expect("G2H ownership reconstruction failed"); self.h2g_producer - .refresh(h2g_info) + .refresh_with_memory(h2g_info, h2g_mem) .expect("H2G ownership reconstruction failed"); } @@ -575,29 +586,62 @@ impl GuestContext { self.send_g2h_oneshot(&message) } - /// Publish one writable H2G chain for each currently free slot. + /// Keep the bootstrap count of writable H2G buffers posted. + /// + /// Guest code can retain H2G buffers past its turn, such as `ByteChunks` arguments. Their + /// slots stay allocated until the last view drops, so the pool grows on fresh scratch pages + /// and the host keeps its receive capacity. fn prefill_h2g(&mut self) -> Result<()> { + let producer = &self.h2g_producer; + + let ring_len = usize::from(producer.layout().desc_table_len()); + let target = producer.pool().layout().slot_count().min(ring_len); + + let refill = target.saturating_sub(producer.num_inflight()); + let free = producer.pool().num_free(); + + if free < refill { + self.add_h2g_slots(refill - free)?; + } + let mut batch = self.h2g_producer.batch(); - loop { + for _ in 0..refill { let chain = match batch.chain().writable(self.h2g_slot_size).build() { Ok(chain) => chain, - Err(error) if error.is_transient() => { - batch.finish_without_notify(); - return Ok(()); - } Err(error) => bail!("H2G prefill build: {error}"), }; - match batch.submit(chain) { - Ok(_) => {} - Err(error) if error.is_transient() => { - batch.finish_without_notify(); - return Ok(()); - } - Err(error) => bail!("H2G prefill submit: {error}"), + if let Err(error) = batch.submit(chain) { + bail!("H2G prefill submit: {error}"); } } + + batch.finish_without_notify(); + Ok(()) + } + + /// Add at least `count` H2G slots on fresh scratch pages. + /// + /// The slots stay in the pool until the next generation resets the scratch allocator. Running + /// out of scratch aborts the guest. + fn add_h2g_slots(&self, count: usize) -> Result<()> { + let size = self.h2g_slot_size; + + let pages = count + .checked_mul(size) + .context("H2G slot growth overflow")? + .div_ceil(PAGE_SIZE); + + // SAFETY: Construction requires initialized guest scratch metadata. + let gpa = unsafe { prim_alloc::alloc_phys_pages(pages as u64) }; + let gva = paging::phys_to_virt(gpa).context("scratch page lies below scratch")?; + + let pool = self.h2g_producer.pool(); + // SAFETY: The allocator hands these pages out once per generation, which the producer + // does not outlive. Its backend binds them from the generation's scratch floor. + unsafe { pool.add_slots(gva as u64, pages * PAGE_SIZE / size) } + .context("failed to add H2G slots") } /// Submit a one-way G2H message without polling its acknowledgement. @@ -725,38 +769,70 @@ fn pool_len(pages: usize) -> result::Result { .ok_or(AllocError::Overflow) } -/// Validate pool placement and bind access to the arena up to the pool's end. +/// GVA of the scratch allocator's next free page. /// -/// The bounds start at the arena, whose address does not depend on the -/// scratch size. The pools follow the rings, so a producer's rings and pool -/// lie in [arena, end of its pool). That range must start in scratch above -/// `scratch_gva`, where the copied page tables sit, and end below the guard -/// page under the reserved scratch-top pages. +/// The bump allocator never frees within a generation, so pages it hands out later lie between +/// this floor and the transport arena. +fn scratch_floor_gva() -> Result { + // SAFETY: Construction requires initialized guest scratch metadata. + let gpa = unsafe { layout::allocator_gva().read_volatile() }; + let gva = paging::phys_to_virt(gpa).context("scratch allocator lies below scratch")?; + Ok(gva as u64) +} + +/// Validate pool placement and return the range its backend binds. /// -/// # Safety +/// The arena's address does not depend on the scratch size. The pools follow +/// the rings, so a producer's rings and pool lie in [arena, end of its pool). +/// The range runs from `start_gva` to the pool's end. It must start in scratch +/// above `scratch_gva`, where the copied page tables sit, at or below the arena. +/// It ends below the guard page under the reserved scratch-top pages. /// -/// Run on the initialized guest vCPU and own the pool's scratch. -unsafe fn pool_mem( +/// G2H starts at the arena. H2G starts at the scratch allocator's floor, so it +/// also covers the slots `add_h2g_slots` adds from later pages. That range +/// holds pages the producer does not own, and the producer touches only its +/// rings and slots. +fn pool_range( pool: &SlotPool, + start_gva: u64, arena_gva: u64, scratch_gva: u64, -) -> result::Result { +) -> result::Result, AllocError> { let limit = scratch_transport_end_gva(); + let page = PAGE_SIZE as u64; let base = pool.base_addr(); let end = base + pool.byte_len() as u64; - if !arena_gva.is_multiple_of(PAGE_SIZE as u64) - || arena_gva <= scratch_gva - || !base.is_multiple_of(PAGE_SIZE as u64) + if !start_gva.is_multiple_of(page) + || !arena_gva.is_multiple_of(page) + || !base.is_multiple_of(page) + || start_gva <= scratch_gva + || start_gva > arena_gva || base < arena_gva || end > limit { return Err(AllocError::InvalidArg); } - // SAFETY: The validated pool lies in the arena on the serialized guest vCPU. - unsafe { Ok(GuestMemOps::new(arena_gva, end)) } + Ok(start_gva..end) +} + +/// Bind access to the range [`pool_range`] validates. +/// +/// # Safety +/// +/// Run on the initialized guest vCPU and own the pool's scratch. +unsafe fn pool_mem( + pool: &SlotPool, + start_gva: u64, + arena_gva: u64, + scratch_gva: u64, +) -> result::Result { + let range = pool_range(pool, start_gva, arena_gva, scratch_gva)?; + + // SAFETY: The validated range lies in live scratch on the serialized guest vCPU. + unsafe { Ok(GuestMemOps::new(range.start, range.end)) } } /// Build the tiered G2H pool. @@ -791,7 +867,7 @@ mod tests { use super::*; #[test] - fn pool_mem_binds_the_arena_below_the_reserved_top() { + fn pool_range_binds_the_arena_below_the_reserved_top() { let limit = scratch_transport_end_gva(); let page = PAGE_SIZE as u64; let arena = limit - 8 * page; @@ -799,18 +875,36 @@ mod tests { let pool = |base, pages| { SlotPool::from_layout(h2g_pool_layout(base, pages, 256).unwrap()).unwrap() }; - // SAFETY: only bounds are computed. No memory is touched. - unsafe { - assert!(pool_mem(&pool(arena + 4 * page, 4), arena, scratch).is_ok()); - // Into the guard page or the reserved pages. - assert!(pool_mem(&pool(arena + 4 * page, 5), arena, scratch).is_err()); - // Below the arena. - assert!(pool_mem(&pool(arena - page, 1), arena, scratch).is_err()); - // An arena below scratch, at its base, or not page aligned. - assert!(pool_mem(&pool(arena + 4 * page, 4), 0, scratch).is_err()); - assert!(pool_mem(&pool(arena + 4 * page, 4), scratch, scratch).is_err()); - assert!(pool_mem(&pool(arena + 4 * page, 4), arena + 8, scratch).is_err()); - } + + let range = pool_range(&pool(arena + 4 * page, 4), arena, arena, scratch); + assert_eq!(range.unwrap(), arena..limit); + // Into the guard page or the reserved pages. + assert!(pool_range(&pool(arena + 4 * page, 5), arena, arena, scratch).is_err()); + // Below the arena. + assert!(pool_range(&pool(arena - page, 1), arena, arena, scratch).is_err()); + // An arena below scratch, at its base, or not page aligned. + assert!(pool_range(&pool(arena + 4 * page, 4), 0, 0, scratch).is_err()); + assert!(pool_range(&pool(arena + 4 * page, 4), scratch, scratch, scratch).is_err()); + assert!(pool_range(&pool(arena + 4 * page, 4), arena, arena + 8, scratch).is_err()); + } + + #[test] + fn pool_range_starts_between_scratch_and_the_arena() { + let limit = scratch_transport_end_gva(); + let page = PAGE_SIZE as u64; + let arena = limit - 8 * page; + let scratch = arena - 16 * page; + // The pool ends a page below the limit, so the range ends with it. + let layout = h2g_pool_layout(arena + 4 * page, 3, 256).unwrap(); + let pool = SlotPool::from_layout(layout).unwrap(); + let start = scratch + page; + + let range = pool_range(&pool, start, arena, scratch); + assert_eq!(range.unwrap(), start..limit - page); + // At the scratch base, above the arena, or not page aligned. + assert!(pool_range(&pool, scratch, arena, scratch).is_err()); + assert!(pool_range(&pool, arena + page, arena, scratch).is_err()); + assert!(pool_range(&pool, start + 8, arena, scratch).is_err()); } fn encoded_message(external: &[u8]) -> EncodedMessage<'_> { diff --git a/src/hyperlight_guest/src/transport/mem.rs b/src/hyperlight_guest/src/transport/mem.rs index d256e7e9e..0813bae5a 100644 --- a/src/hyperlight_guest/src/transport/mem.rs +++ b/src/hyperlight_guest/src/transport/mem.rs @@ -17,8 +17,8 @@ use super::backing; // Mark types not [`Send`] type NotThreadSafe = PhantomData<*mut ()>; -/// Memory access bounded to a range of scratch: the transport arena, for -/// the producers. +/// Memory access bounded to a range of scratch: the transport arena, and for +/// H2G the scratch pages below it that hold extra slots. /// /// Copies reject buffers that overlap the accessed range. #[derive(Clone, Copy, Debug)] @@ -33,8 +33,7 @@ pub(crate) struct GuestMemOps { pub struct GuestMemError; impl GuestMemOps { - /// Bind memory access to `[start, end)`, a live part of - /// scratch (the transport arena, for the producers). + /// Bind memory access to `[start, end)`, a live part of scratch. /// /// # Safety /// diff --git a/src/hyperlight_host/tests/sandbox_host_tests.rs b/src/hyperlight_host/tests/sandbox_host_tests.rs index ec74f7ccc..c4ab8edaa 100644 --- a/src/hyperlight_host/tests/sandbox_host_tests.rs +++ b/src/hyperlight_host/tests/sandbox_host_tests.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex}; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_common::func::Bytes; use hyperlight_host::sandbox::SandboxConfiguration; -use hyperlight_host::{HyperlightError, Result, SandboxBuilder, new_error}; +use hyperlight_host::{HyperlightError, Result, Sandbox, SandboxBuilder, new_error}; use hyperlight_testing::simple_guest_as_pathbuf; pub mod common; // pub to disable dead_code warning @@ -629,23 +629,95 @@ fn h2g_capacity_failure_does_not_poison_sandbox() { with_rust_uninit_sandbox_cfg(cfg, |sandbox| { let mut sandbox = sandbox.evolve().unwrap(); - let retained = vec![0u8; 12_000]; - - sandbox - .call::( - "RetainGuestByteChunks", - vec![Bytes::copy_from_slice(&retained)], - ) - .unwrap(); + // The request alone needs 5 of the 4 posted buffers. let error = sandbox - .call::>("EchoGuestVecBytes", vec![0u8; 9 * 1024]) + .call::>("EchoGuestVecBytes", vec![0u8; 16 * 1024]) .unwrap_err(); assert!(error.to_string().contains("H2G capacity")); + assert!(!sandbox.status().is_poisoned()); + + let expected = vec![0x5a; 9 * 1024]; + let actual: Vec = sandbox.call("EchoGuestVecBytes", expected.clone()).unwrap(); + assert_eq!(actual, expected); + }); +} + +/// Retain one more 1 KiB chunk, then fill every posted H2G buffer and read the chunks back. +fn append_and_fill_h2g(sandbox: &mut Sandbox, chunks: &mut Vec, fill: u8) { + let chunk = Bytes::from(vec![fill; 1024]); + chunks.push(chunk.clone()); + + let retained: i32 = sandbox.call("AppendGuestByteChunks", vec![chunk]).unwrap(); + assert_eq!(retained as usize, chunks.len() * 1024); + + // The request and its spare take all 8 buffers the default H2G pool posts. + let len: i32 = sandbox + .call("ByteChunksLen", vec![Bytes::from(vec![0x3c; 24 * 1024])]) + .unwrap(); + assert_eq!(len, 24 * 1024); + + let actual: Vec = sandbox.call("ReadRetainedGuestByteChunks", ()).unwrap(); + assert_eq!(actual.concat(), chunks.concat()); +} + +/// Each retained chunk keeps its H2G buffer, and the guest posts another buffer in its place. +#[test] +fn retained_guest_byte_chunks_keep_h2g_capacity() { + with_rust_sandbox(|mut sandbox| { + let mut chunks = Vec::new(); + + // 12 retained buffers against the 8 in the pool. + for fill in 1..=12 { + append_and_fill_h2g(&mut sandbox, &mut chunks, fill); + } + + // Buffers added after capture or restore leave the captured chunks intact. + let snapshot = sandbox.snapshot().unwrap(); + append_and_fill_h2g(&mut sandbox, &mut chunks, 13); + + sandbox.restore(snapshot).unwrap(); + chunks.truncate(12); + append_and_fill_h2g(&mut sandbox, &mut chunks, 14); let released: i32 = sandbox.call("ReleaseGuestByteChunks", ()).unwrap(); - assert_eq!(released as usize, retained.len()); + assert_eq!(released, 13 * 1024); + }); +} + +/// Retained guest chunks grow the H2G pool until scratch runs out, which aborts the guest. +#[test] +fn retained_guest_byte_chunks_abort_when_scratch_runs_out() { + with_rust_sandbox(|mut sandbox| { + let snapshot = sandbox.snapshot().unwrap(); + let chunk = Bytes::from(vec![0x5a; 1024]); + let mut retained = 0; + + // Each chunk holds a 4 KiB slot, and 400 KiB of scratch holds fewer than 100. + let error = loop { + assert!(retained < 100, "scratch never ran out"); + + match sandbox.call::("AppendGuestByteChunks", vec![chunk.clone()]) { + Ok(len) => { + retained += 1; + assert_eq!(len, retained * 1024); + } + Err(error) => break error, + } + }; + + // More chunks than the 8 slots of the default H2G pool. + assert!(retained > 8, "{retained}"); + assert!( + matches!(&error, HyperlightError::GuestAborted(code, _) if *code == ErrorCode::MallocFailed as u8), + "{error:?}" + ); + assert!(sandbox.status().is_poisoned()); + + sandbox.restore(snapshot).unwrap(); + let actual: Vec = sandbox.call("ReadRetainedGuestByteChunks", ()).unwrap(); + assert!(actual.is_empty()); }); } diff --git a/src/hyperlight_host/tests/stream_tests.rs b/src/hyperlight_host/tests/stream_tests.rs index 5184af893..249cf4fbf 100644 --- a/src/hyperlight_host/tests/stream_tests.rs +++ b/src/hyperlight_host/tests/stream_tests.rs @@ -684,6 +684,55 @@ fn retained_host_replies_leave_lower_slots_for_streams() { }); } +/// Retained guest chunks hold every H2G pool slot, and a drive streams through extra buffers. +#[test] +fn retained_guest_byte_chunks_leave_h2g_buffers_for_streams() { + let window = DEFAULT_WINDOW.get() as usize; + let data: Vec = (0..4 * window + 17).map(|i| (i % 251) as u8).collect(); + + with_rust_sandbox(|mut sandbox| { + // Each 1 KiB chunk holds one of the 8 slots of the default H2G pool. + for len in 1..=8 { + let chunk = Bytes::from(vec![0x5a; 1024]); + let retained: i32 = sandbox.call("AppendGuestByteChunks", vec![chunk]).unwrap(); + assert_eq!(retained, len * 1024); + } + + let (input, mut writer) = stream::new(); + let mut reader: StreamReader = sandbox.call("EchoStream", input).unwrap(); + + let send = async { + writer.write_all(&data).await?; + writer.close(); + Ok::<_, DriveError>(()) + }; + let receive = async { + let mut received = Vec::new(); + + while let Some(chunk) = reader.read_chunk().await? { + received.extend_from_slice(&chunk); + } + + Ok::<_, DriveError>(received) + }; + + let ((), received) = sandbox + .block_on(async { tokio::try_join!(send, receive) }) + .unwrap(); + + assert_eq!(received, data); + + // The request and its spare take all 8 buffers the last progress turn posted. + let len: i32 = sandbox + .call("ByteChunksLen", vec![Bytes::from(vec![0x3c; 24 * 1024])]) + .unwrap(); + assert_eq!(len, 24 * 1024); + + let released: i32 = sandbox.call("ReleaseGuestByteChunks", ()).unwrap(); + assert_eq!(released, 8 * 1024); + }); +} + /// A full H2G queue leaves stream records pending, and each later call sends one more message. #[test] fn full_h2g_queue_defers_stream_messages() { @@ -880,8 +929,8 @@ fn host_function_returns_a_future_through_a_result() { /// A guest task reads the host stream across several windows, then resolves the future. #[test] fn produced_future_counts_a_host_stream() { - let window = DEFAULT_WINDOW.get() as usize; - let data: Vec = (0..4 * window + 17).map(|i| (i % 251) as u8).collect(); + let size = 4 * DEFAULT_WINDOW.get() as usize + 17; + let data: Vec = (0..size).map(|i| (i % 251) as u8).collect(); with_rust_sandbox(|mut sandbox| { let (input, mut writer) = stream::new(); @@ -889,13 +938,13 @@ fn produced_future_counts_a_host_stream() { let len = sandbox .block_on(async { - writer.write_all(&data).await?; + writer.write_chunk(data.into()).await?; writer.close(); Ok::<_, DriveError>(len.await?) }) .unwrap(); - assert_eq!(len, data.len().to_string()); + assert_eq!(len, size.to_string()); }); } diff --git a/src/tests/rust_guests/simpleguest/src/main.rs b/src/tests/rust_guests/simpleguest/src/main.rs index 19a6d0c82..f1c4ab6ca 100644 --- a/src/tests/rust_guests/simpleguest/src/main.rs +++ b/src/tests/rust_guests/simpleguest/src/main.rs @@ -457,6 +457,18 @@ fn retain_guest_byte_chunks(data: Vec) -> i32 { len as i32 } +/// Retain `data` after the bytes already retained, and return the total retained length. +#[guest_function("AppendGuestByteChunks")] +fn append_guest_byte_chunks(data: Vec) -> i32 { + // SAFETY: the guest is single threaded, so the static has no concurrent access. + #[allow(static_mut_refs)] + unsafe { + let retained = RETAINED_GUEST_CHUNKS.get_or_insert_default(); + retained.extend(data); + retained.iter().map(Bytes::len).sum::() as i32 + } +} + /// Return the retained bytes without releasing their buffers. #[guest_function("ReadRetainedGuestByteChunks")] fn read_retained_guest_byte_chunks() -> Vec { @@ -512,7 +524,7 @@ fn release_host_byte_chunks() -> i32 { #[guest_function("StreamBytes")] fn stream_bytes(data: Vec, abort: bool) -> StreamReader { stream::produce(async move |writer| { - writer.write_all(&data).await?; + writer.write_chunk(data.into()).await?; if abort { Err(StreamError::Aborted) @@ -541,7 +553,7 @@ fn stream_panic() -> StreamReader { let data = vec![0; len]; stream::produce::<_, StreamError>(async move |writer| { - writer.write_all(&data).await?; + writer.write_chunk(data.into()).await?; panic!("stream task panic"); }) } @@ -598,7 +610,7 @@ fn stream_then_wait(data: Vec) -> StreamReader { stream::produce(async move |writer| { let _live = live; - writer.write_all(&data).await?; + writer.write_chunk(data.into()).await?; core::future::pending::>().await }) } @@ -750,7 +762,7 @@ fn send_stream(data: Vec) -> Result> { host_keep_stream(reader)?; Ok(future::produce(async move { - writer.write_all(&data).await?; + writer.write_chunk(data.into()).await?; writer.close(); Ok::<_, StreamError>(()) }))