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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
* Add `HYPERLIGHT_SURROGATE_EXTRACT_DIR` to configure the surrogate extraction directory on Windows.
* Add `Sandbox::recreate()`, which rebuilds a sandbox's VM and memory from a snapshot. It recovers unrecoverable sandboxes and keeps configuration, host functions, and interrupt handles by @ludfjig in https://github.com/hyperlight-dev/hyperlight/pull/1751
* Add ARM64 Linux MSHV support by @cshung in https://github.com/hyperlight-dev/hyperlight/pull/1626
* Add `SandboxBuilder::scratch_transparent_huge_pages` and
`SandboxConfiguration::set_scratch_transparent_huge_pages` to request
transparent huge pages for scratch.

### Changed
* `hyperlight-host` requires Rust 1.95.
Expand All @@ -32,6 +35,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
page size, and log level.
* **Breaking:** Encode function calls with serde/postcard instead of FlatBuffers.
* Stop resetting guest FPU state between guest calls to improve performance.
* Align scratch memory of 2 MiB or more with its guest address on Linux so
KVM and MSHV can map it with 2 MiB pages when transparent huge pages are set
to `always`. First heap use is up to 10× faster on KVM.

### Fixed
* Fix surrogate process creation for Windows paths containing Unicode or spaces.
Expand Down
27 changes: 23 additions & 4 deletions src/hyperlight_host/src/mem/mgr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,8 @@ pub(crate) struct SandboxMemoryManager<S: SharedMemory> {
pub(crate) h2g_consumer: Option<H2gConsumer>,
/// Correlation ID sequence survives consumer replacement and manager cloning.
next_guest_cid: u32,
/// Applied to scratch that a restore reallocates.
scratch_transparent_huge_pages: bool,
}

impl<S: Clone + SharedMemory> Clone for SandboxMemoryManager<S> {
Expand All @@ -399,6 +401,7 @@ impl<S: Clone + SharedMemory> Clone for SandboxMemoryManager<S> {
g2h_consumer: None,
h2g_consumer: None,
next_guest_cid: self.next_guest_cid,
scratch_transparent_huge_pages: self.scratch_transparent_huge_pages,
}
}
}
Expand Down Expand Up @@ -544,6 +547,7 @@ where
g2h_consumer: None,
h2g_consumer: None,
next_guest_cid: 1,
scratch_transparent_huge_pages: false,
}
}

Expand All @@ -554,12 +558,21 @@ where
}

impl SandboxMemoryManager<ExclusiveSharedMemory> {
pub(crate) fn from_snapshot(s: &Snapshot) -> Result<Self> {
pub(crate) fn from_snapshot(
s: &Snapshot,
scratch_transparent_huge_pages: bool,
) -> Result<Self> {
let layout = *s.layout();
let shared_mem = SnapshotMemoryBacking::from_snapshot(s.snapshot_memory().clone())?;
let scratch_mem = ExclusiveSharedMemory::new(s.layout().get_scratch_size())?;
let scratch_size = s.layout().get_scratch_size();
let scratch_mem = ExclusiveSharedMemory::new_for_gpa(
scratch_size,
hyperlight_common::layout::scratch_base_gpa(scratch_size),
scratch_transparent_huge_pages,
)?;
let next_action = s.next_action();
let mut mgr = Self::new(layout, shared_mem, scratch_mem, next_action);
mgr.scratch_transparent_huge_pages = scratch_transparent_huge_pages;
mgr.original_entrypoint = s.original_entrypoint();
// Inherit the snapshot's generation number for the same
// reason `restore_snapshot` does: the guest-visible counter
Expand Down Expand Up @@ -598,6 +611,7 @@ impl SandboxMemoryManager<ExclusiveSharedMemory> {
g2h_consumer: None,
h2g_consumer: None,
next_guest_cid: self.next_guest_cid,
scratch_transparent_huge_pages: self.scratch_transparent_huge_pages,
};
let guest_mgr = SandboxMemoryManager {
shared_mem: gshm,
Expand All @@ -610,6 +624,7 @@ impl SandboxMemoryManager<ExclusiveSharedMemory> {
g2h_consumer: None,
h2g_consumer: None,
next_guest_cid: self.next_guest_cid,
scratch_transparent_huge_pages: self.scratch_transparent_huge_pages,
};
host_mgr.update_scratch_bookkeeping()?;

Expand Down Expand Up @@ -1027,7 +1042,11 @@ impl SandboxMemoryManager<HostSharedMemory> {
// the current platform (see SharedMemory::zero_or_replace).
self.scratch_mem.zero_or_replace()?
} else {
let new_scratch_mem = ExclusiveSharedMemory::new(new_scratch_size)?;
let new_scratch_mem = ExclusiveSharedMemory::new_for_gpa(
new_scratch_size,
hyperlight_common::layout::scratch_base_gpa(new_scratch_size),
self.scratch_transparent_huge_pages,
)?;
let (hscratch, gscratch) = new_scratch_mem.build();
// Even though this destroys the reference to the host
// side of the old scratch mapping, the VM should still
Expand Down Expand Up @@ -1610,7 +1629,7 @@ mod tests {

let snapshot = Snapshot::from_binary(bin, config).unwrap();

let mgr = SandboxMemoryManager::from_snapshot(&snapshot).unwrap();
let mgr = SandboxMemoryManager::from_snapshot(&snapshot, false).unwrap();
let (mgr, _) = mgr.build().unwrap();

assert!(mgr.g2h_consumer.is_some());
Expand Down
161 changes: 149 additions & 12 deletions src/hyperlight_host/src/mem/shared_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ use crate::log_then_return;

type Result<T> = core::result::Result<T, SharedMemoryError>;

/// KVM and MSHV map guest memory with 2 MiB pages only when the host backs
/// it with huge pages and its host and guest addresses are equal modulo this
/// size.
#[cfg(unix)]
pub(crate) const GUEST_MEMORY_ALIGNMENT: usize = 0x20_0000;

/// This is just an alias for std::backtrace::Backtrace that we
/// introduce to stop thiserror from using its backtrace
/// functionality, which depends on nightly APIs.
Expand Down Expand Up @@ -99,6 +105,10 @@ pub enum SharedMemoryError {
#[error("mprotect failed with os error {0:?}")]
MprotectFailed(Option<i32>),

/// A call to `madvise` failed, with the OS error code.
#[error("madvise failed with os error {0:?}")]
MadviseFailed(Option<i32>),

/// A Windows virtual memory API call failed
#[cfg(target_os = "windows")]
#[error("Windows API Error Result {0:?}")]
Expand Down Expand Up @@ -225,8 +235,15 @@ impl_atomic_access!(std::sync::atomic::AtomicUsize, usize);
/// Send or Sync, since it doesn't ensure any particular synchronization.
#[derive(Debug)]
pub struct HostMapping {
/// Owns the whole reservation and unmaps it on drop.
#[cfg(not(target_os = "windows"))]
_reservation: Mmap,
/// Start of the guarded range inside `_reservation`.
#[cfg(not(target_os = "windows"))]
base: *mut u8,
/// Length of the guarded range, including both guard pages.
#[cfg(not(target_os = "windows"))]
mmap: Mmap,
len: usize,
#[cfg(target_os = "windows")]
mapping: WindowsMapping,
}
Expand Down Expand Up @@ -268,7 +285,7 @@ impl HostMapping {
pub(crate) fn ptr(&self) -> *mut u8 {
#[cfg(not(target_os = "windows"))]
{
self.mmap.base as *mut u8
self.base
}
#[cfg(target_os = "windows")]
match &self.mapping {
Expand All @@ -281,7 +298,7 @@ impl HostMapping {
pub(crate) fn size(&self) -> usize {
#[cfg(not(target_os = "windows"))]
{
self.mmap.len
self.len
}
#[cfg(target_os = "windows")]
match &self.mapping {
Expand Down Expand Up @@ -709,6 +726,56 @@ impl ExclusiveSharedMemory {
#[cfg(unix)]
#[instrument(skip_all, parent = Span::current(), level= "Trace")]
pub fn new(min_size_bytes: usize) -> Result<Self> {
Self::new_with_offset(min_size_bytes, None)
}

/// Like [`Self::new`], but [`SharedMemory::base_addr`] equals `gpa` modulo
/// [`GUEST_MEMORY_ALIGNMENT`] when `min_size_bytes` is at least that size
/// and `gpa` is host-page aligned. With `transparent_huge_pages`, requests
/// transparent huge pages with `MADV_HUGEPAGE`.
#[cfg(all(target_os = "linux", not(miri)))]
#[instrument(skip_all, parent = Span::current(), level= "Trace")]
pub(crate) fn new_for_gpa(
min_size_bytes: usize,
gpa: u64,
transparent_huge_pages: bool,
) -> Result<Self> {
let gpa = gpa as usize;
let mem =
if min_size_bytes < GUEST_MEMORY_ALIGNMENT || !gpa.is_multiple_of(page_size::get()) {
Self::new(min_size_bytes)?
} else {
Self::new_with_offset(min_size_bytes, Some(gpa % GUEST_MEMORY_ALIGNMENT))?
};
if transparent_huge_pages {
// SAFETY: The range is a live, page-aligned mapping owned by `mem`.
// `MADV_HUGEPAGE` does not change its contents or permissions.
let ret = unsafe {
libc::madvise(mem.base_ptr().cast(), mem.mem_size(), libc::MADV_HUGEPAGE)
};
if ret != 0 {
return Err(SharedMemoryError::MadviseFailed(
Error::last_os_error().raw_os_error(),
));
}
}
Ok(mem)
}

/// Like [`Self::new`]. Ignores `gpa` and `transparent_huge_pages`.
#[cfg(not(all(target_os = "linux", not(miri))))]
pub(crate) fn new_for_gpa(
min_size_bytes: usize,
_gpa: u64,
_transparent_huge_pages: bool,
) -> Result<Self> {
Self::new(min_size_bytes)
}

/// Allocates the region. With `offset`, the usable memory's address
/// equals `offset` modulo [`GUEST_MEMORY_ALIGNMENT`].
#[cfg(unix)]
fn new_with_offset(min_size_bytes: usize, offset: Option<usize>) -> Result<Self> {
use libc::{
MAP_ANONYMOUS, MAP_FAILED, MAP_PRIVATE, PROT_READ, PROT_WRITE, c_int, mmap, off_t,
size_t,
Expand All @@ -725,10 +792,17 @@ impl ExclusiveSharedMemory {
#[cfg(miri)]
let flags = MAP_ANONYMOUS | MAP_PRIVATE;

// Reserve one alignment unit more than needed. The unused ends become
// part of the guard pages.
let reserve_size = match offset {
Some(_) => total_size + GUEST_MEMORY_ALIGNMENT,
None => total_size,
};

let addr = unsafe {
mmap(
null_mut(),
total_size as size_t,
reserve_size as size_t,
PROT_READ | PROT_WRITE,
flags,
-1 as c_int,
Expand All @@ -742,22 +816,37 @@ impl ExclusiveSharedMemory {
}
let mmap = Mmap {
base: addr,
len: total_size,
len: reserve_size,
};

// protect the guard pages
let head = match offset {
Some(offset) => {
let usable = addr as usize + page_size::get();
(offset + GUEST_MEMORY_ALIGNMENT - usable % GUEST_MEMORY_ALIGNMENT)
% GUEST_MEMORY_ALIGNMENT
}
None => 0,
};
// SAFETY: `head <= reserve_size - total_size`, so the result is inside
// the reservation.
let base = unsafe { addr.byte_add(head) };

// protect the guard pages and the unused ends of the reservation
// SAFETY: Both ranges lie inside the reservation `mmap` owns. The first
// ends at the usable start, the second ends at `addr + reserve_size`.
// Both start page aligned because `addr` and `offset` are.
#[cfg(not(miri))]
{
let res = unsafe { mprotect(mmap.base, page_size::get(), PROT_NONE) };
let page = page_size::get();
let res = unsafe { mprotect(addr, head + page, PROT_NONE) };
if res != 0 {
return Err(SharedMemoryError::MprotectFailed(
Error::last_os_error().raw_os_error(),
));
}
let res = unsafe {
mprotect(
(mmap.base as *const u8).add(total_size - page_size::get()) as *mut c_void,
page_size::get(),
base.byte_add(total_size - page),
reserve_size - head - total_size + page,
PROT_NONE,
)
};
Expand All @@ -778,7 +867,11 @@ impl ExclusiveSharedMemory {
// type does have Send and Sync manually impl'd, the Arc
// is not pointless as the lint suggests.
#[allow(clippy::arc_with_non_send_sync)]
region: Arc::new(HostMapping { mmap }),
region: Arc::new(HostMapping {
_reservation: mmap,
base: base as *mut u8,
len: total_size,
}),
})
}

Expand Down Expand Up @@ -1759,7 +1852,11 @@ impl ReadonlySharedMemory {
// anonymous reservation, so no extra `mprotect` is needed.

#[allow(clippy::arc_with_non_send_sync)]
Ok(Arc::new(HostMapping { mmap: reservation }))
Ok(Arc::new(HostMapping {
base: reservation.base as *mut u8,
len: total_size,
_reservation: reservation,
}))
}

/// Windows: reserve `[guard][blob][guard]` as one
Expand Down Expand Up @@ -1954,6 +2051,46 @@ mod tests {
assert!(hshm.fill(0, mem_size, 1).is_err());
}

#[test]
#[cfg(all(target_os = "linux", not(miri)))]
fn new_for_gpa_matches_gpa_offset() {
use super::GUEST_MEMORY_ALIGNMENT;

let page = page_size::get();
let pid = std::process::id().try_into().unwrap();
for offset in [
0,
page,
GUEST_MEMORY_ALIGNMENT - 4 * page,
GUEST_MEMORY_ALIGNMENT - page,
] {
for size in [
GUEST_MEMORY_ALIGNMENT,
3 * GUEST_MEMORY_ALIGNMENT + page,
4 * GUEST_MEMORY_ALIGNMENT,
] {
let gpa = (1u64 << 36) + offset as u64;
let mut eshm = ExclusiveSharedMemory::new_for_gpa(size, gpa, false).unwrap();
let base = eshm.base_addr();
assert_eq!(base % GUEST_MEMORY_ALIGNMENT, offset, "size {size:#x}");
assert_eq!(eshm.mem_size(), size);
eshm.as_mut_slice()[0] = 1;
eshm.as_mut_slice()[size - 1] = 2;
let maps = proc_maps::get_process_maps(pid).unwrap();
let guarded = |addr: usize| {
maps.iter().any(|m| {
(m.start()..m.start() + m.size()).contains(&addr)
&& !m.is_read()
&& !m.is_write()
&& !m.is_exec()
})
};
assert!(guarded(base - 1));
assert!(guarded(base + size));
}
}
}

/// Verify that `bounds_check!` rejects offset + size combinations that
/// would overflow `usize`.
#[test]
Expand Down
Loading
Loading