Skip to content
Merged
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 Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6384,6 +6384,7 @@ dependencies = [
"fs-err",
"hypervisor_resources",
"test_with_tracing",
"virt_kvm",
"virt_mshv",
"virt_whp",
"vm_resource",
Expand Down
3 changes: 2 additions & 1 deletion openvmm/openvmm_hypervisors/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ rust-version.workspace = true
virt_mshv = ["dep:virt_mshv"]

# Enable building with KVM support.
virt_kvm = []
virt_kvm = ["dep:virt_kvm"]

# Enable building with WHP support.
virt_whp = ["dep:virt_whp"]
Expand All @@ -26,6 +26,7 @@ hypervisor_resources.workspace = true
vm_resource.workspace = true

[target.'cfg(target_os = "linux")'.dependencies]
virt_kvm = { workspace = true, optional = true }
virt_mshv = { workspace = true, optional = true }

[target.'cfg(windows)'.dependencies]
Expand Down
57 changes: 57 additions & 0 deletions openvmm/openvmm_hypervisors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,63 @@ pub fn mshv_snp_available() -> bool {
}
}

/// Returns whether KVM supports the nested-state ioctls on this machine.
pub fn kvm_nested_state_available() -> bool {
#[cfg(all(
target_os = "linux",
feature = "virt_kvm",
guest_is_native,
guest_arch = "x86_64"
))]
{
virt_kvm::is_nested_state_available()
}
#[cfg(not(all(
target_os = "linux",
feature = "virt_kvm",
guest_is_native,
guest_arch = "x86_64"
)))]
{
false
}
}

/// Returns whether MSHV supports partition scrub on this machine.
/// TODO: Remove when dom0 Kernel ships with this IOCTL
pub fn mshv_partition_scrub_available() -> bool {
#[cfg(all(target_os = "linux", feature = "virt_mshv", guest_is_native))]
{
virt_mshv::is_partition_scrub_available()
}
#[cfg(not(all(target_os = "linux", feature = "virt_mshv", guest_is_native)))]
{
false
}
}

/// Returns whether WHP supports nested partition reset on this machine.
pub fn whp_nested_reset_available() -> bool {
#[cfg(all(
target_os = "windows",
feature = "virt_whp",
guest_is_native,
guest_arch = "x86_64"
))]
{
virt_whp::is_nested_reset_available()
}
#[cfg(not(all(
target_os = "windows",
feature = "virt_whp",
guest_is_native,
guest_arch = "x86_64"
)))]
{
false
}
}

#[expect(clippy::allow_attributes, reason = "lots of conditions")]
#[allow(dead_code)]
pub(crate) fn parse_bool_param(key: &str, val: &str) -> anyhow::Result<bool> {
Expand Down
4 changes: 4 additions & 0 deletions petri/petri_artifacts_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ pub mod capabilities {
/// Support for nested virtualization
pub const NESTED_VIRT: &str = "nested_virt";

/// Support for resetting a partition with nested virtualization enabled.
pub const NESTED_RESET: &str = "nested_reset";

/// All capability names known to petri, including those defined by
/// tests.
pub const KNOWN_CAPABILITIES: &[&str] = &[
VPCI,
WINDOWS_PARTITION_RESET,
NESTED_VIRT,
NESTED_RESET,
"test_disk",
"edu_initiator",
"ivshmem_target",
Expand Down
15 changes: 15 additions & 0 deletions petri/src/requirements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ pub struct HostContext {
pub execution_environment: ExecutionEnvironment,
/// Hypervisor backend that OpenVMM will select on this host.
pub openvmm_hypervisor: Option<OpenVmmHypervisor>,
/// Whether the selected OpenVMM backend supports nested partition reset.
pub nested_reset_supported: bool,
}

impl HostContext {
Expand Down Expand Up @@ -153,6 +155,13 @@ impl HostContext {
_ => None,
};

let nested_reset_supported = match openvmm_hypervisor {
Some(OpenVmmHypervisor::Kvm) => openvmm_hypervisors::kvm_nested_state_available(),
Some(OpenVmmHypervisor::Mshv) => openvmm_hypervisors::mshv_partition_scrub_available(),
Some(OpenVmmHypervisor::Whp) => openvmm_hypervisors::whp_nested_reset_available(),
_ => false,
};

let vm_host_info = cfg_select! {
windows => crate::vm::hyperv::powershell::run_get_vm_host()
.await
Expand Down Expand Up @@ -186,6 +195,7 @@ impl HostContext {
ExecutionEnvironment::Baremetal
},
openvmm_hypervisor,
nested_reset_supported,
}
}
}
Expand Down Expand Up @@ -337,6 +347,10 @@ fn available_capabilities(context: &HostContext, vmm: VmmType) -> BTreeSet<&'sta
capabilities.insert(capabilities::NESTED_VIRT);
}

if vmm == VmmType::OpenVmm && context.nested_reset_supported {
capabilities.insert(capabilities::NESTED_RESET);
}

match std::env::var("PETRI_CAPABILITIES") {
Ok(env_capabilities) => {
for capability in env_capabilities.split(',').map(str::trim) {
Expand Down Expand Up @@ -391,6 +405,7 @@ mod tests {
vendor: Vendor::Intel,
execution_environment: ExecutionEnvironment::Baremetal,
openvmm_hypervisor: Some(openvmm_hypervisor),
nested_reset_supported: false,
}
}

Expand Down
1 change: 1 addition & 0 deletions petri/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,7 @@ mod tests {
vendor: Vendor::Intel,
execution_environment: ExecutionEnvironment::Baremetal,
openvmm_hypervisor: hypervisor,
nested_reset_supported: false,
}
}

Expand Down
31 changes: 26 additions & 5 deletions petri/src/vm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2698,8 +2698,25 @@ impl<T: PetriVmmBackend> PetriVm<T> {
&self,
client: &PipetteClient,
env: BTreeMap<String, String>,
) -> anyhow::Result<()> {
self.run_nested_test_with_suffix(client, env, "").await
}

/// Run the nested test with separate results for each invocation.
///
/// Use a unique suffix when running the same nested test more than once.
pub async fn run_nested_test_with_suffix(
&self,
client: &PipetteClient,
env: BTreeMap<String, String>,
suffix: &str,
) -> anyhow::Result<()> {
let nested_test = self.nested_test.as_ref().context("no nested test")?;
let results_dir = if self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
NESTED_RESULTS_DIR.to_owned()
} else {
format!("{NESTED_RESULTS_DIR}{suffix}")
};

let test_binary_path =
if let Some(test_content_dir) = self.guest_shares.get(NESTED_CONTENT_TAG) {
Expand Down Expand Up @@ -2730,7 +2747,7 @@ impl<T: PetriVmmBackend> PetriVm<T> {
)
.env(
TEST_OUTPUT_PATH,
self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into(), NESTED_RESULTS_DIR.into()]),
self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into(), results_dir.clone()]),
)
.stdout(crate::pipette::process::Stdio::piped())
.stderr(crate::pipette::process::Stdio::piped());
Expand All @@ -2740,7 +2757,9 @@ impl<T: PetriVmmBackend> PetriVm<T> {
}

if self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
cmd.env(PETRI_NESTED_TEST_PARENT, &self.name);
// Keep shared results under the normal results directory so the
// host collects them, but give each invocation its own test name.
cmd.env(PETRI_NESTED_TEST_PARENT, format!("{}{suffix}", self.name));
}

if let Ok(v) = std::env::var(PETRI_REMOTE_ARTIFACTS) {
Expand All @@ -2755,7 +2774,9 @@ impl<T: PetriVmmBackend> PetriVm<T> {
.spawn(
"log_nested",
crate::log_task(
self.resources.log_source.log_file("stdout")?,
self.resources
.log_source
.log_file(&format!("stdout{suffix}"))?,
child.stdout.take().unwrap(),
"nested stdout",
),
Expand All @@ -2768,7 +2789,7 @@ impl<T: PetriVmmBackend> PetriVm<T> {
if !self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
let test_results_dir = self.agent_disk_path(&[
NESTED_TEST_CONTENT_DIR.into(),
NESTED_RESULTS_DIR.into(),
results_dir,
nested_test.test_name.replace("::", "__"),
]);

Expand All @@ -2779,7 +2800,7 @@ impl<T: PetriVmmBackend> PetriVm<T> {
let mut output = self
.resources
.log_source
.create_attachment_no_prefix(&file)?;
.create_attachment_no_prefix(&format!("{suffix}{file}"))?;
output.write_all(&data)?;
}
}
Expand Down
41 changes: 41 additions & 0 deletions vm/kvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ mod ioctl {
ioctl_read!(kvm_get_xcrs, KVMIO, 0xa6, kvm_xcrs);
#[cfg(target_arch = "x86_64")]
ioctl_write_ptr!(kvm_set_xcrs, KVMIO, 0xa7, kvm_xcrs);
#[cfg(target_arch = "x86_64")]
ioctl_write_ptr!(kvm_set_nested_state, KVMIO, 0xbf, kvm_nested_state);
ioctl_write_ptr!(kvm_get_reg, KVMIO, 0xab, kvm_one_reg);
ioctl_write_ptr!(kvm_set_reg, KVMIO, 0xac, kvm_one_reg);
#[cfg(target_arch = "aarch64")]
Expand Down Expand Up @@ -313,6 +315,9 @@ pub enum Error {
GetXsave(#[source] nix::Error),
#[error("SetXsave")]
SetXsave(#[source] nix::Error),
#[cfg(target_arch = "x86_64")]
#[error("SetNestedState")]
SetNestedState(#[source] nix::Error),
#[error("GetDebugRegs")]
GetDebugRegs(#[source] nix::Error),
#[error("SetDebugRegs")]
Expand Down Expand Up @@ -1271,6 +1276,29 @@ pub enum RoutingEntry {

pub struct Processor<'a>(&'a Partition, u32);

#[cfg(target_arch = "x86_64")]
// Architectural reset discards any prior L2 state. Only the CPU vendor
// determines the inactive VMX/SVM header; no VMCS/VMCB payload survives.
fn nested_state_at_reset(vmx: bool) -> kvm_nested_state {
Comment thread
russell-islam marked this conversation as resolved.
Resolved
let mut state = kvm_nested_state {
size: size_of::<kvm_nested_state>() as u32,
..Default::default()
};
if vmx {
state.format = KVM_STATE_NESTED_FORMAT_VMX as u16;
// No VMXON region or current VMCS exists after reset.
state.hdr.vmx = kvm_vmx_nested_state_hdr {
vmxon_pa: u64::MAX,
vmcs12_pa: u64::MAX,
..Default::default()
};
} else {
state.format = KVM_STATE_NESTED_FORMAT_SVM as u16;
state.flags = KVM_STATE_NESTED_GIF_SET as u16;
}
state
}

impl<'a> Processor<'a> {
pub fn enable_synic(&self) -> Result<()> {
// TODO: We are not checking KVM_CAP_ENABLE_CAP_VM first.
Expand Down Expand Up @@ -1567,6 +1595,19 @@ impl<'a> Processor<'a> {
Ok(())
}

/// Leaves nested guest mode and resets VMX or SVM state.
#[cfg(target_arch = "x86_64")]
pub fn reset_nested_state(&self, vmx: bool) -> Result<()> {
let state = nested_state_at_reset(vmx);
// SAFETY: The reset state advertises only the initialized header's
// size and has no nested guest payload for KVM to read.
unsafe {
ioctl::kvm_set_nested_state(self.get().vcpu.as_raw_fd(), &state)
.map_err(Error::SetNestedState)?;
}
Ok(())
}

#[cfg(target_arch = "x86_64")]
pub fn set_debug_regs(&self, regs: &DebugRegisters) -> Result<()> {
let data = kvm_debugregs {
Expand Down
2 changes: 2 additions & 0 deletions vmm_core/virt/src/x86/vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1957,6 +1957,8 @@ impl StateElement<X86PartitionCapabilities, X86VpInfo> for SynicEventFlagsPage {
}

/// Opaque nested-virtualization state blob for save/restore.
///
/// An empty blob denotes architectural reset, not a serialized hardware state.
#[derive(Debug, Clone, Default, PartialEq, Eq, Protobuf, Inspect)]
#[mesh(package = "virt.x86")]
#[inspect(skip)]
Expand Down
11 changes: 9 additions & 2 deletions vmm_core/virt_kvm/src/arch/x86_64/vp_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,14 @@ impl AccessVpState for KvmVpStateAccess<'_, '_> {
Err(KvmError::NotSupported)
}

fn set_nested_state(&mut self, _value: &vp::NestedState) -> Result<(), Self::Error> {
Err(KvmError::NotSupported)
fn set_nested_state(&mut self, value: &vp::NestedState) -> Result<(), Self::Error> {
if !value.data.is_empty() {
return Err(KvmError::NestedStateRestoreUnsupported);
}
// Empty is NestedState::at_reset's sentinel. There is no saved payload
// to restore; synthesize the vendor's architectural reset state.
self.kvm()
.reset_nested_state(self.vp.partition.caps.vendor.is_intel_compatible())?;
Ok(())
}
}
24 changes: 24 additions & 0 deletions vmm_core/virt_kvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ cfg_select! {
pub use arch::Kvm;
pub use memory::MemoryError;

#[cfg(guest_arch = "x86_64")]
use anyhow::Context as _;
use guestmem::GuestMemory;
use inspect::Inspect;
use memory::KvmMemoryBackingMode;
Expand All @@ -44,6 +46,25 @@ pub fn is_available() -> Result<bool, KvmError> {
}
}

/// Returns whether KVM supports the nested-state ioctls on this machine.
#[cfg(guest_arch = "x86_64")]
pub fn is_nested_state_available() -> bool {
let probe = || -> anyhow::Result<bool> {
let kvm = kvm::Kvm::new().context("open KVM for nested-state probe")?;
Ok(kvm
.check_extension(kvm::KVM_CAP_NESTED_STATE)
.context("query KVM_CAP_NESTED_STATE")?
> 0)
};
match probe() {
Ok(supported) => supported,
Err(err) => {
tracing::warn!(error = &*err, "KVM nested-state probe failed");
false
}
}
}

use arch::KvmVpInner;
use std::sync::atomic::Ordering;
use virt::VpIndex;
Expand Down Expand Up @@ -89,6 +110,9 @@ pub enum KvmError {
#[error("nested virtualization was requested but the host does not support it")]
NestedVirtUnsupported,
#[cfg(guest_arch = "x86_64")]
#[error("restoring saved nested state is not supported; only reset is implemented")]
NestedStateRestoreUnsupported,
#[cfg(guest_arch = "x86_64")]
#[error("unsupported CPU vendor")]
UnsupportedCpuVendor,
#[cfg(guest_arch = "x86_64")]
Expand Down
Loading
Loading