Skip to content

Commit aa5dbc1

Browse files
committed
openvmm: support snapshotting UEFI and nested-virtualization VMs
Two gaps prevented a successful snapshot save/restore of a KVM-backed VM. UEFI restore: the UEFI device's logger and watchdog platform resolvers were only registered in the LoadMode::Uefi arm. A restore sets the load mode to None (firmware is not reloaded) while still instantiating the UEFI device from the chipset config, so restoring a UEFI VM failed with "no resolver for uefi_logger:platform". Register those resolvers whenever the UEFI device is present, independent of the load mode. Nested virtualization: the KVM backend's nested_state()/set_nested_state() returned NotSupported, so saving or restoring a partition with nested virtualization enabled failed: the vCPU's nested VMX/SVM state (VMCS12 and the per-vCPU nested control fields) was never captured, and a nested guest running an L2 at save time could not be resumed. Add the KVM_GET_NESTED_STATE / KVM_SET_NESTED_STATE ioctls to the kvm crate; get_nested_state() sizes the buffer from KVM_CHECK_EXTENSION(KVM_CAP_NESTED_STATE) and returns an empty blob when the host lacks the capability, and set_nested_state() pushes the opaque blob back. NestedState save/restore is already ordered last in the per-VP state list, after registers, MSRs, and CPUID, which the kernel validates the blob against on restore. An empty blob takes the reset path, so a guest-initiated reset is not aborted. Note the nested-state support in the snapshots guide and point save-snapshot's help at the file-backed-memory requirement.
1 parent 3081fd6 commit aa5dbc1

5 files changed

Lines changed: 125 additions & 16 deletions

File tree

‎Guide/src/user_guide/openvmm/snapshots.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ These are stored as three files in a snapshot directory:
2020
| `state.bin` | Serialized device state |
2121
| `memory.bin` | Memory backing file |
2222

23+
```admonish note
24+
On the KVM backend, the saved per-VP state includes nested-virtualization
25+
(VMX/SVM) state, so a VM that is itself running a nested hypervisor can be
26+
snapshotted and resumed.
27+
```
28+
2329
## Prerequisites
2430

2531
Snapshots require **file-backed guest memory**. Pass `file=<PATH>` in the

‎openvmm/openvmm_core/src/worker/dispatch.rs‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1381,19 +1381,22 @@ impl InitializedVm {
13811381

13821382
#[cfg_attr(not(guest_arch = "x86_64"), expect(unused_mut))]
13831383
let mut deps_hyperv_firmware_pcat = None;
1384+
// The UEFI device's platform resolvers (logger, watchdog) are needed
1385+
// whenever the device is present, including on a snapshot restore where
1386+
// the load mode is None because firmware is not reloaded.
1387+
if cfg.chipset_devices.iter().any(|d| d.name == "uefi") {
1388+
use emuplat::uefi::*;
1389+
resolver.add_resolver(emuplat::firmware::MeshLoggerResolver::new(
1390+
cfg.firmware_event_send.clone(),
1391+
));
1392+
resolver.add_async_resolver(OpenvmmUefiWatchdogPlatformResolver::new(
1393+
partition.clone(),
1394+
halt_vps.clone(),
1395+
));
1396+
}
1397+
13841398
match &cfg.load_mode {
1385-
LoadMode::Uefi { .. } => {
1386-
use emuplat::uefi::*;
1387-
// Register the platform-specific resolvers used by the UEFI
1388-
// device.
1389-
resolver.add_resolver(emuplat::firmware::MeshLoggerResolver::new(
1390-
cfg.firmware_event_send.clone(),
1391-
));
1392-
resolver.add_async_resolver(OpenvmmUefiWatchdogPlatformResolver::new(
1393-
partition.clone(),
1394-
halt_vps.clone(),
1395-
));
1396-
}
1399+
LoadMode::Uefi { .. } => {}
13971400
#[cfg(guest_arch = "x86_64")]
13981401
LoadMode::Pcat {
13991402
firmware,

‎openvmm/openvmm_entry/src/repl.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,8 @@ enum InteractiveCommand {
105105
#[clap(visible_alias = "r")]
106106
Resume,
107107

108-
/// Save a snapshot to a directory (requires --memory-backing-file).
108+
/// Save a snapshot to a directory (requires file-backed guest memory,
109+
/// i.e. `file=` in --memory).
109110
#[clap(visible_alias = "snap")]
110111
SaveSnapshot {
111112
/// Directory to write the snapshot to.

‎vm/kvm/src/lib.rs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ mod ioctl {
9191
ioctl_read!(kvm_get_xcrs, KVMIO, 0xa6, kvm_xcrs);
9292
#[cfg(target_arch = "x86_64")]
9393
ioctl_write_ptr!(kvm_set_xcrs, KVMIO, 0xa7, kvm_xcrs);
94+
#[cfg(target_arch = "x86_64")]
95+
ioctl_readwrite!(kvm_get_nested_state, KVMIO, 0xbe, kvm_nested_state);
96+
#[cfg(target_arch = "x86_64")]
97+
ioctl_write_ptr!(kvm_set_nested_state, KVMIO, 0xbf, kvm_nested_state);
9498
ioctl_write_ptr!(kvm_get_reg, KVMIO, 0xab, kvm_one_reg);
9599
ioctl_write_ptr!(kvm_set_reg, KVMIO, 0xac, kvm_one_reg);
96100
#[cfg(target_arch = "aarch64")]
@@ -191,6 +195,14 @@ pub enum Error {
191195
SetDeviceAttr(#[source] nix::Error),
192196
#[error("CheckExtension")]
193197
CheckExtension(#[source] nix::Error),
198+
#[error("GetNestedState")]
199+
GetNestedState(#[source] nix::Error),
200+
#[error("SetNestedState")]
201+
SetNestedState(#[source] nix::Error),
202+
#[error("nested state buffer too small: {0} bytes")]
203+
NestedStateTooSmall(usize),
204+
#[error("nested state size {size} out of range for a {len}-byte buffer")]
205+
NestedStateBadSize { size: usize, len: usize },
194206
}
195207

196208
type Result<T, E = Error> = std::result::Result<T, E>;
@@ -1104,6 +1116,86 @@ impl<'a> Processor<'a> {
11041116
Ok(data.xcrs[0].value)
11051117
}
11061118

1119+
/// Reads the vCPU's nested-virtualization state (VMCS12/VMCB plus the
1120+
/// per-vCPU nested control fields) as an opaque, size-prefixed blob.
1121+
///
1122+
/// Returns an empty vector when the host kernel does not support
1123+
/// `KVM_CAP_NESTED_STATE`, so callers can treat "no nested state" as a blob
1124+
/// of length zero.
1125+
#[cfg(target_arch = "x86_64")]
1126+
pub fn get_nested_state(&self) -> Result<Vec<u8>> {
1127+
// KVM_CHECK_EXTENSION returns the size in bytes of the largest
1128+
// nested-state buffer the kernel may produce, or <= 0 when the
1129+
// capability is unavailable. It must be issued on the VM fd; the vcpu
1130+
// fd does not handle this ioctl and rejects it with EINVAL.
1131+
// SAFETY: Calling IOCTL as documented, with no special requirements.
1132+
let max = unsafe {
1133+
ioctl::kvm_check_extension(self.0.vm.as_raw_fd(), KVM_CAP_NESTED_STATE as i32)
1134+
.map_err(Error::CheckExtension)?
1135+
};
1136+
if max <= 0 {
1137+
return Ok(Vec::new());
1138+
}
1139+
let max = max as usize;
1140+
if max < size_of::<kvm_nested_state>() {
1141+
return Err(Error::NestedStateTooSmall(max));
1142+
}
1143+
1144+
let mut buf = vec![0u8; max];
1145+
// The kernel reads the caller-provided `.size` field to bound how much
1146+
// it writes, then overwrites it with the actual length on return.
1147+
// SAFETY: `buf` is at least `size_of::<kvm_nested_state>()` bytes and is
1148+
// valid for writes for `max` bytes.
1149+
unsafe {
1150+
let state = buf.as_mut_ptr().cast::<kvm_nested_state>();
1151+
(*state).size = max as u32;
1152+
ioctl::kvm_get_nested_state(self.get().vcpu.as_raw_fd(), state)
1153+
.map_err(Error::GetNestedState)?;
1154+
let used = (*state).size as usize;
1155+
buf.truncate(used);
1156+
}
1157+
Ok(buf)
1158+
}
1159+
1160+
/// Restores nested-virtualization state previously captured by
1161+
/// [`Processor::get_nested_state`].
1162+
///
1163+
/// The vCPU's CPUID, MSRs, and control registers (CR4.VMXE,
1164+
/// IA32_FEATURE_CONTROL) must already be restored, since the kernel
1165+
/// validates the blob against them.
1166+
#[cfg(target_arch = "x86_64")]
1167+
pub fn set_nested_state(&self, data: &[u8]) -> Result<()> {
1168+
// An empty blob is the "no nested state" value get_nested_state returns
1169+
// on a host without KVM_CAP_NESTED_STATE; there is nothing to restore.
1170+
if data.is_empty() {
1171+
return Ok(());
1172+
}
1173+
if data.len() < size_of::<kvm_nested_state>() {
1174+
return Err(Error::NestedStateTooSmall(data.len()));
1175+
}
1176+
// The kernel reads `kvm_nested_state.size` bytes from the buffer. Reject
1177+
// a blob whose embedded size is smaller than the header or larger than
1178+
// the slice, so a malformed snapshot cannot drive an out-of-bounds read.
1179+
// SAFETY: `data` holds at least a `kvm_nested_state` header.
1180+
let size = unsafe { (*data.as_ptr().cast::<kvm_nested_state>()).size } as usize;
1181+
if !(size_of::<kvm_nested_state>()..=data.len()).contains(&size) {
1182+
return Err(Error::NestedStateBadSize {
1183+
size,
1184+
len: data.len(),
1185+
});
1186+
}
1187+
// SAFETY: the kernel reads `size` bytes starting at `data`, and
1188+
// `size <= data.len()`.
1189+
unsafe {
1190+
ioctl::kvm_set_nested_state(
1191+
self.get().vcpu.as_raw_fd(),
1192+
data.as_ptr().cast::<kvm_nested_state>(),
1193+
)
1194+
.map_err(Error::SetNestedState)?;
1195+
}
1196+
Ok(())
1197+
}
1198+
11071199
pub fn set_mp_state(&self, state: u32) -> Result<()> {
11081200
let state = kvm_mp_state { mp_state: state };
11091201
// TODO: We are not checking KVM_CAP_MP_STATE first.

‎vmm_core/virt_kvm/src/arch/x86_64/vp_state.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -655,10 +655,17 @@ impl AccessVpState for KvmVpStateAccess<'_, '_> {
655655
}
656656

657657
fn nested_state(&mut self) -> Result<vp::NestedState, Self::Error> {
658-
Err(KvmError::NotSupported)
658+
// Empty only on a host without KVM_CAP_NESTED_STATE; otherwise the
659+
// kernel returns the current nested state, which is a minimal header
660+
// when no L2 is active.
661+
let data = self.kvm().get_nested_state()?;
662+
Ok(vp::NestedState { data })
659663
}
660664

661-
fn set_nested_state(&mut self, _value: &vp::NestedState) -> Result<(), Self::Error> {
662-
Err(KvmError::NotSupported)
665+
fn set_nested_state(&mut self, value: &vp::NestedState) -> Result<(), Self::Error> {
666+
// An empty blob (the at-reset value, or a host without the capability)
667+
// is a no-op in set_nested_state.
668+
self.kvm().set_nested_state(&value.data)?;
669+
Ok(())
663670
}
664671
}

0 commit comments

Comments
 (0)