Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

### Added
* ARM64 guests support CPUs without LSE atomics when built with `-C target-feature=-lse`.
* Add `SandboxBuilder::memory_reset_strategy` and sandbox configuration support for tuning snapshot restore and subsequent guest call performance.
* 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
Expand Down
11 changes: 11 additions & 0 deletions src/hyperlight_host/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
use hyperlight_common::virtq::VirtqError;
use thiserror::Error;

use crate::MemoryResetStrategy;
use crate::hypervisor::hyperlight_vm::HyperlightVmError;
#[cfg(target_os = "windows")]
use crate::hypervisor::wrappers::HandleWrapper;
Expand Down Expand Up @@ -151,6 +152,15 @@ pub enum HyperlightError {
#[error("No Hypervisor was found for Sandbox")]
NoHypervisorFound(),

/// The selected backend cannot use the requested memory reset strategy.
#[error("Memory reset strategy {strategy:?} is not supported by {hypervisor}")]
UnsupportedMemoryResetStrategy {
/// Requested strategy.
strategy: MemoryResetStrategy,
/// Selected backend.
hypervisor: &'static str,
},

/// Restore_state called with no valid snapshot
#[error("Restore_state called with no valid snapshot")]
NoMemorySnapshot,
Expand Down Expand Up @@ -362,6 +372,7 @@ impl HyperlightError {
| HyperlightError::UnexpectedNoOfArguments(_, _)
| HyperlightError::UnexpectedParameterValueType(_, _)
| HyperlightError::UnexpectedReturnValueType(_, _)
| HyperlightError::UnsupportedMemoryResetStrategy { .. }
| HyperlightError::UnrecoverableSandbox
| HyperlightError::UTF8StringConversionFailure(_)
| HyperlightError::SharedMemory(_) => false,
Expand Down
60 changes: 60 additions & 0 deletions src/hyperlight_host/src/hypervisor/virtual_machine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::sync::OnceLock;

use tracing::{Span, instrument};

use crate::MemoryResetStrategy;
#[cfg(gdb)]
use crate::hypervisor::gdb::DebugError;
use crate::hypervisor::regs::{
Expand Down Expand Up @@ -109,6 +110,44 @@ pub(crate) enum HypervisorType {
Hvf,
}

impl HypervisorType {
pub(crate) fn resolve_memory_reset_strategy(
self,
requested: MemoryResetStrategy,
) -> crate::Result<MemoryResetStrategy> {
use MemoryResetStrategy::*;

let (default, supported, hypervisor): (
MemoryResetStrategy,
&[MemoryResetStrategy],
&'static str,
) = match self {
#[cfg(kvm)]
Self::Kvm => (Discard, &[ZeroInPlace, Discard], "Kvm"),
#[cfg(mshv3)]
Self::Mshv => (ZeroInPlace, &[ZeroInPlace], "Mshv"),
#[cfg(target_os = "windows")]
Self::Whp => (Discard, &[ZeroInPlace, Discard], "Whp"),
#[cfg(hvf)]
Self::Hvf => (ZeroInPlace, &[ZeroInPlace], "Hvf"),
};

let strategy = match requested {
PlatformDefault => default,
strategy => strategy,
};
if !supported.contains(&strategy) {
let error = crate::HyperlightError::UnsupportedMemoryResetStrategy {
strategy: requested,
hypervisor,
};
tracing::error!(%error);
return Err(error);
}
Ok(strategy)
}
}

/// Minimum XSAVE buffer size: 512 bytes legacy region + 64 bytes header.
/// Only used by WHP which uses compacted XSAVE format and needs to
/// validate buffer size before accessing XCOMP_BV.
Expand Down Expand Up @@ -656,6 +695,27 @@ pub(crate) fn hyperv_msr_reset_indices(

#[cfg(test)]
mod tests {
#[test]
#[cfg(any(mshv3, hvf))]
fn rejects_unsupported_memory_reset_strategy() {
use super::HypervisorType;
use crate::MemoryResetStrategy;

#[cfg(mshv3)]
let hypervisor = HypervisorType::Mshv;
#[cfg(hvf)]
let hypervisor = HypervisorType::Hvf;
let error = hypervisor
.resolve_memory_reset_strategy(MemoryResetStrategy::Discard)
.unwrap_err();
assert!(matches!(
error,
crate::HyperlightError::UnsupportedMemoryResetStrategy {
strategy: MemoryResetStrategy::Discard,
..
}
));
}

#[test]
// TODO: add support for testing on WHP
Expand Down
2 changes: 2 additions & 0 deletions src/hyperlight_host/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ pub(crate) mod testing;
pub use error::HyperlightError;
/// The re-export for the `is_hypervisor_present` type
pub use hypervisor::virtual_machine::is_hypervisor_present;
/// How writable guest memory is cleared during snapshot restore.
pub use sandbox::MemoryResetStrategy;
/// Deprecated name for [`Sandbox`].
#[allow(deprecated)]
pub use sandbox::MultiUseSandbox;
Expand Down
71 changes: 26 additions & 45 deletions src/hyperlight_host/src/mem/mgr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ pub(crate) struct SandboxMemoryManager<S: SharedMemory> {
pub(crate) abort_buffer: Vec<u8>,
/// 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
/// on each `snapshot` call; on restore we inherit the
/// restored snapshot's own generation number so the guest-visible
/// counter tracks which snapshot the sandbox is a clone of.
pub(crate) snapshot_count: u64,
Expand Down Expand Up @@ -562,7 +562,7 @@ impl SandboxMemoryManager<ExclusiveSharedMemory> {
let mut mgr = Self::new(layout, shared_mem, scratch_mem, next_action);
mgr.original_entrypoint = s.original_entrypoint();
// Inherit the snapshot's generation number for the same
// reason `restore_snapshot` does: the guest-visible counter
// reason snapshot restore does: the guest-visible counter
// reflects "which snapshot is the sandbox currently a clone
// of", not "how many snapshots this partition has taken".
mgr.snapshot_count = s.snapshot_generation();
Expand Down Expand Up @@ -933,22 +933,15 @@ impl SandboxMemoryManager<HostSharedMemory> {
self.original_entrypoint = snapshot.original_entrypoint();
}

/// 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.
/// Install same-size captured memory and fresh transport ownership.
pub(crate) fn install_captured_snapshot(
&mut self,
snapshot: &Snapshot,
) -> Result<(
SnapshotMemoryBacking<GuestSharedMemory>,
Option<GuestSharedMemory>,
)> {
) -> Result<SnapshotMemoryBacking<GuestSharedMemory>> {
if snapshot.layout().get_scratch_size() != self.scratch_mem.mem_size() {
let requests = self.guest_requests()?;
let memory = self.restore_snapshot(snapshot)?;
self.set_guest_requests(requests)?;
return Ok(memory);
return Err(new_error!(
"captured snapshot scratch size does not match the allocation"
));
}

let virtq = snapshot
Expand All @@ -965,7 +958,7 @@ impl SandboxMemoryManager<HostSharedMemory> {
self.zero_freed_scratch(used_scratch_end)?;
self.restore_virtq(virtq)?;

Ok((gsnapshot, None))
Ok(gsnapshot)
}

/// The end of the scratch the guest has allocated: its allocator's next
Expand Down Expand Up @@ -1001,17 +994,12 @@ impl SandboxMemoryManager<HostSharedMemory> {
Ok(())
}

/// Restore base memory after the caller checks snapshot compatibility.
pub(crate) fn restore_snapshot(
/// Transport consumers stay detached until `finish_restore` rebuilds them.
pub(crate) fn begin_restore(
&mut self,
snapshot: &Snapshot,
) -> Result<(
SnapshotMemoryBacking<GuestSharedMemory>,
Option<GuestSharedMemory>,
)> {
let virtq = snapshot.virtq();

if virtq.is_none() && matches!(snapshot.next_action(), NextAction::Call(_)) {
) -> Result<SnapshotMemoryBacking<GuestSharedMemory>> {
if snapshot.virtq().is_none() && matches!(snapshot.next_action(), NextAction::Call(_)) {
return Err(new_error!(
"running snapshot has no canonical transport state"
));
Expand All @@ -1020,26 +1008,19 @@ impl SandboxMemoryManager<HostSharedMemory> {
self.g2h_consumer = None;
self.h2g_consumer = None;

let gsnapshot = self.replace_snapshot_memory(snapshot)?;
let new_scratch_size = snapshot.layout().get_scratch_size();
let gscratch = if new_scratch_size == self.scratch_mem.mem_size() {
// zero_or_replace picks the fastest zeroing strategy for
// 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 (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
// own the reference to the guest side of the old scratch
// mapping, so it won't actually be deallocated until it
// has been unmapped from the VM.
self.scratch_mem = hscratch;
Some(gscratch)
};
self.replace_snapshot_memory(snapshot)
}

/// Scratch must be cleared and mapped at the snapshot's size.
pub(crate) fn finish_restore(&mut self, snapshot: &Snapshot) -> Result<()> {
if snapshot.layout().get_scratch_size() != self.scratch_mem.mem_size() {
return Err(new_error!(
"snapshot scratch size does not match the allocation"
));
}
self.apply_snapshot_metadata(snapshot);
self.update_scratch_bookkeeping()?;
if let Some(virtq) = virtq {
if let Some(virtq) = snapshot.virtq() {
self.restore_virtq(virtq)?;
} else if matches!(snapshot.next_action(), NextAction::Initialise(_)) {
self.scratch_mem.copy_from_slice(
Expand All @@ -1048,7 +1029,7 @@ impl SandboxMemoryManager<HostSharedMemory> {
)?;
self.create_virtq_consumers()?;
}
Ok((gsnapshot, gscratch))
Ok(())
}

#[inline]
Expand All @@ -1060,7 +1041,7 @@ impl SandboxMemoryManager<HostSharedMemory> {
.map_err(From::from)
}

fn guest_requests(&self) -> Result<[u64; 2]> {
pub(crate) fn guest_requests(&self) -> Result<[u64; 2]> {
let scratch_size = self.scratch_mem.mem_size();
let mut values = [0; 2];
for (value, offset) in values.iter_mut().zip(GUEST_REQUEST_OFFSETS) {
Expand All @@ -1071,7 +1052,7 @@ impl SandboxMemoryManager<HostSharedMemory> {
Ok(values)
}

fn set_guest_requests(&mut self, values: [u64; 2]) -> Result<()> {
pub(crate) fn set_guest_requests(&mut self, values: [u64; 2]) -> Result<()> {
for (value, offset) in values.into_iter().zip(GUEST_REQUEST_OFFSETS) {
self.update_scratch_bookkeeping_item(offset, value)?;
}
Expand Down
Loading
Loading