diff --git a/CHANGELOG.md b/CHANGELOG.md index d521a1565..8795e7f14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/hyperlight_host/src/error.rs b/src/hyperlight_host/src/error.rs index 4ecf47b8e..9ba9fa9d4 100644 --- a/src/hyperlight_host/src/error.rs +++ b/src/hyperlight_host/src/error.rs @@ -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; @@ -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, @@ -362,6 +372,7 @@ impl HyperlightError { | HyperlightError::UnexpectedNoOfArguments(_, _) | HyperlightError::UnexpectedParameterValueType(_, _) | HyperlightError::UnexpectedReturnValueType(_, _) + | HyperlightError::UnsupportedMemoryResetStrategy { .. } | HyperlightError::UnrecoverableSandbox | HyperlightError::UTF8StringConversionFailure(_) | HyperlightError::SharedMemory(_) => false, diff --git a/src/hyperlight_host/src/hypervisor/virtual_machine/mod.rs b/src/hyperlight_host/src/hypervisor/virtual_machine/mod.rs index 47c7db573..3216d58ed 100644 --- a/src/hyperlight_host/src/hypervisor/virtual_machine/mod.rs +++ b/src/hyperlight_host/src/hypervisor/virtual_machine/mod.rs @@ -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::{ @@ -109,6 +110,44 @@ pub(crate) enum HypervisorType { Hvf, } +impl HypervisorType { + pub(crate) fn resolve_memory_reset_strategy( + self, + requested: MemoryResetStrategy, + ) -> crate::Result { + 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. @@ -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 diff --git a/src/hyperlight_host/src/lib.rs b/src/hyperlight_host/src/lib.rs index e97d6c4d2..89589624a 100644 --- a/src/hyperlight_host/src/lib.rs +++ b/src/hyperlight_host/src/lib.rs @@ -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; diff --git a/src/hyperlight_host/src/mem/mgr.rs b/src/hyperlight_host/src/mem/mgr.rs index 959aac180..44943f578 100644 --- a/src/hyperlight_host/src/mem/mgr.rs +++ b/src/hyperlight_host/src/mem/mgr.rs @@ -374,7 +374,7 @@ pub(crate) struct SandboxMemoryManager { pub(crate) abort_buffer: Vec, /// 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, @@ -562,7 +562,7 @@ impl SandboxMemoryManager { 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(); @@ -933,22 +933,15 @@ impl SandboxMemoryManager { 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, - Option, - )> { + ) -> Result> { 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 @@ -965,7 +958,7 @@ impl SandboxMemoryManager { 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 @@ -1001,17 +994,12 @@ impl SandboxMemoryManager { 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, - Option, - )> { - let virtq = snapshot.virtq(); - - if virtq.is_none() && matches!(snapshot.next_action(), NextAction::Call(_)) { + ) -> Result> { + if snapshot.virtq().is_none() && matches!(snapshot.next_action(), NextAction::Call(_)) { return Err(new_error!( "running snapshot has no canonical transport state" )); @@ -1020,26 +1008,19 @@ impl SandboxMemoryManager { 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( @@ -1048,7 +1029,7 @@ impl SandboxMemoryManager { )?; self.create_virtq_consumers()?; } - Ok((gsnapshot, gscratch)) + Ok(()) } #[inline] @@ -1060,7 +1041,7 @@ impl SandboxMemoryManager { .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) { @@ -1071,7 +1052,7 @@ impl SandboxMemoryManager { 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)?; } diff --git a/src/hyperlight_host/src/mem/shared_mem.rs b/src/hyperlight_host/src/mem/shared_mem.rs index 02b8d6cf8..589512636 100644 --- a/src/hyperlight_host/src/mem/shared_mem.rs +++ b/src/hyperlight_host/src/mem/shared_mem.rs @@ -30,8 +30,6 @@ use windows::core::PCSTR; use super::memory_region::{ HostGuestMemoryRegion, MemoryRegion, MemoryRegionFlags, MemoryRegionKind, MemoryRegionType, }; -#[cfg(kvm)] -use crate::hypervisor::virtual_machine::{HypervisorType, get_available_hypervisor}; use crate::log_then_return; type Result = core::result::Result; @@ -99,6 +97,11 @@ pub enum SharedMemoryError { #[error("mprotect failed with os error {0:?}")] MprotectFailed(Option), + /// A request to discard anonymous memory failed. + #[cfg(kvm)] + #[error("madvise failed: {0}")] + MadviseFailed(std::io::Error), + /// A Windows virtual memory API call failed #[cfg(target_os = "windows")] #[error("Windows API Error Result {0:?}")] @@ -1509,54 +1512,27 @@ impl HostSharedMemory { } impl HostSharedMemory { - /// Reset this memory region to all-zeros, choosing the fastest - /// strategy for the current platform and hypervisor configuration. - /// - /// When the running hypervisor is KVM, uses `MADV_DONTNEED` for - /// lazy zeroing. Otherwise, uses `fill(0)`. - /// - /// On Windows, zeroing via `fill(0)` is prohibitively expensive - /// for large regions (e.g. 448 MiB scratch). Instead, the - /// mapping is replaced with a fresh demand-zero allocation. - /// Returns `Some(GuestSharedMemory)` when the mapping was - /// replaced (the caller must update the VM mapping), or `None` - /// when zeroed in place. - /// - // TODO: Find the break-even point between zero-in-place and - // replace for each hypervisor and use a size-based heuristic - // instead of a compile-time platform check. - pub(crate) fn zero_or_replace(&mut self) -> Result> { - #[cfg(target_os = "windows")] - { - let new_mem = ExclusiveSharedMemory::new(self.mem_size())?; - let (hscratch, gscratch) = new_mem.build(); - *self = hscratch; - Ok(Some(gscratch)) - } - #[cfg(not(target_os = "windows"))] - { - self.with_exclusivity(|e| { - // TODO: Find a similar lazy zeroing approach that works on MSHV. - // (See Note [Keeping mappings in sync between userspace and the guest]) - #[cfg(kvm)] - if matches!(get_available_hypervisor(), Some(HypervisorType::Kvm)) { - // SAFETY: `with_exclusivity` holds the write lock on this private anonymous - // mapping. KVM MMU notifiers make the guest also read zeros after discard. - let ret = unsafe { - libc::madvise( - e.region.ptr() as *mut libc::c_void, - e.region.size(), - libc::MADV_DONTNEED, - ) - }; - if ret == 0 { - return; - } - } - e.as_mut_slice().fill(0); - })?; - Ok(None) - } + pub(crate) fn zero_in_place(&mut self) -> Result<()> { + self.with_exclusivity(|e| e.as_mut_slice().fill(0)) + } + + /// The caller must use KVM, whose MMU notifiers invalidate guest mappings. + #[cfg(kvm)] + pub(crate) fn discard_pages(&mut self) -> Result<()> { + self.with_exclusivity(|e| { + // SAFETY: The write lock covers this private anonymous mapping. + let ret = unsafe { + libc::madvise( + e.region.ptr() as *mut libc::c_void, + e.region.size(), + libc::MADV_DONTNEED, + ) + }; + if ret != 0 { + return Err(SharedMemoryError::MadviseFailed(Error::last_os_error())); + } + Ok(()) + })? } } @@ -1954,6 +1930,40 @@ mod tests { assert!(hshm.fill(0, mem_size, 1).is_err()); } + #[test] + #[cfg(not(miri))] + fn in_place_resets_clear_full_region() { + let resets: &[fn(&mut HostSharedMemory) -> Result<()>] = &[ + HostSharedMemory::zero_in_place, + #[cfg(kvm)] + HostSharedMemory::discard_pages, + ]; + for reset in resets { + for size in [page_size::get(), 100 * page_size::get()] { + for pattern in [0x55, 0xaa] { + let memory = ExclusiveSharedMemory::new(size).unwrap(); + let (mut host, mut guest) = memory.build(); + host.with_exclusivity(|e| e.as_mut_slice().fill(pattern)) + .unwrap(); + let base = host.base_addr(); + + reset(&mut host).unwrap(); + + assert!( + host.with_exclusivity(|e| e.as_slice().iter().all(|&b| b == 0)) + .unwrap() + ); + assert_eq!(host.base_addr(), base); + assert!( + guest + .with_exclusivity(|e| e.as_slice().iter().all(|&b| b == 0)) + .unwrap() + ); + } + } + } + } + /// Verify that `bounds_check!` rejects offset + size combinations that /// would overflow `usize`. #[test] diff --git a/src/hyperlight_host/src/sandbox/builder.rs b/src/hyperlight_host/src/sandbox/builder.rs index def83caa2..39896b47f 100644 --- a/src/hyperlight_host/src/sandbox/builder.rs +++ b/src/hyperlight_host/src/sandbox/builder.rs @@ -11,13 +11,13 @@ use tracing_core::LevelFilter; use crate::func::HostFunction; use crate::mem::memory_region::MemoryRegion; -use crate::sandbox::SandboxConfiguration; #[cfg(gdb)] use crate::sandbox::config::DebugInfo; #[cfg(target_arch = "x86_64")] use crate::sandbox::config::GuestMsrError; use crate::sandbox::host_funcs::FunctionEntry; use crate::sandbox::snapshot::Snapshot; +use crate::sandbox::{MemoryResetStrategy, SandboxConfiguration}; use crate::{GuestBinary, HostFunctions, Result, Sandbox, UninitializedSandbox}; /// What a [`SandboxBuilder`] builds the sandbox from. @@ -283,6 +283,42 @@ impl SandboxBuilder { self.cfg.get_scratch_size() } + /// Chooses how snapshot restore clears scratch to zero. + /// + /// `ZeroInPlace` writes zeros to existing pages and keeps their mappings. + /// It can be faster for small sandboxes, but clearing a large + /// [`scratch_size`](Self::scratch_size) can slow restores. + /// + /// `Discard` releases pages on KVM and replaces the allocation on WHP. + /// It can speed up restores for larger sandboxes, but may slow subsequent + /// guest calls. Accessing the memory can trigger faults that allocate + /// physical pages and map them into the VM. + /// + /// We recommend benchmarking the strategies supported on your platform + /// with your workload, measuring both restore time and subsequent guest calls. + /// + /// | Platform / hypervisor | Supported strategies | `PlatformDefault` | + /// | --- | --- | --- | + /// | Linux / KVM | `ZeroInPlace`, `Discard` | `Discard` | + /// | Linux / MSHV | `ZeroInPlace` | `ZeroInPlace` | + /// | Windows / WHP | `ZeroInPlace`, `Discard` | `Discard` | + /// | macOS / HVF | `ZeroInPlace` | `ZeroInPlace` | + /// + /// On KVM, `PlatformDefault` falls back to `ZeroInPlace` if discard fails. + /// + /// Applies to equal-size restores. Size changes and recreation always allocate + /// fresh scratch. Unsupported choices fail at [`Self::build`] with + /// [`crate::HyperlightError::UnsupportedMemoryResetStrategy`]. + pub fn memory_reset_strategy(mut self, strategy: MemoryResetStrategy) -> Self { + self.cfg.set_memory_reset_strategy(strategy); + self + } + + /// Returns the requested strategy, including an unresolved `PlatformDefault`. + pub fn get_memory_reset_strategy(&self) -> MemoryResetStrategy { + self.cfg.get_memory_reset_strategy() + } + /// Set the G2H virtqueue descriptor count. /// /// See [`SandboxConfiguration::set_g2h_queue_size`] for normalization. diff --git a/src/hyperlight_host/src/sandbox/config.rs b/src/hyperlight_host/src/sandbox/config.rs index 0f70e2f34..215c4e444 100644 --- a/src/hyperlight_host/src/sandbox/config.rs +++ b/src/hyperlight_host/src/sandbox/config.rs @@ -32,6 +32,33 @@ pub enum GuestMsrError { }, } +/// Tunes snapshot restore performance by choosing how scratch is cleared. +/// +/// All strategies clear scratch to zero. Performance depends on sandbox +/// size, workload, and backend. +/// +/// The strategy controls equal-size restores. +/// Size changes, construction, and recreation allocate fresh scratch. +/// Unsupported strategies and reset failures return errors. +#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] +#[repr(u8)] +pub enum MemoryResetStrategy { + /// Use the backend's default mechanism. + /// + /// KVM falls back to in-place zeroing if discard fails. + #[default] + PlatformDefault, + /// Overwrite the existing scratch allocation with zeros. + ZeroInPlace, + /// Discard scratch contents using OS discard or allocation replacement. + /// + /// KVM uses `MADV_DONTNEED`. Windows replaces the allocation and remaps + /// guest memory. MSHV and HVF do not support this strategy. + /// Page allocation and mapping costs can be deferred until the guest + /// accesses the memory. + Discard, +} + /// The complete set of configuration needed to create a Sandbox #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(C)] @@ -64,6 +91,7 @@ pub struct SandboxConfiguration { interrupt_vcpu_sigrtmin_offset: u8, /// How much writable memory to offer the guest scratch_size: usize, + memory_reset_strategy: MemoryResetStrategy, /// The maximum log level enabled for guest code execution. /// /// If unset, the level is determined from the `RUST_LOG` environment @@ -139,6 +167,7 @@ impl SandboxConfiguration { ) -> Self { Self { scratch_size, + memory_reset_strategy: MemoryResetStrategy::default(), max_guest_log_level: Self::MAX_GUEST_LOG_LEVEL_UNSET, g2h_queue_size: Self::DEFAULT_G2H_QUEUE_SIZE, h2g_queue_size: Self::DEFAULT_H2G_QUEUE_SIZE, @@ -281,6 +310,21 @@ impl SandboxConfiguration { self.scratch_size = scratch_size; } + /// Tunes snapshot restore performance with [`MemoryResetStrategy`]. + /// + /// The strategy controls equal-size restores. + /// The destination keeps this setting across resizing and recreation. + /// Unsupported choices fail during sandbox initialization with + /// [`crate::HyperlightError::UnsupportedMemoryResetStrategy`]. + pub fn set_memory_reset_strategy(&mut self, strategy: MemoryResetStrategy) { + self.memory_reset_strategy = strategy; + } + + /// Returns the requested strategy, including an unresolved `PlatformDefault`. + pub fn get_memory_reset_strategy(&self) -> MemoryResetStrategy { + self.memory_reset_strategy + } + /// Sets the maximum log level for guest code execution. /// /// If not set, the level is determined from the `RUST_LOG` environment diff --git a/src/hyperlight_host/src/sandbox/initialized.rs b/src/hyperlight_host/src/sandbox/initialized.rs index f9018ed67..9714eccc4 100644 --- a/src/hyperlight_host/src/sandbox/initialized.rs +++ b/src/hyperlight_host/src/sandbox/initialized.rs @@ -21,14 +21,19 @@ use super::snapshot::{Snapshot, SnapshotOptions}; use crate::func::{ParameterTuple, SupportedReturnType}; use crate::hypervisor::InterruptHandle; use crate::hypervisor::hyperlight_vm::{HyperlightVm, HyperlightVmError}; +#[cfg(kvm)] +use crate::hypervisor::virtual_machine::HypervisorType; +use crate::hypervisor::virtual_machine::get_available_hypervisor; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; use crate::mem::mgr::SandboxMemoryManager; -use crate::mem::shared_mem::{HostSharedMemory, SharedMemory as _}; +#[cfg(kvm)] +use crate::mem::shared_mem::SharedMemoryError; +use crate::mem::shared_mem::{ExclusiveSharedMemory, HostSharedMemory, SharedMemory as _}; use crate::metrics::{ METRIC_GUEST_ERROR, METRIC_GUEST_ERROR_LABEL_CODE, maybe_time_and_emit_guest_call, }; use crate::sandbox::snapshot::SnapshotMemoryBacking; -use crate::{HyperlightError, Result, log_then_return}; +use crate::{HyperlightError, MemoryResetStrategy, Result, log_then_return}; /// The lifecycle state of a [`Sandbox`]. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -314,12 +319,12 @@ impl Sandbox { let page_size = u32::try_from(page_size::get())? as usize; - #[cfg(target_os = "linux")] - crate::signal_handlers::setup_signal_handlers(&config)?; - let mut vm = set_up_hypervisor_partition(gshm, &config, stack_top_gva, page_size, load_info)?; + #[cfg(target_os = "linux")] + crate::signal_handlers::setup_signal_handlers(&config)?; + let seed = { let mut rng = rand::rng(); rng.random::() @@ -550,25 +555,10 @@ impl Sandbox { self.snapshot = None; return Err(error); } - let (snapshot_mem, scratch_mem) = match self.mem_mgr.install_captured_snapshot(&snapshot) { - Ok(memory) => memory, - Err(error) => { - self.status = SandboxStatus::Unrecoverable; - self.snapshot = None; - return Err(error); - } - }; - if let Err(error) = self.vm.update_snapshot_mapping(snapshot_mem) { + if let Err(error) = self.install_captured_snapshot(&snapshot) { self.status = SandboxStatus::Unrecoverable; self.snapshot = None; - return Err(HyperlightVmError::UpdateRegion(error).into()); - } - if let Some(scratch_mem) = scratch_mem - && let Err(error) = self.vm.update_scratch_mapping(scratch_mem) - { - self.status = SandboxStatus::Unrecoverable; - self.snapshot = None; - return Err(HyperlightVmError::UpdateRegion(error).into()); + return Err(error); } if let Err(error) = self.vm.apply_sregs(snapshot.root_pt_gpa(), &sregs) { self.status = SandboxStatus::Poisoned; @@ -580,6 +570,20 @@ impl Sandbox { Ok(snapshot) } + fn install_captured_snapshot(&mut self, snapshot: &Snapshot) -> Result<()> { + if snapshot.layout().get_scratch_size() == self.mem_mgr.scratch_mem.mem_size() { + let memory = self.mem_mgr.install_captured_snapshot(snapshot)?; + self.vm + .update_snapshot_mapping(memory) + .map_err(HyperlightVmError::UpdateRegion)?; + Ok(()) + } else { + let requests = self.mem_mgr.guest_requests()?; + self.restore_memory_and_mappings(snapshot)?; + self.mem_mgr.set_guest_requests(requests) + } + } + fn remove_dynamic_mappings(&mut self) -> Result<()> { let regions = self.vm.get_mapped_regions().cloned().collect::>(); for region in ®ions { @@ -591,18 +595,59 @@ impl Sandbox { } fn restore_memory_and_mappings(&mut self, snapshot: &Snapshot) -> Result<()> { - let (snapshot_mem, scratch_mem) = self.mem_mgr.restore_snapshot(snapshot)?; + let snapshot_mem = self.mem_mgr.begin_restore(snapshot)?; self.vm .update_snapshot_mapping(snapshot_mem) .map_err(HyperlightVmError::UpdateRegion)?; - if let Some(scratch_mem) = scratch_mem { - self.vm - .update_scratch_mapping(scratch_mem) - .map_err(HyperlightVmError::UpdateRegion)?; + self.reset_scratch(snapshot.layout().get_scratch_size())?; + self.mem_mgr.finish_restore(snapshot) + } + + fn reset_scratch(&mut self, size: usize) -> Result<()> { + let hypervisor = get_available_hypervisor().ok_or(HyperlightError::NoHypervisorFound())?; + let requested = self.config.get_memory_reset_strategy(); + let strategy = hypervisor.resolve_memory_reset_strategy(requested)?; + + if size != self.mem_mgr.scratch_mem.mem_size() { + return self.replace_scratch(size); + } + + match strategy { + MemoryResetStrategy::ZeroInPlace => { + self.mem_mgr.scratch_mem.zero_in_place()?; + } + #[cfg(kvm)] + MemoryResetStrategy::Discard if hypervisor == HypervisorType::Kvm => { + match self.mem_mgr.scratch_mem.discard_pages() { + Err(SharedMemoryError::MadviseFailed(error)) + if requested == MemoryResetStrategy::PlatformDefault => + { + tracing::warn!(%error, "KVM scratch discard failed, zeroing in place"); + self.mem_mgr.scratch_mem.zero_in_place()?; + } + result => result?, + } + } + MemoryResetStrategy::Discard => self.replace_scratch(size)?, + MemoryResetStrategy::PlatformDefault => { + let error = crate::new_error!("Backend {hypervisor:?} resolved to PlatformDefault"); + tracing::error!(%error); + return Err(error); + } } Ok(()) } + fn replace_scratch(&mut self, size: usize) -> Result<()> { + let memory = ExclusiveSharedMemory::new(size)?; + let (host, guest) = memory.build(); + self.vm + .update_scratch_mapping(guest) + .map_err(HyperlightVmError::UpdateRegion)?; + self.mem_mgr.scratch_mem = host; + Ok(()) + } + /// Restores the sandbox's memory to a previously captured snapshot state. /// /// The sandbox's registered host functions must be a superset of @@ -1437,8 +1482,8 @@ mod tests { use crate::sandbox::SandboxConfiguration; use crate::sandbox::snapshot::{Snapshot, SnapshotOptions}; use crate::{ - GuestBinary, HyperlightError, Result, Sandbox, SandboxBuilder, SandboxStatus, - UninitializedSandbox, + GuestBinary, HyperlightError, MemoryResetStrategy, Result, Sandbox, SandboxBuilder, + SandboxStatus, UninitializedSandbox, }; #[test] @@ -1460,6 +1505,18 @@ mod tests { SnapshotOptions::default().scratch_size(scratch_size) } + fn free_scratch_page(sandbox: &Sandbox) -> (u64, usize) { + let gpa = sandbox.mem_mgr.layout.get_transport_arena().base_addr() + - hyperlight_common::vmem::PAGE_SIZE as u64; + assert!( + gpa >= sandbox.mem_mgr.first_free_scratch_gpa() + + sandbox.mem_mgr.scratch_allocated_bytes().unwrap() + ); + let base = + hyperlight_common::layout::scratch_base_gpa(sandbox.mem_mgr.scratch_mem.mem_size()); + (gpa, usize::try_from(gpa - base).unwrap()) + } + fn assert_virtq_attached(sbox: &Sandbox) { assert!(sbox.mem_mgr.g2h_consumer.is_some()); assert!(sbox.mem_mgr.h2g_consumer.is_some()); @@ -1893,6 +1950,7 @@ mod tests { .scratch_size(8 << 20) .build() .unwrap(); + let scratch_base = sandbox.mem_mgr.scratch_mem.base_addr(); let fault_plan = sandbox .vm .inject_vm_faults([VmOperation::Map(MemoryRegionType::Scratch)]); @@ -1904,6 +1962,7 @@ mod tests { assert!(matches!(error, HyperlightError::HyperlightVmError(_))); assert!(fault_plan.is_consumed()); + assert_eq!(sandbox.mem_mgr.scratch_mem.base_addr(), scratch_base); assert_eq!(sandbox.status(), SandboxStatus::Unrecoverable); } @@ -2125,6 +2184,209 @@ mod tests { assert_eq!(res, 0); } + #[test] + fn memory_reset_strategy_controls_restores() { + use crate::hypervisor::virtual_machine::{HypervisorType, get_available_hypervisor}; + + fn check_restore( + sandbox: &mut Sandbox, + snapshot: &Arc, + strategy: MemoryResetStrategy, + ) { + sandbox.call::("AddToStatic", 5i32).unwrap(); + sandbox + .call::<()>("AllocAndWritePattern", 32u64 << 10) + .unwrap(); + let base = sandbox.mem_mgr.scratch_mem.base_addr(); + let size = sandbox.mem_mgr.scratch_mem.mem_size(); + let (marker_gpa, marker_offset) = free_scratch_page(sandbox); + sandbox + .mem_mgr + .scratch_mem + .write(marker_offset, u64::MAX) + .unwrap(); + let bytes = sandbox + .call::>("ReadMappedBuffer", (marker_gpa, 8u64, true)) + .unwrap(); + assert_eq!(bytes, [0xff; 8]); + + sandbox.restore(snapshot.clone()).unwrap(); + + let same_size = size == snapshot.layout().get_scratch_size(); + if same_size + && (strategy == MemoryResetStrategy::ZeroInPlace || !cfg!(target_os = "windows")) + { + assert_eq!(sandbox.mem_mgr.scratch_mem.base_addr(), base); + } else { + assert_ne!(sandbox.mem_mgr.scratch_mem.base_addr(), base); + } + let (restored_gpa, restored_offset) = free_scratch_page(sandbox); + assert_eq!(restored_gpa, marker_gpa); + let bytes = sandbox + .call::>("ReadMappedBuffer", (marker_gpa, 8u64, true)) + .unwrap(); + assert_eq!(bytes, [0; 8]); + assert_eq!( + sandbox + .mem_mgr + .scratch_mem + .read::(restored_offset) + .unwrap(), + 0 + ); + assert_eq!(sandbox.call::("GetStatic", ()).unwrap(), 0); + assert_eq!(sandbox.config.get_memory_reset_strategy(), strategy); + } + + let supports_discard = match get_available_hypervisor().unwrap() { + #[cfg(kvm)] + HypervisorType::Kvm => true, + #[cfg(mshv3)] + HypervisorType::Mshv => false, + #[cfg(target_os = "windows")] + HypervisorType::Whp => true, + #[cfg(hvf)] + HypervisorType::Hvf => false, + }; + for strategy in [ + MemoryResetStrategy::PlatformDefault, + MemoryResetStrategy::ZeroInPlace, + MemoryResetStrategy::Discard, + ] { + let result = SandboxBuilder::from_file(simple_guest_as_pathbuf()) + .scratch_size(2 << 20) + .memory_reset_strategy(strategy) + .build(); + if strategy == MemoryResetStrategy::Discard && !supports_discard { + assert!(matches!( + result, + Err(HyperlightError::UnsupportedMemoryResetStrategy { + strategy: MemoryResetStrategy::Discard, + .. + }) + )); + let snapshot = SandboxBuilder::from_file(simple_guest_as_pathbuf()) + .build() + .unwrap() + .snapshot() + .unwrap(); + assert!(matches!( + SandboxBuilder::from_snapshot(snapshot) + .memory_reset_strategy(strategy) + .build(), + Err(HyperlightError::UnsupportedMemoryResetStrategy { + strategy: MemoryResetStrategy::Discard, + .. + }) + )); + continue; + } + let mut sandbox = result.unwrap(); + let small = sandbox.snapshot().unwrap(); + check_restore(&mut sandbox, &small, strategy); + + let large = sandbox.snapshot_with_options(&scratch(4 << 20)).unwrap(); + check_restore(&mut sandbox, &large, strategy); + check_restore(&mut sandbox, &small, strategy); + check_restore(&mut sandbox, &small, strategy); + check_restore(&mut sandbox, &large, strategy); + + sandbox.recreate(large.clone()).unwrap(); + check_restore(&mut sandbox, &large, strategy); + drop(sandbox); + + let destination_strategy = + if strategy == MemoryResetStrategy::ZeroInPlace && supports_discard { + MemoryResetStrategy::Discard + } else { + MemoryResetStrategy::ZeroInPlace + }; + let mut destination = SandboxBuilder::from_snapshot(small.clone()) + .memory_reset_strategy(destination_strategy) + .build() + .unwrap(); + check_restore(&mut destination, &small, destination_strategy); + } + } + + #[test] + #[cfg(kvm)] + fn locked_scratch_preserves_default_reset_fallback() { + use crate::hypervisor::virtual_machine::{HypervisorType, get_available_hypervisor}; + use crate::mem::shared_mem::SharedMemoryError; + + if !matches!(get_available_hypervisor(), Some(HypervisorType::Kvm)) { + return; + } + for strategy in [ + MemoryResetStrategy::PlatformDefault, + MemoryResetStrategy::ZeroInPlace, + MemoryResetStrategy::Discard, + ] { + let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) + .scratch_size(2 << 20) + .memory_reset_strategy(strategy) + .build() + .unwrap(); + let snapshot = sandbox.snapshot().unwrap(); + let (gpa, offset) = free_scratch_page(&sandbox); + sandbox.mem_mgr.scratch_mem.write(offset, u64::MAX).unwrap(); + let address = (sandbox.mem_mgr.scratch_mem.base_addr() + offset) as *const libc::c_void; + let length = page_size::get(); + // SAFETY: The page lies within the sandbox's live scratch allocation. + if unsafe { libc::mlock(address, length) } != 0 { + let error = std::io::Error::last_os_error(); + if matches!( + error.raw_os_error(), + Some(libc::EPERM | libc::ENOMEM | libc::EAGAIN) + ) { + tracing::warn!(%error, "Skipping locked scratch test: mlock unavailable"); + return; + } + panic!("mlock failed: {error}"); + } + + let result = sandbox.restore(snapshot); + // SAFETY: Equal-size KVM resets keep this scratch allocation mapped. + assert_eq!(unsafe { libc::munlock(address, length) }, 0); + + if strategy == MemoryResetStrategy::Discard { + assert!(matches!( + result, + Err(HyperlightError::SharedMemory(SharedMemoryError::MadviseFailed(error))) + if error.raw_os_error() == Some(libc::EINVAL) + )); + assert_eq!(sandbox.status(), SandboxStatus::Unrecoverable); + } else { + result.unwrap(); + assert_eq!(sandbox.status(), SandboxStatus::Ready); + assert_eq!( + sandbox + .call::>("ReadMappedBuffer", (gpa, 8u64, true)) + .unwrap(), + [0; 8] + ); + assert_eq!(sandbox.mem_mgr.scratch_mem.read::(offset).unwrap(), 0); + } + } + } + + #[test] + fn missing_hypervisor_preserves_vm_creation_error() { + use crate::hypervisor::hyperlight_vm::{CreateHyperlightVmError, HyperlightVmError}; + use crate::hypervisor::virtual_machine::get_available_hypervisor; + + if get_available_hypervisor().is_some() { + return; + } + assert!(matches!( + SandboxBuilder::from_file(simple_guest_as_pathbuf()).build(), + Err(HyperlightError::HyperlightVmError( + HyperlightVmError::Create(CreateHyperlightVmError::NoHypervisorFound) + )) + )); + } + #[test] fn snapshots_cache_until_guest_state_changes() { let mut sandbox = SandboxBuilder::from_file(simple_guest_as_pathbuf()) diff --git a/src/hyperlight_host/src/sandbox/mod.rs b/src/hyperlight_host/src/sandbox/mod.rs index cdc4c920d..1c555b42d 100644 --- a/src/hyperlight_host/src/sandbox/mod.rs +++ b/src/hyperlight_host/src/sandbox/mod.rs @@ -39,8 +39,8 @@ pub(crate) mod trace; /// Trait used by the macros to paper over the differences between hyperlight and hyperlight-wasm pub use callable::Callable; -/// Re-export for `SandboxConfiguration` type -pub use config::SandboxConfiguration; +/// Configuration and memory reset settings for a sandbox. +pub use config::{MemoryResetStrategy, SandboxConfiguration}; /// Re-export for the deprecated `MultiUseSandbox` name #[allow(deprecated)] pub use initialized::MultiUseSandbox; diff --git a/src/hyperlight_host/src/sandbox/snapshot/mod.rs b/src/hyperlight_host/src/sandbox/snapshot/mod.rs index f8aa29e07..dfd2167c3 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/mod.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/mod.rs @@ -1512,7 +1512,9 @@ mod tests { if mapping.virt_base == base + PAGE_SIZE as u64 ))); - manager.restore_snapshot(&snapshot).unwrap(); + manager.begin_restore(&snapshot).unwrap(); + manager.scratch_mem.zero_in_place().unwrap(); + manager.finish_restore(&snapshot).unwrap(); manager .with_guest_memory(&[], |memory| { for (root, gva, expected) in [ @@ -1635,7 +1637,9 @@ mod tests { .unwrap(); // Restore snapshot A - mgr.restore_snapshot(&snapshot_a).unwrap(); + mgr.begin_restore(&snapshot_a).unwrap(); + mgr.scratch_mem.zero_in_place().unwrap(); + mgr.finish_restore(&snapshot_a).unwrap(); let mut restored = vec![0u8; pattern_a.len()]; mgr.shared_mem .read_snapshot_gpa(SandboxMemoryLayout::BASE_ADDRESS as u64, &mut restored) @@ -1643,7 +1647,9 @@ mod tests { assert_eq!(restored, pattern_a); // Restore snapshot B - mgr.restore_snapshot(&snapshot_b).unwrap(); + mgr.begin_restore(&snapshot_b).unwrap(); + mgr.scratch_mem.zero_in_place().unwrap(); + mgr.finish_restore(&snapshot_b).unwrap(); restored.fill(0); mgr.shared_mem .read_snapshot_gpa(SandboxMemoryLayout::BASE_ADDRESS as u64, &mut restored) diff --git a/src/hyperlight_host/src/sandbox/uninitialized.rs b/src/hyperlight_host/src/sandbox/uninitialized.rs index efca1944c..193b45dcd 100644 --- a/src/hyperlight_host/src/sandbox/uninitialized.rs +++ b/src/hyperlight_host/src/sandbox/uninitialized.rs @@ -82,8 +82,8 @@ impl GuestBinary { impl UninitializedSandbox { // Creates a new uninitialized sandbox from a pre-built snapshot. // Note that since memory configuration is part of the snapshot the only configuration - // that can be changed (from the original snapshot) is the configuration defines the behaviour of - // `InterruptHandler` on Linux. + // that can be changed (from the original snapshot) is the memory reset strategy and the + // configuration that defines the behaviour of `InterruptHandler` on Linux. // // This is ok for now as this is not a public function fn from_snapshot(snapshot: Arc, cfg: Option) -> Result { diff --git a/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs b/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs index 38f28c3de..a8b275391 100644 --- a/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs +++ b/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs @@ -6,6 +6,7 @@ use tracing::{Span, instrument}; use super::SandboxConfiguration; use super::snapshot::NextAction; use crate::hypervisor::hyperlight_vm::{HyperlightVm, HyperlightVmError}; +use crate::hypervisor::virtual_machine::get_available_hypervisor; use crate::mem::exe::LoadInfo; use crate::mem::mgr::SandboxMemoryManager; use crate::mem::shared_mem::GuestSharedMemory; @@ -88,11 +89,15 @@ pub(super) fn initialize_sandbox(u_sbox: UninitializedSandbox) -> Result, - #[cfg_attr(target_os = "windows", allow(unused_variables))] config: &SandboxConfiguration, + config: &SandboxConfiguration, stack_top_gva: u64, page_size: usize, _load_info: LoadInfo, ) -> Result { + if let Some(hypervisor) = get_available_hypervisor() { + hypervisor.resolve_memory_reset_strategy(config.get_memory_reset_strategy())?; + } + // Create gdb thread if gdb is enabled and the configuration is provided #[cfg(gdb)] let gdb_conn = if let Some(DebugInfo { port }) = config.get_guest_debug_info() {