Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
8 changes: 5 additions & 3 deletions docs/how-to-build-a-hyperlight-guest-binary.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,11 @@ return value or the guest function's parameter decides:
* `Vec<u8>` 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
Expand Down
46 changes: 38 additions & 8 deletions docs/virtio-host-guest-communication.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -398,25 +407,46 @@ 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.

```text
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<u8>`.
* 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
Expand Down Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions src/hyperlight_common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
edition.workspace = true
rust-version.workspace = true
license.workspace = true
homepage.workspace = true

Check warning on line 7 in src/hyperlight_common/Cargo.toml

View workflow job for this annotation

GitHub Actions / miri (arm64) / miri

`package.homepage` is redundant with `package.repository`

Check warning on line 7 in src/hyperlight_common/Cargo.toml

View workflow job for this annotation

GitHub Actions / miri (X64) / miri

`package.homepage` is redundant with `package.repository`
repository.workspace = true
readme.workspace = true
description = """
Expand Down Expand Up @@ -56,6 +56,10 @@
name = "buffer_pool"
harness = false

[[bench]]
name = "stream_pipe"
harness = false

[[bench]]
name = "virtq_api"
harness = false
59 changes: 59 additions & 0 deletions src/hyperlight_common/benches/stream_pipe.rs
Original file line number Diff line number Diff line change
@@ -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<F: Future>(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::<u8>();

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::<u8>();

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);
2 changes: 1 addition & 1 deletion src/hyperlight_common/src/future/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>(())
});
Expand Down
2 changes: 2 additions & 0 deletions src/hyperlight_common/src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]>;
Expand Down
Loading
Loading