The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(hypervisor): save and restore x86 KVM vCPU and VM state (#2963)
lfld2877ee49e71a80b
diff --git a/make/coverage.mk b/make/coverage.mkindex 1654e8d17..772cd8649 100644--- a/make/coverage.mk+++ b/make/coverage.mk@@ -77,7 +77,7 @@ codecov: coverage\:lcovcoverage\:vmm\:kvm: _ensure-kvm@cargo llvm-cov nextest --no-report --no-tests=fail --profile ci --retries 0 --status-level pass \-p boxlite-hypervisor -p boxlite-vmm --lib --run-ignored only --test-threads=1 \- -E 'test(vm::tests::) | test(tests::kvm::)'+ -E '(package(boxlite-hypervisor) & test(/^kvm::/)) | (package(boxlite-vmm) & (test(/^vm::tests::/) | test(tests::kvm::)))'@cargo llvm-cov report $(COVERAGE_REPORT_ARGS) --lcov --output-path target/coverage/lcov.info# Add the real-kernel boots of VMM_KERNEL to the same profiles, listed the same way.diff --git a/make/test.mk b/make/test.mkindex bb76658d9..313ed5c41 100644--- a/make/test.mk+++ b/make/test.mk@@ -307,7 +307,7 @@ _ensure-kvm:test\:integration\:vmm\:kvm: _ensure-kvm@cargo test -p boxlite-hypervisor -p boxlite-vmm --lib --no-run@status=0; \- timeout 60s cargo test -p boxlite-hypervisor --lib kvm::vm::tests:: -- --ignored --test-threads=1 || status=1; \+ timeout 60s cargo test -p boxlite-hypervisor --lib kvm:: -- --ignored --test-threads=1 || status=1; \timeout 60s cargo test -p boxlite-vmm --lib -- --ignored --test-threads=1 vm::tests:: tests::kvm:: || status=1; \exit $$statusdiff --git a/src/hypervisor/README.md b/src/hypervisor/README.mdindex a8476309c..02ef191be 100644--- a/src/hypervisor/README.md+++ b/src/hypervisor/README.md@@ -23,7 +23,7 @@ machine layout and device emulation belong to `boxlite-vmm`.| `arm64` | `Arm64Vcpu`, `Arm64BootRegisters` and `CpuOnResult`: the arm64 boot registers and the VMM's answer to `CPU_ON` || `hvf` | macOS arm64: the VM and its in-kernel GICv3, memory, vCPU execution and kicks, with `syndrome` decoding exceptions and emulating trapped system registers, and `psci` serving PSCI 0.2 || `x86` | Boot configuration and Linux x86_64 VM/vCPU state images with Serde encoding |-| `kvm` | x86_64 VM creation, memory slots, registers, CPUID/MSRs, execution, kicks and pending-I/O completion; arm64 follows |+| `kvm` | x86_64 VM creation, memory slots, registers, CPUID/MSRs, execution, kicks, pending-I/O completion and paused-state transfer; arm64 follows || `whp` / `whp::emulator` | WHP operations and x86 instruction decoding for memory-access exits (reserved for M10) |Three boundaries decide placement when a case is ambiguous: KVM memory-slot@@ -68,32 +68,67 @@ MSRs are explicit index/value writes. A short KVM write is an error identifyingthe first rejected MSR, never a successful partially configured CPU. Host featurediscovery is a ceiling, not permission to add unsupported instructions.-These three methods form the x86_64 extension traits `X86Vm`+These boot methods form the x86_64 extension traits `X86Vm`(`supported_cpuid`) and `X86Vcpu` (`set_cpu_features`, `set_boot_registers`),which `KvmVm` and `KvmVcpu` implement, so the VMM's vCPU workers and its mockbackend use one interface. On arm64, `Arm64Vcpu` sets MPIDR_EL1 (`set_mpidr`) andthe entry PC, X0 and PSTATE (`set_boot_registers`).-## Linux x86_64 snapshot state+## Linux x86_64 paused state-`X86VmState` and `X86VcpuState` are owned KVM state images for the same host-and KVM environment. Their wire format is unstable. Both implement Serde for-`postcard::to_allocvec` and `postcard::from_bytes`. Callers own the snapshot-container, RAM, device state and persistence.+`X86Vm::save_state` and `X86Vcpu::save_state` capture owned images on Linux+x86_64 KVM. Restore requires the same host and KVM environment, with compatible+guest CPU policy and VM configuration. The images have a non-stable ABI and+implement Serde for Postcard encoding. The VMM owns RAM, devices, machine-state+assembly, and persistence.-| Image | State |+| Image | Captured state || --- | --- |-| `X86VmState` | PIC master/slave and IOAPIC as `X86IrqchipState`, optional PIT, and KVM clock |-| `X86VcpuState` | General and special registers, FPU, XSAVE, CPUID, MSRs, XCRs, debug registers, events, MP state, LAPIC, and TSC frequency |--The vCPU decoder rejects truncated input and FPU payloads with a length other-than the KVM ABI size. It checks the declared sequence lengths before reading-elements and accepts up to 65,536 XSAVE words (256 KiB), 256 CPUID entries,-and 4,096 MSR entries. These limits apply to decoding. The caller handles-host compatibility and validation of register values.--On Linux x86_64, `make test:unit:vmm` checks Postcard round trips, truncated-input, and decode limits without `/dev/kvm`.+| `X86VmState` | PIC master and slave, IOAPIC, PIT, and KVM clock |+| `X86VcpuState` | General and special registers, FPU, CPUID, filtered MSRs, host-sized XSAVE, XCRs, debug registers, events, MP state, LAPIC, and TSC frequency |++### Save++Stop all vCPUs and IRQ producers, then call `Vcpu::complete_pending_io` on each+vCPU's owning thread. Begin the round with `X86Vm::save_state`, then call+`X86Vcpu::save_state` once per vCPU on its owning thread. A failed vCPU save can+be retried in the same round. Finish all vCPU saves before starting another+round. KVM timers can advance during capture, and PIT restore can lose+sub-tick timing.++### Restore++Restore into an identically configured VM with fresh, never-entered vCPUs.++1. Register restored guest RAM with `Vm::map_memory`.+2. Call `X86Vm::restore_before_vcpus` to set the guest clock in nanoseconds.+ KVM receives `flags: 0` for kernel compatibility and to exclude snapshot downtime.+3. Create the vCPUs and call `X86Vcpu::restore_state` on each owning thread.+ The restored clock anchors the pvclock epoch that KVM writes into guest RAM.+4. Call `X86Vm::restore_after_vcpus` after all vCPUs are restored. It validates+ IRQ chip IDs, restores the chips, then restores the PIT if present.+5. Call `Vcpu::notify_guest_stopped` on each owning thread before `Vcpu::run`.+ It succeeds even if KVM pvclock is inactive.++A vCPU restore preflight error permits a retry on the same vCPU. Any failure+from the `KVM_SET_CPUID2` attempt onward requires discarding the destination VM.+VM snapshot operations return `Error::VmState` on failure, and vCPU snapshot+operations return `Error::ConfigureVcpu`. Both preserve the underlying `io::Error`,+including its kind and any ioctl errno.++### Scope++Nested virtualization, Hyper-V SynIC, MCE bank setup, guest-debug configuration,+IRQ routing, and device or irqfd configuration are outside the snapshot images.+Capture and restore reject paged 32-bit PAE and CET shadow stack (SHSTK).+Keep host XSTATE permissions fixed after vCPU creation.++Capture gates and restore validates CPUID-gated MSRs against guest CPUID.+SGX launch key hashes require SGX_LC. IA32_PERF_CAPABILITIES requires PDCM and a+nonzero architectural PMU version.++- `make test:unit:vmm` runs unit tests without hardware.+- `make test:integration:vmm:kvm` runs restoration tests on Linux x86_64 with `/dev/kvm`.## Host executiondiff --git a/src/hypervisor/src/error.rs b/src/hypervisor/src/error.rsindex ae6580c06..7374833bf 100644--- a/src/hypervisor/src/error.rs+++ b/src/hypervisor/src/error.rs@@ -62,6 +62,14 @@ pub enum Error {},}+impl Error {+ /// Keeps the host cause intact at the VM state transfer boundary.+ #[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]+ pub(crate) fn vm_state(operation: &'static str, source: io::Error) -> Self {+ Self::VmState { operation, source }+ }+}+impl fmt::Display for Error {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {@@ -195,7 +203,7 @@ mod tests {// EACCES on both Linux and macOS.let source = io::Error::from_raw_os_error(13);let kind = source.kind();- let error = Error::VmState { operation, source };+ let error = Error::vm_state(operation, source);let cause = error.source().and_then(|source| source.downcast_ref::<io::Error>())@@ -213,10 +221,7 @@ mod tests {#[test]fn vm_state_errors_identify_save_and_restore() {for operation in ["save", "restore"] {- let error = Error::VmState {- operation,- source: io::Error::from_raw_os_error(13),- };+ let error = Error::vm_state(operation, io::Error::from_raw_os_error(13));assert_eq!(error.to_string(), format!("failed to {operation} VM state"));}}diff --git a/src/hypervisor/src/kvm/features.rs b/src/hypervisor/src/kvm/features.rsindex 819812546..991665cd6 100644--- a/src/hypervisor/src/kvm/features.rs+++ b/src/hypervisor/src/kvm/features.rs@@ -1,17 +1,207 @@// Copyright 2026 BoxLite Contributors// SPDX-License-Identifier: Apache-2.0-use std::io;+use std::{collections::HashSet, io, os::fd::AsRawFd, sync::Arc};use kvm_bindings::{CpuId, KVM_CPUID_FLAG_SIGNIFCANT_INDEX, KVM_CPUID_FLAG_STATE_READ_NEXT,- KVM_CPUID_FLAG_STATEFUL_FUNC, KVM_MAX_CPUID_ENTRIES, Msrs, kvm_cpuid_entry2, kvm_msr_entry,+ KVM_CPUID_FLAG_STATEFUL_FUNC, KVM_MAX_CPUID_ENTRIES, KVM_MAX_MSR_ENTRIES, Msrs,+ kvm_cpuid_entry2, kvm_msr_entry,};use kvm_ioctls::Kvm;use super::KvmVcpu;+use crate::x86::MAX_SNAPSHOT_MSR_ENTRIES;use crate::{Error, Result, X86CpuidEntry, X86Msr};+pub(super) const MSR_IA32_TSC: u32 = 0x10;+const MSR_IA32_FEAT_CTL: u32 = 0x3a;+const MSR_IA32_TSC_ADJUST: u32 = 0x3b;+const MSR_MTRR_CAP: u32 = 0xfe;+const MSR_IA32_PERF_CAPABILITIES: u32 = 0x345;+const MSR_IA32_RTIT_CTL: u32 = 0x570;+pub(super) const MSR_IA32_TSC_DEADLINE: u32 = 0x6e0;+const MSR_IA32_DEBUGCTLMSR: u32 = 0x1d9;+const MSR_IA32_XSS: u32 = 0xda0;+const MSR_KVM_ASYNC_PF_EN: u32 = 0x4b56_4d02;+const MSR_KVM_ASYNC_PF_INT: u32 = 0x4b56_4d06;+const SGX_LC_MSRS: &[u32] = &[0x8c, 0x8d, 0x8e, 0x8f];++// Linux x86_64 _IOWR(KVMIO, 0x02, struct kvm_msr_list).+const KVM_GET_MSR_INDEX_LIST: libc::c_ulong = 0xc004_ae02;++pub(super) fn kvm_msr_index_list(kvm: &Kvm) -> io::Result<Vec<u32>> {+ query_msr_index_list_with(MAX_SNAPSHOT_MSR_ENTRIES, |buf| {+ // SAFETY: the aligned buffer holds the u32 header and the number of+ // u32 indices advertised by the header for the synchronous ioctl.+ if unsafe {+ libc::ioctl(+ kvm.as_raw_fd(),+ KVM_GET_MSR_INDEX_LIST as _,+ buf.as_mut_ptr(),+ )+ } == 0+ {+ Ok(())+ } else {+ Err(io::Error::last_os_error())+ }+ })+}++fn query_msr_index_list_with(+ max_entries: usize,+ mut ioctl: impl FnMut(&mut [u32]) -> io::Result<()>,+) -> io::Result<Vec<u32>> {+ let max_entries = max_entries.min(MAX_SNAPSHOT_MSR_ENTRIES);+ let mut cap = KVM_MAX_MSR_ENTRIES.min(max_entries);+ let mut retries = 4;+ loop {+ let mut buf = vec![0; 1 + cap];+ buf[0] = cap as u32;+ match ioctl(&mut buf) {+ Ok(()) => {+ let count = buf[0] as usize;+ if count > cap {+ return Err(io::Error::other("KVM returned an invalid MSR index count"));+ }+ buf.copy_within(1..1 + count, 0);+ buf.truncate(count);+ return Ok(buf);+ }+ Err(error) => {+ let needed = buf[0] as usize;+ if error.raw_os_error() != Some(libc::E2BIG)+ || needed <= cap+ || needed > max_entries+ || retries == 0+ {+ return Err(error);+ }+ retries -= 1;+ cap = needed;+ }+ }+ }+}++const SUPPLEMENTAL_SNAPSHOT_MSRS: &[u32] = &[+ // MTRR_DEF_TYPE.+ 0x2ff,+ // Fixed MTRRs.+ 0x250,+ 0x258,+ 0x259,+ 0x268,+ 0x269,+ 0x26a,+ 0x26b,+ 0x26c,+ 0x26d,+ 0x26e,+ 0x26f,+ // Variable MTRRs.+ 0x200,+ 0x201,+ 0x202,+ 0x203,+ 0x204,+ 0x205,+ 0x206,+ 0x207,+ 0x208,+ 0x209,+ 0x20a,+ 0x20b,+ 0x20c,+ 0x20d,+ 0x20e,+ 0x20f,+ MSR_IA32_XSS,+ MSR_IA32_DEBUGCTLMSR,+];++fn is_excluded_msr(index: u32) -> bool {+ // MTRRcap is read-only. LAPIC ioctls carry x2APIC state. Hyper-V's+ // paravirtualized state has separate VM-wide and per-vCPU dependencies.+ matches!(index, MSR_MTRR_CAP | 0x800..=0xbff | 0x4000_0000..=0x4000_01ff)+}++pub(super) fn validate_restore_msrs(+ entries: &[kvm_msr_entry],+ cpuid: &[kvm_cpuid_entry2],+) -> io::Result<()> {+ if let Some(entry) = entries.iter().find(|entry| is_excluded_msr(entry.index)) {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("MSR index {:#x} is excluded from snapshots", entry.index),+ ));+ }+ if let Some(entry) = entries.iter().find(|entry| match entry.index {+ MSR_IA32_PERF_CAPABILITIES => !cpuid_supports_perf_capabilities(cpuid),+ index => SGX_LC_MSRS.contains(&index) && !cpuid_supports_sgx_lc(cpuid),+ }) {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!(+ "MSR index {:#x} is incompatible with snapshot CPUID",+ entry.index+ ),+ ));+ }+ Ok(())+}++pub(super) fn build_snapshot_msr_indices(kvm_advertised: &[u32]) -> Arc<[u32]> {+ let mut seen = HashSet::new();+ kvm_advertised+ .iter()+ .chain(SUPPLEMENTAL_SNAPSHOT_MSRS)+ .copied()+ .filter(|&index| {+ !is_excluded_msr(index)+ && !SGX_LC_MSRS.contains(&index)+ && index != MSR_IA32_PERF_CAPABILITIES+ && seen.insert(index)+ })+ .collect()+}++#[derive(Debug, Default)]+pub(super) struct RestoreMsrPlan {+ pub(super) before_tsc: Vec<kvm_msr_entry>,+ pub(super) tsc: Option<kvm_msr_entry>,+ pub(super) after_tsc: Vec<kvm_msr_entry>,+}++pub(super) fn order_msrs_for_restore(entries: &[kvm_msr_entry]) -> RestoreMsrPlan {+ let mut plan = RestoreMsrPlan::default();+ let mut ordinary = Vec::new();+ let mut feature_controls = Vec::new();+ let mut deadlines = Vec::new();+ let mut trace_controls = Vec::new();+ for &entry in entries {+ match entry.index {+ MSR_IA32_TSC_ADJUST => plan.before_tsc.push(entry),+ MSR_IA32_TSC => plan.tsc = Some(entry),+ // PERF_CAPABILITIES can refresh the masks used to validate PMU MSRs.+ MSR_IA32_PERF_CAPABILITIES => plan.after_tsc.push(entry),+ MSR_KVM_ASYNC_PF_INT => plan.after_tsc.push(entry),+ // The interrupt vector must be installed before the enable bit.+ MSR_KVM_ASYNC_PF_EN => ordinary.push(entry),+ MSR_IA32_FEAT_CTL => feature_controls.push(entry),+ MSR_IA32_TSC_DEADLINE => deadlines.push(entry),+ MSR_IA32_RTIT_CTL => trace_controls.push(entry),+ _ => ordinary.push(entry),+ }+ }+ plan.after_tsc.extend(ordinary);+ plan.after_tsc.extend(feature_controls);+ plan.after_tsc.extend(deadlines);+ plan.after_tsc.extend(trace_controls);+ plan+}+pub(super) fn supported_cpuid(kvm: &Kvm) -> io::Result<Vec<X86CpuidEntry>> {let cpuid = kvm.get_supported_cpuid(KVM_MAX_CPUID_ENTRIES)@@ -62,6 +252,7 @@ impl KvmVcpu {};let cpuid = cpuid_buffer(cpuid).map_err(|e| failure("prepare CPUID", e))?;let msrs = msr_buffer(msrs).map_err(|e| failure("prepare MSRs", e))?;+ self.fd.clear_tsc_save_anchor();self.fd.set_cpuid2(&cpuid).map_err(|e| failure("set CPUID", e.into()))?;@@ -73,7 +264,7 @@ impl KvmVcpu {}}-fn check_written(msrs: &Msrs, written: usize) -> io::Result<()> {+pub(super) fn check_written(msrs: &Msrs, written: usize) -> io::Result<()> {match msrs.as_slice().get(written) {Some(rejected) => Err(io::Error::other(format!("KVM wrote {written} of {} MSRs; first rejected index {:#x}",@@ -126,11 +317,545 @@ fn msr_buffer(entries: &[X86Msr]) -> io::Result<Msrs> {Ok(buffer)}+/// Probe one index at a time: a short batch read stops at the first unavailable+/// MSR and would lose every subsequent register (notably CPUID-gated PMU MSRs).+/// Probe the VM's filtered list of KVM-advertised and supplemental indices.+pub(super) fn snapshot_msrs(+ fd: &kvm_ioctls::VcpuFd,+ indices: &[u32],+) -> io::Result<Vec<kvm_msr_entry>> {+ let mut entries = Vec::new();+ for &index in indices {+ if is_excluded_msr(index) {+ continue;+ }+ let mut msr = Msrs::from_entries(&[kvm_msr_entry {+ index,+ ..Default::default()+ }])+ .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;+ match fd.get_msrs(&mut msr).map_err(io::Error::from)? {+ 0 => {} // Unavailable under this vCPU's CPUID/MCE configuration.+ 1 => entries.push(msr.as_slice()[0]),+ _ => return Err(io::Error::other("invalid MSR read count")),+ }+ }+ Ok(entries)+}++pub(super) fn validate_cpuid_count(len: usize) -> io::Result<()> {+ if !(1..=KVM_MAX_CPUID_ENTRIES).contains(&len) {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "invalid CPUID count",+ ));+ }+ Ok(())+}++pub(super) fn snapshot_cpuid(entries: &[kvm_cpuid_entry2]) -> io::Result<CpuId> {+ validate_cpuid_count(entries.len())?;+ CpuId::from_entries(entries).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))+}++fn cpuid_leaf_subleaf0(entries: &[kvm_cpuid_entry2], leaf: u32) -> Option<&kvm_cpuid_entry2> {+ entries.iter().find(|entry| {+ entry.function == leaf+ && (entry.flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX == 0 || entry.index == 0)+ })+}++pub(super) fn validate_snapshot_cpuid_features(entries: &[kvm_cpuid_entry2]) -> io::Result<()> {+ if cpuid_leaf_subleaf0(entries, 7).is_some_and(|entry| entry.ecx & (1 << 7) != 0) {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "CET shadow stack (SHSTK) state cannot be snapshotted",+ ));+ }+ Ok(())+}++fn cpuid_supports_sgx_lc(cpuid: &[kvm_cpuid_entry2]) -> bool {+ cpuid_leaf_subleaf0(cpuid, 7).is_some_and(|entry| entry.ecx & (1 << 30) != 0)+}++fn cpuid_supports_perf_capabilities(cpuid: &[kvm_cpuid_entry2]) -> bool {+ // KVM can return the host value even when the guest lacks PDCM or a PMU.+ // Require both PDCM and a nonzero architectural PMU version for restore.+ cpuid_leaf_subleaf0(cpuid, 1).is_some_and(|entry| entry.ecx & (1 << 15) != 0)+ && cpuid_leaf_subleaf0(cpuid, 0xa).is_some_and(|entry| entry.eax & 0xff != 0)+}++pub(super) fn extra_cpuid_gated_msr_indices(cpuid: &[kvm_cpuid_entry2]) -> Vec<u32> {+ let mut indices = Vec::new();+ if cpuid_supports_sgx_lc(cpuid) {+ indices.extend_from_slice(SGX_LC_MSRS);+ }+ if cpuid_supports_perf_capabilities(cpuid) {+ indices.push(MSR_IA32_PERF_CAPABILITIES);+ }+ indices+}+#[cfg(test)]mod tests {use super::*;use kvm_bindings::{KVM_CPUID_FLAG_STATE_READ_NEXT, KVM_CPUID_FLAG_STATEFUL_FUNC};+ #[test]+ fn msr_index_list_ioctl_number_matches_kvm_abi() {+ assert_eq!(size_of::<kvm_bindings::kvm_msr_list>(), 4);+ assert_eq!(KVM_GET_MSR_INDEX_LIST, 0xc004_ae02);+ }++ #[test]+ fn msr_index_list_retries_with_the_kernel_count() {+ for count in [0, 1, 256, 257, MAX_SNAPSHOT_MSR_ENTRIES] {+ let mut caps = Vec::new();+ let indices = query_msr_index_list_with(MAX_SNAPSHOT_MSR_ENTRIES, |buf| {+ let cap = buf[0] as usize;+ assert_eq!(buf.len(), cap + 1);+ caps.push(cap);+ buf[0] = count as u32;+ if count > cap {+ return Err(io::Error::from_raw_os_error(libc::E2BIG));+ }+ for (i, index) in buf[1..=count].iter_mut().enumerate() {+ *index = i as u32 + 0x10;+ }+ Ok(())+ })+ .unwrap();+ assert_eq!(indices, (0x10..0x10 + count as u32).collect::<Vec<_>>());+ let mut expected = vec![KVM_MAX_MSR_ENTRIES];+ if count > KVM_MAX_MSR_ENTRIES {+ expected.push(count);+ }+ assert_eq!(caps, expected);+ }+ }++ #[test]+ fn msr_index_list_rejects_bad_counts_and_preserves_errno() {+ for (max_entries, count, errno) in [+ (+ MAX_SNAPSHOT_MSR_ENTRIES + 1,+ MAX_SNAPSHOT_MSR_ENTRIES + 1,+ libc::E2BIG,+ ),+ (MAX_SNAPSHOT_MSR_ENTRIES, KVM_MAX_MSR_ENTRIES, libc::E2BIG),+ (MAX_SNAPSHOT_MSR_ENTRIES, 0, libc::E2BIG),+ (8, 9, libc::E2BIG),+ (MAX_SNAPSHOT_MSR_ENTRIES, 257, libc::EPERM),+ ] {+ let mut calls = 0;+ let error = query_msr_index_list_with(max_entries, |buf| {+ calls += 1;+ assert_eq!(buf[0] as usize, KVM_MAX_MSR_ENTRIES.min(max_entries));+ buf[0] = count as u32;+ Err(io::Error::from_raw_os_error(errno))+ })+ .unwrap_err();+ assert_eq!(calls, 1);+ assert_eq!(error.raw_os_error(), Some(errno));+ }+ let error = query_msr_index_list_with(0, |buf| {+ assert_eq!(buf, [0]);+ buf[0] = 1;+ Ok(())+ })+ .unwrap_err();+ assert_eq!(error.to_string(), "KVM returned an invalid MSR index count");+ }++ #[test]+ fn msr_index_list_stops_after_four_resizes() {+ let mut caps = Vec::new();+ let error = query_msr_index_list_with(MAX_SNAPSHOT_MSR_ENTRIES, |buf| {+ caps.push(buf[0] as usize);+ buf[0] += 1;+ Err(io::Error::from_raw_os_error(libc::E2BIG))+ })+ .unwrap_err();+ assert_eq!(+ caps,+ (KVM_MAX_MSR_ENTRIES..=KVM_MAX_MSR_ENTRIES + 4).collect::<Vec<_>>()+ );+ assert_eq!(error.raw_os_error(), Some(libc::E2BIG));+ }++ #[test]+ fn restore_rejects_excluded_msrs() {+ for index in [0xfe, 0x800, 0xbff, 0x4000_0000, 0x4000_01ff] {+ assert_eq!(+ validate_restore_msrs(+ &[kvm_msr_entry {+ index,+ ..Default::default()+ }],+ &[],+ )+ .unwrap_err()+ .kind(),+ io::ErrorKind::InvalidInput+ );+ }+ let allowed = [0x7ff, 0xc00, 0x3fff_ffff, 0x4000_0200].map(|index| kvm_msr_entry {+ index,+ ..Default::default()+ });+ assert!(validate_restore_msrs(&allowed, &[]).is_ok());+ }++ #[test]+ fn restore_validates_cpuid_gated_msrs() {+ let cpuid = [+ kvm_cpuid_entry2 {+ function: 1,+ ecx: 1 << 15,+ ..Default::default()+ },+ kvm_cpuid_entry2 {+ function: 0xa,+ eax: 1,+ ..Default::default()+ },+ kvm_cpuid_entry2 {+ function: 7,+ ecx: 1 << 30,+ ..Default::default()+ },+ ];+ let perf_cases = [&cpuid[2..], &cpuid[..1], &cpuid[1..2]]+ .map(|unsupported| (0x345, &cpuid[..2], unsupported));+ let sgx_cases = SGX_LC_MSRS+ .iter()+ .map(|&index| (index, &cpuid[2..], &cpuid[..2]));+ for (index, supported, unsupported) in perf_cases.into_iter().chain(sgx_cases) {+ let msrs = [kvm_msr_entry {+ index,+ ..Default::default()+ }];+ assert!(validate_restore_msrs(&msrs, supported).is_ok());+ assert_eq!(+ validate_restore_msrs(&msrs, unsupported)+ .unwrap_err()+ .kind(),+ io::ErrorKind::InvalidInput,+ "MSR index {index:#x}"+ );+ }+ }++ #[test]+ fn cpuid_count_requires_at_least_one_leaf_and_respects_the_kvm_limit() {+ for count in [0, KVM_MAX_CPUID_ENTRIES + 1] {+ assert_eq!(+ validate_cpuid_count(count).unwrap_err().kind(),+ io::ErrorKind::InvalidInput+ );+ }+ assert!(validate_cpuid_count(1).is_ok());+ assert!(validate_cpuid_count(KVM_MAX_CPUID_ENTRIES).is_ok());+ }++ #[test]+ fn shstk_is_rejected_for_leaf_seven_subleaf_zero() {+ let mut entry = kvm_cpuid_entry2 {+ function: 7,+ flags: KVM_CPUID_FLAG_SIGNIFCANT_INDEX,+ ecx: 1 << 7,+ ..Default::default()+ };+ assert_eq!(+ validate_snapshot_cpuid_features(&[entry])+ .unwrap_err()+ .kind(),+ io::ErrorKind::Unsupported+ );+ entry.index = 1;+ assert!(validate_snapshot_cpuid_features(&[entry]).is_ok());+ entry.flags = 0;+ assert_eq!(+ validate_snapshot_cpuid_features(&[entry])+ .unwrap_err()+ .kind(),+ io::ErrorKind::Unsupported+ );+ assert!(validate_snapshot_cpuid_features(&[]).is_ok());+ }++ #[test]+ fn sgx_launch_hashes_follow_sgx_lc() {+ let mut entry = kvm_cpuid_entry2 {+ function: 7,+ flags: KVM_CPUID_FLAG_SIGNIFCANT_INDEX,+ ebx: 1 << 2,+ ..Default::default()+ };+ assert!(extra_cpuid_gated_msr_indices(&[entry]).is_empty());+ entry.ecx = 1 << 30;+ assert_eq!(extra_cpuid_gated_msr_indices(&[entry]), SGX_LC_MSRS);+ entry.index = 1;+ assert!(extra_cpuid_gated_msr_indices(&[entry]).is_empty());+ }++ #[test]+ fn perf_capabilities_requires_pdcm_and_a_nonzero_pmu_version() {+ for pdcm in [false, true] {+ for pmu_version in [None, Some(0), Some(1)] {+ let mut cpuid = vec![kvm_cpuid_entry2 {+ function: 1,+ ecx: u32::from(pdcm) << 15,+ ..Default::default()+ }];+ if let Some(version) = pmu_version {+ cpuid.push(kvm_cpuid_entry2 {+ function: 0xa,+ eax: (1 << 8) | version,+ ..Default::default()+ });+ }+ let expected: &[u32] = if pdcm && pmu_version == Some(1) {+ &[0x345]+ } else {+ &[]+ };+ assert_eq!(extra_cpuid_gated_msr_indices(&cpuid), expected);+ }+ }+ }++ #[test]+ fn perf_capabilities_and_sgx_launch_hashes_follow_cpuid_index_flags() {+ let mut cpuid = [+ kvm_cpuid_entry2 {+ function: 1,+ ecx: 1 << 15,+ ..Default::default()+ },+ kvm_cpuid_entry2 {+ function: 0xa,+ eax: 1,+ ..Default::default()+ },+ kvm_cpuid_entry2 {+ function: 7,+ ecx: 1 << 30,+ ..Default::default()+ },+ ];+ let combined = [0x8c, 0x8d, 0x8e, 0x8f, 0x345];+ for leaf in [0, 1] {+ cpuid[leaf].flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;+ assert_eq!(extra_cpuid_gated_msr_indices(&cpuid), combined);+ cpuid[leaf].index = 1;+ assert_eq!(extra_cpuid_gated_msr_indices(&cpuid), SGX_LC_MSRS);+ cpuid[leaf].flags = 0;+ assert_eq!(extra_cpuid_gated_msr_indices(&cpuid), combined);+ }+ }++ #[test]+ fn restore_orders_async_pf_and_sgx_dependencies() {+ let ordered = [+ MSR_KVM_ASYNC_PF_INT,+ MSR_KVM_ASYNC_PF_INT,+ MSR_KVM_ASYNC_PF_EN,+ 0x4b56_4d07,+ 0x8c,+ 0x8d,+ 0x8e,+ 0x8f,+ MSR_IA32_FEAT_CTL,+ MSR_IA32_TSC_DEADLINE,+ MSR_IA32_RTIT_CTL,+ ];+ let entries = ordered.map(|index| kvm_msr_entry {+ index,+ ..Default::default()+ });+ for msrs in [+ entries,+ [10, 9, 8, 2, 3, 4, 5, 6, 7, 0, 1].map(|i| entries[i]),+ ] {+ assert_eq!(order_msrs_for_restore(&msrs).after_tsc, entries);+ }+ for entry in entries {+ assert_eq!(order_msrs_for_restore(&[entry]).after_tsc, [entry]);+ }+ let mut duplicate_vectors = [entries[0], entries[0]];+ duplicate_vectors[1].data = 42;+ let plan =+ order_msrs_for_restore(&[entries[2], duplicate_vectors[0], duplicate_vectors[1]]);+ assert_eq!(+ plan.after_tsc,+ [duplicate_vectors[0], duplicate_vectors[1], entries[2]]+ );+ }++ #[test]+ fn build_snapshot_msr_indices_adds_all_writable_mtrrs_and_supplements() {+ let indices = build_snapshot_msr_indices(&[]);+ let expected: Vec<_> = [0x2ff, 0x250, 0x258, 0x259]+ .into_iter()+ .chain(0x268..=0x26f)+ .chain(0x200..=0x20f)+ .chain([0xda0, 0x1d9])+ .collect();+ assert_eq!(expected.len(), 28 + 2);+ assert_eq!(&*indices, expected);+ }++ #[test]+ fn build_snapshot_msr_indices_excludes_cpuid_gated_msrs() {+ let advertised = [0x8c, 0x8d, 0x8e, 0x8f, 0x345];+ let indices = build_snapshot_msr_indices(&advertised);+ for index in advertised {+ assert!(!indices.contains(&index), "shared MSR index {index:#x}");+ }+ }++ #[test]+ fn build_snapshot_msr_indices_deduplicates_and_excludes_reserved_ranges() {+ let retained = [0x1d9, 0x7ff, 0xc00, 0xda0, 0x4000_0200, 0x250, 0x10];+ let indices = build_snapshot_msr_indices(&[+ 0x1d9,+ 0x7ff,+ 0x800,+ 0xbff,+ 0xc00,+ 0xda0,+ 0x4000_0000,+ 0x4000_01ff,+ 0x4000_0200,+ 0xfe,+ 0x250,+ 0x10,+ 0x1d9,+ 0xda0,+ 0x10,+ ]);+ assert_eq!(&indices[..retained.len()], &retained);+ let expected: Vec<_> = retained+ .into_iter()+ .chain(+ SUPPLEMENTAL_SNAPSHOT_MSRS+ .iter()+ .copied()+ .filter(|index| !retained.contains(index)),+ )+ .collect();+ assert_eq!(&*indices, expected);+ }++ #[test]+ fn order_msrs_for_restore_places_dependencies_and_keeps_the_last_tsc() {+ let entries = [+ 0x570,+ 0x6e0,+ 0x10,+ 0x2ff,+ 0x3b,+ 0x571,+ 0xda0,+ 0x10,+ 0x1d9,+ 0x11,+ 0x4b56_4d00,+ 0x560,+ ]+ .into_iter()+ .enumerate()+ .map(|(pos, index)| kvm_msr_entry {+ index,+ data: pos as u64,+ ..Default::default()+ })+ .collect::<Vec<_>>();+ let plan = order_msrs_for_restore(&entries);+ assert_eq!(plan.before_tsc, [entries[4]]);+ assert_eq!(plan.tsc, Some(entries[7]));+ assert_eq!(+ plan.after_tsc,+ [3, 5, 6, 8, 9, 10, 11, 1, 0].map(|pos| entries[pos])+ );+ }++ #[test]+ fn order_msrs_for_restore_accepts_empty_input() {+ let plan = order_msrs_for_restore(&[]);+ assert!(plan.before_tsc.is_empty());+ assert!(plan.tsc.is_none());+ assert!(plan.after_tsc.is_empty());+ }++ #[test]+ fn restore_orders_perf_capabilities_before_pmu_msrs() {+ let entries = [0x38f, 0x3f1, 0x186, 0x345].map(|index| kvm_msr_entry {+ index,+ ..Default::default()+ });+ let plan = order_msrs_for_restore(&entries);+ assert!(plan.before_tsc.is_empty());+ assert_eq!(plan.after_tsc, [3, 0, 1, 2].map(|pos| entries[pos]));+ }++ #[test]+ fn snapshot_cpuid_preserves_entries_and_only_checks_count() {+ let first = kvm_cpuid_entry2 {+ function: 7,+ ..Default::default()+ };+ let mut second = first;+ second.index = 1;+ second.flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX | (1 << 31);+ second.padding[0] = 1;+ let entries = [first, second, second];+ assert_eq!(snapshot_cpuid(&entries).unwrap().as_slice(), &entries);+ assert!(snapshot_cpuid(&[]).is_err());+ assert!(snapshot_cpuid(&vec![first; KVM_MAX_CPUID_ENTRIES + 1]).is_err());+ }++ #[test]+ fn snapshot_cpuid_accepts_counts_just_below_and_at_the_limit() {+ let entry = kvm_cpuid_entry2 {+ function: 7,+ eax: 42,+ ..Default::default()+ };+ for len in [1, KVM_MAX_CPUID_ENTRIES - 1, KVM_MAX_CPUID_ENTRIES] {+ let entries = vec![entry; len];+ assert_eq!(snapshot_cpuid(&entries).unwrap().as_slice(), entries);+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_msrs_skips_x2apic_and_unavailable_indices_without_losing_later_values() {+ let vm = super::super::KvmVm::new().unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(+ vm.supported_cpuid(),+ &[X86Msr {+ index: 0xc0000102,+ value: 0x12345678,+ }],+ )+ .unwrap();+ assert!(snapshot_msrs(&cpu.fd, &[]).unwrap().is_empty());+ let entries = snapshot_msrs(+ &cpu.fd,+ &[0x7ff, 0x800, 0xbff, 0xc00, 0x10, u32::MAX, 0xc0000102],+ )+ .unwrap();+ assert_eq!(+ entries.iter().map(|e| e.index).collect::<Vec<_>>(),+ [0x10, 0xc0000102]+ );+ assert_eq!(entries[1].data, 0x12345678);+ }+#[test]fn supported_cpuid_omits_unrepresentable_stateful_entries() {let entries = [diff --git a/src/hypervisor/src/kvm/vcpu.rs b/src/hypervisor/src/kvm/vcpu.rsindex 74b8fdb32..0464e2697 100644--- a/src/hypervisor/src/kvm/vcpu.rs+++ b/src/hypervisor/src/kvm/vcpu.rs@@ -1,17 +1,340 @@// Copyright 2026 BoxLite Contributors// SPDX-License-Identifier: Apache-2.0-use std::{io, marker::PhantomData, rc::Rc};+use std::{+ collections::{HashMap, HashSet},+ io,+ marker::PhantomData,+ ops::{Deref, DerefMut},+ os::fd::AsRawFd,+ rc::Rc,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+};use kvm_bindings::{KVM_EXIT_HLT, KVM_EXIT_INTR, KVM_EXIT_IO, KVM_EXIT_IO_IN, KVM_EXIT_IO_OUT, KVM_EXIT_MMIO,KVM_EXIT_SHUTDOWN, KVM_EXIT_SYSTEM_EVENT, KVM_SYSTEM_EVENT_RESET, KVM_SYSTEM_EVENT_SHUTDOWN,- kvm_run,+ KVM_VCPU_TSC_CTRL, KVM_VCPU_TSC_OFFSET, Msrs, kvm_device_attr, kvm_msr_entry, kvm_run,+ kvm_sregs,+};+use kvm_ioctls::{VcpuFd, VmFd};++use super::{+ KvmVcpuHandle,+ features::{+ MSR_IA32_TSC, check_written, extra_cpuid_gated_msr_indices, order_msrs_for_restore,+ snapshot_cpuid, snapshot_msrs, validate_cpuid_count, validate_restore_msrs,+ validate_snapshot_cpuid_features,+ },+ kick::WorkerSignal,};-use kvm_ioctls::VcpuFd;+use crate::{Error, Result, VcpuExit, x86::MAX_SNAPSHOT_MSR_ENTRIES};++/// Number of u32 words in kvm_xsave.region, before its flexible-array tail.+const XSAVE_REGION_WORDS: usize = 1024;++/// KVM_SET_MSRS returns E2BIG when nmsrs >= KVM_MAX_MSR_ENTRIES;+/// each ioctl can write at most 255 entries.+const MAX_MSR_BATCH_ENTRIES: usize = kvm_bindings::KVM_MAX_MSR_ENTRIES - 1;++pub(super) const MSR_KVM_WALL_CLOCK: u32 = 0x11;+pub(super) const MSR_KVM_WALL_CLOCK_NEW: u32 = 0x4b56_4d00;++// Linux x86_64 _IO(KVMIO, 0xa3), returning the frequency directly.+const KVM_GET_TSC_KHZ: libc::c_ulong = 0x0000_aea3;++fn parse_tsc_khz(ret: libc::c_int, last_err: io::Error) -> io::Result<u32> {+ match ret {+ 1.. => Ok(ret as u32),+ 0 => Err(io::Error::other("KVM_GET_TSC_KHZ returned zero")),+ _ if last_err.raw_os_error().is_some_and(|errno| errno != 0) => Err(last_err),+ _ => Err(io::Error::other(format!(+ "KVM_GET_TSC_KHZ failed with {ret}"+ ))),+ }+}++fn get_tsc_khz(fd: &VcpuFd) -> io::Result<u32> {+ // SAFETY: this ioctl takes no pointer argument and uses a live vCPU fd.+ let ret = unsafe { libc::ioctl(fd.as_raw_fd(), KVM_GET_TSC_KHZ as _, 0 as libc::c_ulong) };+ parse_tsc_khz(ret, io::Error::last_os_error())+}++// Linux x86_64 _IOW(KVMIO, nr, struct kvm_device_attr).+const KVM_SET_DEVICE_ATTR: libc::c_ulong = 0x4018_aee1;+const KVM_GET_DEVICE_ATTR: libc::c_ulong = 0x4018_aee2;+const KVM_HAS_DEVICE_ATTR: libc::c_ulong = 0x4018_aee3;+const _: () = assert!(size_of::<kvm_device_attr>() == 24);-use super::{KvmVcpuHandle, kick::WorkerSignal};-use crate::{Error, Result, VcpuExit};+fn tsc_offset_ioctl(fd: &VcpuFd, request: libc::c_ulong, addr: u64) -> io::Result<bool> {+ let attr = kvm_device_attr {+ group: KVM_VCPU_TSC_CTRL,+ attr: u64::from(KVM_VCPU_TSC_OFFSET),+ addr,+ ..Default::default()+ };+ // SAFETY: attr lives through the synchronous ioctl. Its addr is unused for+ // HAS and points to a u64 writable for GET and readable for SET.+ if unsafe { libc::ioctl(fd.as_raw_fd(), request as _, &raw const attr) } == 0 {+ return Ok(true);+ }+ let error = io::Error::last_os_error();+ match error.raw_os_error() {+ Some(libc::ENXIO) => Ok(false),+ Some(libc::ENOTTY | libc::EINVAL) if request == KVM_HAS_DEVICE_ATTR => Ok(false),+ _ => Err(error),+ }+}++#[derive(Debug)]+pub(super) struct CachedIoError {+ raw_os_error: Option<i32>,+ kind: io::ErrorKind,+ message: String,+}++impl CachedIoError {+ pub(super) fn from_io(error: io::Error) -> Self {+ Self {+ raw_os_error: error.raw_os_error(),+ kind: error.kind(),+ message: error.to_string(),+ }+ }++ fn to_io(&self) -> io::Error {+ match self.raw_os_error {+ Some(errno) => io::Error::from_raw_os_error(errno),+ None => io::Error::new(self.kind, self.message.clone()),+ }+ }+}++#[derive(Debug, Default)]+struct TscSaveAnchor {+ active: AtomicBool,+ state: Mutex<TscSaveState>,+}++#[derive(Debug, Default)]+struct TscSaveState {+ vm_clock_ns: Option<u64>,+ per_freq: HashMap<u32, u64>,+ saved_vcpus: HashSet<u32>,+}++impl TscSaveState {+ fn clock_for_vcpu_save(&self, id: u32) -> io::Result<u64> {+ let clock_ns = self+ .vm_clock_ns+ .ok_or_else(|| io::Error::other("save VM state before saving vCPU state"))?;+ if self.saved_vcpus.contains(&id) {+ return Err(io::Error::other(+ "save VM state before recapturing vCPU state",+ ));+ }+ Ok(clock_ns)+ }+}++impl TscSaveAnchor {+ fn record_vm_clock(&self, clock_ns: u64) {+ let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());+ state.per_freq.clear();+ state.saved_vcpus.clear();+ state.vm_clock_ns = Some(clock_ns);+ self.active.store(true, Ordering::Release);+ }++ fn check_vcpu_save(&self, id: u32) -> io::Result<()> {+ let state = self.state.lock().unwrap_or_else(|e| e.into_inner());+ state.clock_for_vcpu_save(id)?;+ Ok(())+ }++ fn commit_vcpu_save(+ &self,+ id: u32,+ normalize_tsc: impl FnOnce(u64, &mut HashMap<u32, u64>) -> io::Result<()>,+ ) -> io::Result<()> {+ let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());+ let clock_ns = state.clock_for_vcpu_save(id)?;+ normalize_tsc(clock_ns, &mut state.per_freq)?;+ state.saved_vcpus.insert(id);+ self.active.store(true, Ordering::Release);+ Ok(())+ }++ fn clear(&self) {+ // Capture requires quiescent vCPUs. The flag bypasses the mutex on+ // normal guest entry and is set while holding the capture lock.+ if self.active.load(Ordering::Acquire) {+ let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());+ *state = TscSaveState::default();+ self.active.store(false, Ordering::Release);+ }+ }+}++#[derive(Debug, Default)]+struct TscRestoreAnchor {+ state: Mutex<TscRestoreState>,+}++#[derive(Debug, Default)]+struct TscRestoreState {+ target_clock_ns: Option<u64>,+ per_freq: HashMap<u32, u64>,+}++fn ns_to_tsc_cycles(elapsed_ns: u64, tsc_khz: u32) -> u64 {+ ((u128::from(elapsed_ns) * u128::from(tsc_khz)) / 1_000_000) as u64+}++fn forward_clock_delta(before: u64, after: u64) -> Option<u64> {+ // Adjacent clock samples are less than half the u64 range apart. Modular+ // subtraction then distinguishes a short forward wrap from a backward step.+ let delta = after.wrapping_sub(before);+ (delta <= i64::MAX as u64).then_some(delta)+}++fn anchored_scaled_tsc(+ scaled_now: u64,+ now_clock_ns: u64,+ anchor_clock_ns: u64,+ tsc_khz: u32,+) -> Option<u64> {+ let elapsed_ns = forward_clock_delta(anchor_clock_ns, now_clock_ns)?;+ Some(scaled_now.wrapping_sub(ns_to_tsc_cycles(elapsed_ns, tsc_khz)))+}++fn sample_scaled_tsc_with(+ anchor_ns: u64,+ tsc_khz: u32,+ mut sample: impl FnMut() -> io::Result<(u64, u64, u64)>,+) -> io::Result<u64> {+ const MAX_ATTEMPTS: usize = 5;+ const MAX_SAMPLE_WINDOW_NS: u64 = 1_000_000;++ let mut best = None;+ for _ in 0..MAX_ATTEMPTS {+ let (before, scaled_now, after) = sample()?;+ let Some(window_ns) = forward_clock_delta(before, after) else {+ continue;+ };+ let midpoint = before.wrapping_add(window_ns / 2);+ let Some(anchored) = anchored_scaled_tsc(scaled_now, midpoint, anchor_ns, tsc_khz) else {+ continue;+ };+ if window_ns <= MAX_SAMPLE_WINDOW_NS {+ return Ok(anchored);+ }+ if best.is_none_or(|(best_window, _)| window_ns < best_window) {+ best = Some((window_ns, anchored));+ }+ }+ best.map(|(_, anchored)| anchored)+ .ok_or_else(|| io::Error::other("KVM clock moved backward during TSC sampling"))+}++fn scaled_tsc_anchor(+ per_freq: &mut HashMap<u32, u64>,+ tsc_khz: u32,+ sample: impl FnOnce() -> io::Result<Option<u64>>,+) -> io::Result<Option<u64>> {+ if let Some(&anchor) = per_freq.get(&tsc_khz) {+ return Ok(Some(anchor));+ }+ let anchor = sample()?;+ if let Some(anchor) = anchor {+ per_freq.insert(tsc_khz, anchor);+ }+ Ok(anchor)+}++#[derive(Debug)]+pub(super) struct VcpuSnapshotShared {+ vm_fd: Arc<VmFd>,+ msr_indices: std::result::Result<Arc<[u32]>, CachedIoError>,+ wall_clock_lock: Mutex<()>,+ tsc_save_anchor: TscSaveAnchor,+ tsc_restore_anchor: TscRestoreAnchor,+}++impl VcpuSnapshotShared {+ pub(super) fn new(+ vm_fd: Arc<VmFd>,+ msr_indices: std::result::Result<Arc<[u32]>, CachedIoError>,+ ) -> Self {+ Self {+ vm_fd,+ msr_indices,+ wall_clock_lock: Mutex::default(),+ tsc_save_anchor: TscSaveAnchor::default(),+ tsc_restore_anchor: TscRestoreAnchor::default(),+ }+ }++ fn msr_indices(&self) -> io::Result<&Arc<[u32]>> {+ self.msr_indices.as_ref().map_err(CachedIoError::to_io)+ }++ pub(super) fn record_tsc_save_clock(&self, clock_ns: u64) {+ self.tsc_save_anchor.record_vm_clock(clock_ns);+ }++ pub(super) fn clear_tsc_save_anchor(&self) {+ self.tsc_save_anchor.clear();+ }++ pub(super) fn record_tsc_restore_clock(&self, clock_ns: u64) {+ let mut state = self+ .tsc_restore_anchor+ .state+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ state.target_clock_ns = Some(clock_ns);+ state.per_freq.clear();+ }+}++#[derive(Debug)]+pub(super) struct SnapshotVcpuFd {+ inner: VcpuFd,+ snapshot: Arc<VcpuSnapshotShared>,+}++impl SnapshotVcpuFd {+ pub(super) fn set_sregs(+ &self,+ state: &kvm_sregs,+ ) -> std::result::Result<(), kvm_ioctls::Error> {+ // Boot register setup reaches this write through both public entry points.+ self.clear_tsc_save_anchor();+ self.inner.set_sregs(state)+ }++ pub(super) fn clear_tsc_save_anchor(&self) {+ self.snapshot.clear_tsc_save_anchor();+ }+}++impl Deref for SnapshotVcpuFd {+ type Target = VcpuFd;++ fn deref(&self) -> &VcpuFd {+ &self.inner+ }+}++impl DerefMut for SnapshotVcpuFd {+ fn deref_mut(&mut self) -> &mut VcpuFd {+ &mut self.inner+ }+}/// A Linux x86_64 vCPU bound to its creating thread.///@@ -19,21 +342,39 @@ use crate::{Error, Result, VcpuExit};/// signal on this worker until drop. The caller supplies entry registers.#[derive(Debug)]pub struct KvmVcpu {- pub(super) fd: VcpuFd,+ pub(super) fd: SnapshotVcpuFd,pub(super) id: u32,run_size: usize,pending_io: PendingIo,+ entered: bool,+ restore_started: bool,+ xsave_size: std::result::Result<usize, CachedIoError>,+ tsc_offset: Option<bool>,kick: WorkerSignal,_thread_bound: PhantomData<Rc<()>>,}impl KvmVcpu {- pub(super) fn new(fd: VcpuFd, id: u32, run_size: usize, kick: WorkerSignal) -> Self {+ pub(super) fn new(+ fd: VcpuFd,+ id: u32,+ run_size: usize,+ kick: WorkerSignal,+ xsave_size: std::result::Result<usize, CachedIoError>,+ snapshot: Arc<VcpuSnapshotShared>,+ ) -> Self {Self {- fd,+ fd: SnapshotVcpuFd {+ inner: fd,+ snapshot,+ },id,run_size,pending_io: PendingIo::default(),+ entered: false,+ restore_started: false,+ xsave_size,+ tsc_offset: None,kick,_thread_bound: PhantomData,}@@ -47,6 +388,8 @@ impl KvmVcpu {/// Runs until the next exit; handle borrowed device bytes before re-entry./// An idle guest blocks until an interrupt or a cross-thread kick arrives.pub fn run(&mut self) -> Result<VcpuExit<'_>> {+ self.fd.clear_tsc_save_anchor();+ self.entered = true;match self.fd.run().map(|_| ()) {Ok(()) => {}// A vCPU waiting for INIT or SIPI returns this once it accepts one.@@ -80,6 +423,7 @@ impl KvmVcpu {pub fn complete_pending_io(&mut self) -> Result<()> {self.pending_io.complete(|| {+ self.fd.clear_tsc_save_anchor();self.fd.set_kvm_immediate_exit(1);let result = self.fd.run().map(|_| ()).map_err(io::Error::from);self.fd.set_kvm_immediate_exit(0);@@ -90,6 +434,17 @@ impl KvmVcpu {source,})}++ /// Notifies an enabled KVM pvclock that its vCPU was stopped.+ pub fn notify_guest_stopped(&mut self) -> Result<()> {+ crate::vcpu::kvmclock_ctrl_result(self.fd.kvmclock_ctrl().map_err(io::Error::from)).map_err(+ |source| Error::ConfigureVcpu {+ id: self.id,+ operation: "notify guest stopped",+ source,+ },+ )+ }}impl crate::Vcpu for KvmVcpu {@@ -103,12 +458,24 @@ impl crate::Vcpu for KvmVcpu {Self::complete_pending_io(self)}+ fn notify_guest_stopped(&mut self) -> Result<()> {+ Self::notify_guest_stopped(self)+ }+fn handle(&self) -> Self::Handle {Self::handle(self)}}impl crate::X86Vcpu for KvmVcpu {+ fn save_state(&mut self) -> Result<crate::X86VcpuState> {+ Self::save_state(self)+ }++ fn restore_state(&mut self, state: &crate::X86VcpuState) -> Result<()> {+ Self::restore_state(self, state)+ }+fn set_cpu_features(&mut self,cpuid: &[crate::X86CpuidEntry],@@ -219,10 +586,625 @@ unsafe fn decode_exit(id: u32, run: &mut kvm_run, run_size: usize) -> Result<Vcp}}+fn is_paged_32bit_pae(sregs: &kvm_sregs) -> bool {+ const CR0_PG: u64 = 1 << 31;+ const CR4_PAE: u64 = 1 << 5;+ const EFER_LMA: u64 = 1 << 10;+ sregs.cr0 & CR0_PG != 0 && sregs.cr4 & CR4_PAE != 0 && sregs.efer & EFER_LMA == 0+}++fn validate_snapshot_paging(sregs: &kvm_sregs) -> io::Result<()> {+ if is_paged_32bit_pae(sregs) {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "32-bit PAE paging state is unsupported because SREGS omits PDPTRs",+ ));+ }+ Ok(())+}++impl KvmVcpu {+ fn xsave_size(&self) -> io::Result<usize> {+ self.xsave_size+ .as_ref()+ .copied()+ .map_err(CachedIoError::to_io)+ }++ pub(super) fn has_tsc_offset(&mut self) -> io::Result<bool> {+ if let Some(supported) = self.tsc_offset {+ return Ok(supported);+ }+ let supported = tsc_offset_ioctl(&self.fd, KVM_HAS_DEVICE_ATTR, 0)?;+ self.tsc_offset = Some(supported);+ Ok(supported)+ }++ pub(super) fn get_tsc_offset(&self) -> io::Result<Option<u64>> {+ if self.tsc_offset != Some(true) {+ return Ok(None);+ }+ let mut offset = 0u64;+ tsc_offset_ioctl(&self.fd, KVM_GET_DEVICE_ATTR, &raw mut offset as u64)+ .map(|supported| supported.then_some(offset))+ }++ pub(super) fn set_tsc_offset(&self, offset: u64) -> io::Result<bool> {+ if self.tsc_offset != Some(true) {+ return Ok(false);+ }+ tsc_offset_ioctl(&self.fd, KVM_SET_DEVICE_ATTR, &raw const offset as u64)+ }++ fn sample_scaled_tsc(+ &self,+ offset: u64,+ tsc_khz: u32,+ anchor_ns: Option<u64>,+ ) -> io::Result<u64> {+ let read_scaled_tsc = || {+ let msrs = snapshot_msrs(&self.fd, &[MSR_IA32_TSC])?;+ msrs.first()+ .map(|tsc| tsc.data.wrapping_sub(offset))+ .ok_or_else(|| io::Error::other("KVM did not return IA32_TSC"))+ };+ let Some(anchor_ns) = anchor_ns else {+ return read_scaled_tsc();+ };+ let vm_fd = &self.fd.snapshot.vm_fd;+ sample_scaled_tsc_with(anchor_ns, tsc_khz, || {+ let before = vm_fd.get_clock()?.clock;+ let scaled_now = read_scaled_tsc()?;+ let after = vm_fd.get_clock()?.clock;+ Ok((before, scaled_now, after))+ })+ }++ fn commit_saved_state(&self, msrs: &mut [kvm_msr_entry], tsc_khz: u32) -> io::Result<()> {+ self.fd+ .snapshot+ .tsc_save_anchor+ .commit_vcpu_save(self.id, |clock_ns, per_freq| {+ let Some(tsc) = msrs.iter_mut().find(|entry| entry.index == MSR_IA32_TSC) else {+ return Ok(());+ };+ let Some(offset) = self.get_tsc_offset()? else {+ return Ok(());+ };+ if let Some(host_tsc) = scaled_tsc_anchor(per_freq, tsc_khz, || {+ self.sample_scaled_tsc(offset, tsc_khz, Some(clock_ns))+ .map(Some)+ })? {+ tsc.data = host_tsc.wrapping_add(offset);+ }+ Ok(())+ })+ }++ fn restore_tsc(&self, tsc: kvm_msr_entry, tsc_khz: u32) -> io::Result<()> {+ if self.tsc_offset != Some(true) {+ return self.write_msr_batches(&[tsc]);+ }+ let mut state = self+ .fd+ .snapshot+ .tsc_restore_anchor+ .state+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let clock_ns = state.target_clock_ns;+ let Some(host_tsc) = scaled_tsc_anchor(&mut state.per_freq, tsc_khz, || {+ self.get_tsc_offset()?+ .map(|offset| self.sample_scaled_tsc(offset, tsc_khz, clock_ns))+ .transpose()+ })?+ else {+ return self.write_msr_batches(&[tsc]);+ };+ if self.set_tsc_offset(tsc.data.wrapping_sub(host_tsc))? {+ Ok(())+ } else {+ self.write_msr_batches(&[tsc])+ }+ }++ fn write_msr_batches(&self, entries: &[kvm_msr_entry]) -> io::Result<()> {+ for chunk in entries.chunks(MAX_MSR_BATCH_ENTRIES) {+ let msrs = Msrs::from_entries(chunk)+ .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;+ let written = if chunk+ .iter()+ .any(|entry| matches!(entry.index, MSR_KVM_WALL_CLOCK | MSR_KVM_WALL_CLOCK_NEW))+ {+ // Each vCPU can rewrite the same pvclock sequence counter.+ let _guard = self+ .fd+ .snapshot+ .wall_clock_lock+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ self.fd.set_msrs(&msrs)?+ } else {+ self.fd.set_msrs(&msrs)?+ };+ check_written(&msrs, written)?;+ }+ Ok(())+ }++ /// Captures an architecture- and host-version-specific CPU image.+ /// Complete pending I/O and stop all VM state producers before saving VM+ /// state, then capture each vCPU once. A failed capture can be retried in the+ /// same round. Capture never enters KVM_RUN.+ ///+ /// After preflight, read `KVM_GET_MP_STATE` so `kvm_apic_accept_events()` can apply+ /// pending INIT/SIPI events and update `CS:RIP` and related state. Then read+ /// `KVM_GET_VCPU_EVENTS` before `sregs` and `debug_regs` to capture any pending+ /// `#PF`/`#DB` payload materialized into `CR2`/`DR6`. Capture CPUID after+ /// these reads so runtime bits such as OSXSAVE match the saved registers.+ pub fn save_state(&mut self) -> Result<crate::X86VcpuState> {+ let mut save = || -> io::Result<crate::X86VcpuState> {+ if self.pending_io.0 {+ return Err(io::Error::other("complete pending I/O before saving"));+ }+ self.fd.snapshot.tsc_save_anchor.check_vcpu_save(self.id)?;+ let read_cpuid = |fd: &VcpuFd| -> io::Result<_> {+ let cpuid = fd.get_cpuid2(kvm_bindings::KVM_MAX_CPUID_ENTRIES)?;+ validate_cpuid_count(cpuid.as_slice().len())?;+ validate_snapshot_cpuid_features(cpuid.as_slice())?;+ Ok(cpuid)+ };+ read_cpuid(&self.fd)?;+ let xsave_size = self.xsave_size()?;+ self.has_tsc_offset()?;+ let base_msr_indices = self.fd.snapshot.msr_indices()?;+ let tsc_khz = get_tsc_khz(&self.fd)?;+ let mut xsave = Self::xsave_buffer(xsave_size)?;+ let mp_state = self.fd.get_mp_state()?;+ let events = self.fd.get_vcpu_events()?;+ let cpuid = read_cpuid(&self.fd)?;+ let cpuid = cpuid.as_slice();+ let sregs = self.fd.get_sregs()?;+ validate_snapshot_paging(&sregs)?;+ if xsave_size == 0 {+ // SAFETY: this branch uses the fixed-size GET_XSAVE ioctl.+ unsafe { xsave.as_mut_fam_struct().xsave = self.fd.get_xsave()? };+ } else {+ // SAFETY: buffer covers the VM's KVM_CAP_XSAVE2 size. The API+ // contract forbids enabling dynamic XSTATE permissions later.+ unsafe { self.fd.get_xsave2(&mut xsave) }?;+ }+ let mut words = Vec::with_capacity(XSAVE_REGION_WORDS + xsave.as_slice().len());+ words.extend_from_slice(&xsave.as_fam_struct_ref().xsave.region);+ words.extend_from_slice(xsave.as_slice());+ // Sample timer MSRs before LAPIC state so an intervening timer+ // expiration can be reflected in the captured interrupt state.+ let mut msrs = snapshot_msrs(&self.fd, base_msr_indices)?;+ msrs.extend(snapshot_msrs(+ &self.fd,+ &extra_cpuid_gated_msr_indices(cpuid),+ )?);+ if msrs.len() > MAX_SNAPSHOT_MSR_ENTRIES {+ return Err(io::Error::other("snapshot MSR count exceeds the limit"));+ }+ let mut state = crate::X86VcpuState {+ regs: self.fd.get_regs()?,+ sregs,+ fpu: self.fd.get_fpu()?,+ cpuid: cpuid.to_vec(),+ msrs,+ xsave: words,+ xcrs: self.fd.get_xcrs()?,+ debug_regs: self.fd.get_debug_regs()?,+ events,+ mp_state,+ lapic: self.fd.get_lapic()?,+ tsc_khz,+ };+ self.commit_saved_state(&mut state.msrs, state.tsc_khz)?;+ Ok(state)+ };+ save().map_err(|source| Error::ConfigureVcpu {+ id: self.id,+ operation: "save CPU state",+ source,+ })+ }++ #[cfg(test)]+ pub(super) fn save_state_with_pending_io(&mut self) -> Result<crate::X86VcpuState> {+ self.pending_io.0 = true;+ let state = self.save_state();+ self.pending_io.0 = false;+ state+ }++ /// Overwrites a fresh, never-entered vCPU; never executes guest code.+ /// Read-only validation and capability probes permit a retry on failure.+ /// Once `KVM_SET_CPUID2` is attempted, any error can leave the vCPU partially+ /// mutated, including a read error during TSC restore. Discard the destination VM.+ ///+ /// CPUID must precede CPUID-gated MSRs/XCRs.+ /// TSC scaling precedes TSC writes; SREGS precedes REGS and establishes mode+ /// and APIC base. LAPIC precedes MSRs so its timer setup cannot clobber the+ /// saved TSC deadline. TSC_ADJUST precedes the TSC offset. The async page-fault+ /// interrupt vector precedes its enable MSR, and SGX launch key hashes precede+ /// IA32_FEATURE_CONTROL. IA32_PERF_CAPABILITIES precedes the other PMU MSRs.+ /// MSRs (including XSS/XFD) precede XCRS/XSAVE. KVM_SET_XSAVE restores the+ /// authoritative x87, SSE and extended state.+ /// Debug/REGS follow mode setup, MP state and events are last (LAPIC/SREGS+ /// can change pending events).+ ///+ /// MSR_KVM_WALL_CLOCK and MSR_KVM_WALL_CLOCK_NEW update the VM-global+ /// wall_clock and write the epoch into guest RAM. Call+ /// [`crate::X86Vm::restore_before_vcpus`] before restoring any vCPU.+ pub fn restore_state(&mut self, state: &crate::X86VcpuState) -> Result<()> {+ let mut restore = || -> io::Result<()> {+ let invalid = |message| io::Error::new(io::ErrorKind::InvalidInput, message);+ if self.entered || self.pending_io.0 || self.restore_started {+ return Err(invalid("restore requires a fresh, never-entered vCPU"));+ }+ let cpuid = snapshot_cpuid(&state.cpuid)?;+ validate_snapshot_cpuid_features(&state.cpuid)?;+ validate_snapshot_paging(&state.sregs)?;+ if state.tsc_khz == 0 {+ return Err(invalid("TSC frequency must be nonzero"));+ }+ validate_restore_msrs(&state.msrs, &state.cpuid)?;+ let xsave_size = self.xsave_size()?;+ self.has_tsc_offset()?;+ let mut xsave = Self::xsave_buffer(xsave_size)?;+ if state.xsave.len() != XSAVE_REGION_WORDS + xsave.as_slice().len()+ || state.xcrs.nr_xcrs as usize > state.xcrs.xcrs.len()+ || state.xcrs.flags != 0+ {+ return Err(invalid("invalid XSAVE/XCR snapshot shape"));+ }+ // SAFETY: the destination-sized buffer and length check above+ // guarantee matching slice lengths. Copying the fixed region does+ // not change the flexible-array length or its allocation.+ unsafe {+ xsave+ .as_mut_fam_struct()+ .xsave+ .region+ .copy_from_slice(&state.xsave[..XSAVE_REGION_WORDS])+ };+ xsave+ .as_mut_slice()+ .copy_from_slice(&state.xsave[XSAVE_REGION_WORDS..]);+ let current_khz = get_tsc_khz(&self.fd)?;+ let plan = order_msrs_for_restore(&state.msrs);+ self.fd.clear_tsc_save_anchor();+ self.restore_started = true;+ self.fd.set_cpuid2(&cpuid)?;+ if current_khz != state.tsc_khz {+ self.fd.set_tsc_khz(state.tsc_khz)?;+ }+ self.fd.set_sregs(&state.sregs)?;+ self.fd.set_lapic(&state.lapic)?;+ self.write_msr_batches(&plan.before_tsc)?;+ if let Some(tsc) = plan.tsc {+ self.restore_tsc(tsc, state.tsc_khz)?;+ }+ self.write_msr_batches(&plan.after_tsc)?;+ if state.xcrs.nr_xcrs > 0 {+ self.fd.set_xcrs(&state.xcrs)?;+ }+ // SAFETY: destination-sized allocation, checked above; no dynamic+ // XSTATE permission changes are allowed during the vCPU lifetime.+ unsafe {+ if xsave_size == 0 {+ self.fd.set_xsave(&xsave.as_fam_struct_ref().xsave)+ } else {+ self.fd.set_xsave2(&xsave)+ }+ }?;+ self.fd.set_debug_regs(&state.debug_regs)?;+ self.fd.set_regs(&state.regs)?;+ self.fd.set_mp_state(state.mp_state)?;+ self.fd.set_vcpu_events(&state.events)?;+ // Clear host-side run controls, not part of the guest CPU image.+ self.fd.set_kvm_immediate_exit(0);+ Ok(())+ };+ restore().map_err(|source| Error::ConfigureVcpu {+ id: self.id,+ operation: "restore CPU state",+ source,+ })+ }++ fn xsave_buffer(xsave_size: usize) -> io::Result<kvm_bindings::Xsave> {+ let size = xsave_size.max(size_of::<kvm_bindings::kvm_xsave>());+ let extra_words = (size - size_of::<kvm_bindings::kvm_xsave>()).div_ceil(size_of::<u32>());+ kvm_bindings::Xsave::new(extra_words)+ .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))+ }+}+#[cfg(test)]mod tests {+ use super::super::{+ KvmVm,+ features::{build_snapshot_msr_indices, kvm_msr_index_list},+ };use super::*;+ fn snapshot_cpu(vm: &KvmVm) -> KvmVcpu {+ let mut cpuid = vm.supported_cpuid().to_vec();+ for entry in &mut cpuid {+ if entry.leaf == 7 && (!entry.subleaf_required || entry.subleaf == 0) {+ entry.ecx &= !(1 << 7); // CET shadow stack is outside the snapshot contract.+ }+ }+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(&cpuid, &[]).unwrap();+ cpu+ }++ #[test]+ fn cached_io_errors_preserve_errno_or_kind_and_message() {+ for original in [+ io::Error::from_raw_os_error(libc::EPERM),+ io::Error::new(io::ErrorKind::InvalidData, "invalid size"),+ ] {+ let errno = original.raw_os_error();+ let kind = original.kind();+ let message = original.to_string();+ let cached = CachedIoError::from_io(original);+ for error in [cached.to_io(), cached.to_io()] {+ assert_eq!(error.raw_os_error(), errno);+ assert_eq!(error.kind(), kind);+ assert_eq!(error.to_string(), message);+ }+ }+ }++ #[test]+ fn tsc_khz_ioctl_parses_frequency_and_preserves_errno() {+ assert_eq!(KVM_GET_TSC_KHZ, 0xaea3);+ let parse = |ret| parse_tsc_khz(ret, io::Error::from_raw_os_error(libc::EPERM));+ assert_eq!(parse(1).unwrap(), 1);+ assert_eq!(parse(i32::MAX).unwrap(), i32::MAX as u32);+ assert_eq!(+ parse(0).unwrap_err().to_string(),+ "KVM_GET_TSC_KHZ returned zero"+ );+ assert_eq!(parse(-1).unwrap_err().raw_os_error(), Some(libc::EPERM));+ assert_eq!(+ parse_tsc_khz(-1, io::Error::from_raw_os_error(0))+ .unwrap_err()+ .raw_os_error(),+ None+ );+ }++ #[test]+ fn clock_delta_converts_with_wide_arithmetic_and_wrapping_tsc() {+ assert_eq!(ns_to_tsc_cycles(1_500_000, 1234), 1851);+ assert_eq!(ns_to_tsc_cycles(999_999, 1), 0);+ assert_eq!(ns_to_tsc_cycles(u64::MAX, 1_000_000), u64::MAX);+ assert_eq!(ns_to_tsc_cycles(u64::MAX, 2_000_000), u64::MAX - 1);+ assert_eq!(anchored_scaled_tsc(10, 4, 9, 1_000_000), None);+ assert_eq!(anchored_scaled_tsc(10, 9, 9, 1_000_000), Some(10));+ assert_eq!(anchored_scaled_tsc(2, 9, 5, 1_000_000), Some(u64::MAX - 1));+ }++ #[test]+ fn clock_anchor_handles_a_short_forward_wraparound() {+ assert_eq!(anchored_scaled_tsc(10, 2, u64::MAX - 1, 1_000_000), Some(6));+ }++ #[test]+ fn tsc_sampling_handles_a_window_that_wraps_past_u64_max() {+ let tsc =+ sample_scaled_tsc_with(u64::MAX - 5, 1_000_000, || Ok((u64::MAX - 3, 10, 4))).unwrap();+ assert_eq!(tsc, 4);+ }++ #[test]+ fn tsc_sampling_retries_midpoints_before_the_anchor() {+ let mut windows = [+ (10, 100, 20),+ (999_994, 200, 1_000_002),+ (1_000_002, 600_002, 2_000_002),+ ]+ .into_iter();+ let tsc =+ sample_scaled_tsc_with(1_000_000, 1_000_000, || Ok(windows.next().unwrap())).unwrap();+ assert_eq!(tsc, 100_000);+ }++ #[test]+ fn tsc_sampling_errors_after_five_midpoints_before_the_anchor() {+ let mut attempts = 0;+ let error = sample_scaled_tsc_with(100, 1_000_000, || {+ attempts += 1;+ Ok((10, 50, 20))+ })+ .unwrap_err();+ assert_eq!(attempts, 5);+ assert_eq!(+ error.to_string(),+ "KVM clock moved backward during TSC sampling"+ );+ }++ #[test]+ fn tsc_sampling_uses_the_narrowest_of_five_wide_windows() {+ let mut windows = [+ (0, 10_000_000, 4_000_000),+ (4_000_000, 10_000_000, 7_000_000),+ (7_000_000, 10_000_000, 8_500_000),+ (8_500_000, 10_000_000, 12_000_000),+ (12_000_000, 15_000_000, 14_500_000),+ ]+ .into_iter();+ let tsc = sample_scaled_tsc_with(0, 1_000_000, || Ok(windows.next().unwrap())).unwrap();+ assert_eq!(tsc, 2_250_000);+ assert_eq!(windows.next(), None);+ }++ #[test]+ fn tsc_sampling_propagates_ioctl_errors_after_a_wide_window() {+ let mut windows = [+ Ok((0, 3_000_000, 2_000_000)),+ Err(io::Error::from_raw_os_error(libc::EIO)),+ ]+ .into_iter();+ let error = sample_scaled_tsc_with(0, 1_000_000, || windows.next().unwrap()).unwrap_err();+ assert_eq!(error.raw_os_error(), Some(libc::EIO));+ }++ #[test]+ fn clock_anchors_reuse_each_frequency_independently() {+ let mut per_freq = HashMap::new();+ let anchor_ns = 1_000_000;+ for (khz, sampled_clock_ns, scaled_now, expected) in+ [(1000, 2_000_000, 3000, 2000), (2000, 3_000_000, 5000, 1000)]+ {+ assert_eq!(+ scaled_tsc_anchor(&mut per_freq, khz, || {+ Ok(anchored_scaled_tsc(+ scaled_now,+ sampled_clock_ns,+ anchor_ns,+ khz,+ ))+ })+ .unwrap(),+ Some(expected)+ );+ }+ assert_eq!(+ scaled_tsc_anchor(&mut per_freq, 2000, || panic!("frequency already sampled")).unwrap(),+ Some(1000)+ );+ assert_eq!(per_freq, HashMap::from([(1000, 2000), (2000, 1000)]));+ }++ #[test]+ fn tsc_save_requires_vm_clock_and_rejects_duplicate_vcpus() {+ let anchor = TscSaveAnchor::default();+ let no_vm = "save VM state before saving vCPU state";+ let duplicate = "save VM state before recapturing vCPU state";+ let must_reject_commit = |message| {+ let error = anchor+ .commit_vcpu_save(0, |_, _| panic!("invalid capture reached normalization"))+ .unwrap_err();+ assert_eq!(error.to_string(), message);+ };+ assert_eq!(anchor.check_vcpu_save(0).unwrap_err().to_string(), no_vm);+ must_reject_commit(no_vm);++ // Even a successful capture without TSC normalization consumes its slot.+ anchor.record_vm_clock(1_000);+ anchor.check_vcpu_save(0).unwrap();+ anchor.commit_vcpu_save(0, |_, _| Ok(())).unwrap();+ assert_eq!(+ anchor.check_vcpu_save(0).unwrap_err().to_string(),+ duplicate+ );+ must_reject_commit(duplicate);++ anchor.check_vcpu_save(1).unwrap();+ anchor.clear();+ assert!(!anchor.active.load(Ordering::Acquire));+ assert_eq!(anchor.check_vcpu_save(1).unwrap_err().to_string(), no_vm);+ must_reject_commit(no_vm);+ anchor.record_vm_clock(2_000);+ anchor.check_vcpu_save(0).unwrap();+ anchor.commit_vcpu_save(0, |_, _| Ok(())).unwrap();+ }++ #[test]+ fn tsc_save_shares_tsc_and_reanchors_each_round() {+ let anchor = TscSaveAnchor::default();+ let tsc_khz = 1_000_000;+ let capture = |id, sampled_clock_ns, sampled_tsc| {+ let mut tsc = None;+ anchor+ .commit_vcpu_save(id, |clock_ns, per_freq| {+ tsc = scaled_tsc_anchor(per_freq, tsc_khz, || {+ Ok(anchored_scaled_tsc(+ sampled_tsc,+ sampled_clock_ns,+ clock_ns,+ tsc_khz,+ ))+ })?;+ Ok(())+ })+ .unwrap();+ tsc.unwrap()+ };++ anchor.record_vm_clock(1_000);+ assert_eq!(capture(0, 1_100, 10_100), 10_000);+ assert_eq!(capture(1, 1_200, 10_201), 10_000);++ anchor.record_vm_clock(2_000);+ assert_eq!(capture(0, 2_100, 11_100), 11_000);+ assert_eq!(capture(1, 2_200, 11_201), 11_000);+ }++ #[test]+ fn failed_tsc_save_preserves_the_round_for_retry() {+ let anchor = TscSaveAnchor::default();+ anchor.record_vm_clock(1_000);+ let error = anchor+ .commit_vcpu_save(0, |_, per_freq| {+ scaled_tsc_anchor(per_freq, 1_000, || Err(io::Error::other("sample failed")))?;+ Ok(())+ })+ .unwrap_err();+ assert_eq!(error.to_string(), "sample failed");++ anchor+ .commit_vcpu_save(1, |clock_ns, per_freq| {+ assert_eq!(clock_ns, 1_000);+ assert_eq!(+ scaled_tsc_anchor(per_freq, 1_000, || Ok(Some(900)))?,+ Some(900)+ );+ Ok(())+ })+ .unwrap();+ anchor.check_vcpu_save(0).unwrap();+ anchor+ .commit_vcpu_save(0, |clock_ns, per_freq| {+ assert_eq!(clock_ns, 1_000);+ assert_eq!(+ scaled_tsc_anchor(per_freq, 1_000, || panic!("frequency already sampled"))?,+ Some(900)+ );+ Ok(())+ })+ .unwrap();+ }++ #[test]+ fn paged_32bit_pae_requires_pg_and_pae_without_lma() {+ for pg in [false, true] {+ for pae in [false, true] {+ for lma in [false, true] {+ let sregs = kvm_sregs {+ cr0: u64::from(pg) << 31,+ cr4: u64::from(pae) << 5,+ efer: u64::from(lma) << 10,+ ..Default::default()+ };+ assert_eq!(+ is_paged_32bit_pae(&sregs),+ pg && pae && !lma,+ "{pg}, {pae}, {lma}"+ );+ }+ }+ }+ }+#[repr(C)]#[derive(Default)]struct ExitBuffer {@@ -351,6 +1333,508 @@ mod tests {}}+ #[test]+ fn kvm_tsc_device_attr_ioctl_numbers() {+ // _IOW packs the write bit, structure size, KVMIO type and request.+ let iow = |nr: libc::c_ulong| {+ (1 << 30) | ((size_of::<kvm_device_attr>() as libc::c_ulong) << 16) | (0xae << 8) | nr+ };+ assert_eq!(KVM_SET_DEVICE_ATTR, iow(0xe1));+ assert_eq!(KVM_GET_DEVICE_ATTR, iow(0xe2));+ assert_eq!(KVM_HAS_DEVICE_ATTR, iow(0xe3));+ assert_eq!((KVM_VCPU_TSC_CTRL, KVM_VCPU_TSC_OFFSET), (0, 0));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_save_rejects_unconfigured_empty_cpuid() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ vm.save_state().unwrap();+ let error = cpu.save_state().unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "save CPU state", ref source, .. }+ if source.kind() == io::ErrorKind::InvalidInput && source.to_string() == "invalid CPUID count")+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_round_trips_with_guest_pmu_disabled() {+ for (clear_pmu, clear_pdcm) in [(true, false), (true, true), (false, true)] {+ let (platform, state) = {+ let vm = KvmVm::new().unwrap();+ let mut cpuid = vm.supported_cpuid().to_vec();+ for entry in &mut cpuid {+ match entry.leaf {+ 1 if clear_pdcm => entry.ecx &= !(1 << 15),+ 0xa if clear_pmu => entry.eax &= !0xff,+ 7 if !entry.subleaf_required || entry.subleaf == 0 => {+ entry.ecx &= !(1 << 7); // SHSTK is outside the snapshot contract.+ }+ _ => {}+ }+ }+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(&cpuid, &[]).unwrap();+ (vm.save_state().unwrap(), cpu.save_state().unwrap())+ };+ assert!(+ state.msrs.iter().all(|entry| entry.index != 0x345),+ "captured IA32_PERF_CAPABILITIES (clear_pmu={clear_pmu}, clear_pdcm={clear_pdcm})"+ );++ let vm = KvmVm::new().unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.restore_state(&state).unwrap();+ vm.restore_after_vcpus(&platform).unwrap();+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_save_rejects_paged_32bit_pae() {+ const CR0_PE: u64 = 1;+ const CR0_PG: u64 = 1 << 31;+ const CR4_PAE: u64 = 1 << 5;+ const EFER_LMA: u64 = 1 << 10;++ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ let mut sregs = cpu.fd.get_sregs().unwrap();+ sregs.cr0 |= CR0_PE | CR0_PG;+ sregs.cr4 |= CR4_PAE;+ sregs.efer &= !EFER_LMA;+ cpu.fd.set_sregs(&sregs).unwrap();+ vm.save_state().unwrap();++ let error = cpu.save_state().unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "save CPU state", ref source, .. }+ if source.kind() == io::ErrorKind::Unsupported+ && source.to_string() == "32-bit PAE paging state is unsupported because SREGS omits PDPTRs"),+ "{error:?}"+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_xsave_probe_error_preflights_save_and_restore_without_blocking_run() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ let original = state.regs;+ state.regs.rax ^= 1;+ cpu.xsave_size = Err(CachedIoError::from_io(io::Error::from_raw_os_error(+ libc::EPERM,+ )));+ vm.save_state().unwrap();+ for error in [+ cpu.save_state().unwrap_err(),+ cpu.restore_state(&state).unwrap_err(),+ ] {+ assert!(matches!(error, Error::ConfigureVcpu { ref source, .. }+ if source.raw_os_error() == Some(libc::EPERM)));+ }+ assert!(!cpu.restore_started);+ assert_eq!(cpu.fd.get_regs().unwrap(), original);+ cpu.fd.set_kvm_immediate_exit(1);+ assert!(matches!(cpu.run().unwrap(), VcpuExit::Interrupted));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_rejects_unsupported_cpu_state_before_writes() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ let platform = vm.save_state().unwrap();+ let valid = cpu.save_state().unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ let mut shstk = valid.clone();+ shstk.cpuid = vec![kvm_bindings::kvm_cpuid_entry2 {+ function: 7,+ ecx: 1 << 7,+ ..Default::default()+ }];+ let mut pae = valid.clone();+ pae.sregs.cr0 |= 1 << 31;+ pae.sregs.cr4 |= 1 << 5;+ pae.sregs.efer &= !(1 << 10);+ let mut zero_frequency = valid.clone();+ zero_frequency.tsc_khz = 0;+ let mut excluded_msr = valid.clone();+ excluded_msr.msrs.push(kvm_msr_entry {+ index: 0x800,+ ..Default::default()+ });+ for (mut state, kind, message) in [+ (+ shstk,+ io::ErrorKind::Unsupported,+ "CET shadow stack (SHSTK) state cannot be snapshotted",+ ),+ (+ pae,+ io::ErrorKind::Unsupported,+ "32-bit PAE paging state is unsupported because SREGS omits PDPTRs",+ ),+ (+ zero_frequency,+ io::ErrorKind::InvalidInput,+ "TSC frequency must be nonzero",+ ),+ (+ excluded_msr,+ io::ErrorKind::InvalidInput,+ "MSR index 0x800 is excluded from snapshots",+ ),+ ] {+ state.regs.rax ^= 1;+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "restore CPU state", ref source, .. }+ if source.kind() == kind && source.to_string() == message),+ "{error:?}"+ );+ assert!(!cpu.restore_started);+ assert_eq!(cpu.fd.get_regs().unwrap(), valid.regs);+ assert_eq!(+ cpu.fd+ .get_cpuid2(kvm_bindings::KVM_MAX_CPUID_ENTRIES)+ .unwrap()+ .as_slice(),+ valid.cpuid+ );+ }+ cpu.restore_state(&valid).unwrap();+ assert!(cpu.restore_started);+ let error = cpu.restore_state(&valid).unwrap_err();+ assert!(matches!(error, Error::ConfigureVcpu { ref source, .. }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.to_string() == "restore requires a fresh, never-entered vCPU"));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_rejects_invalid_cpuid_before_writing_registers() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ let original = cpu.fd.get_regs().unwrap();+ let original_cpuid = state.cpuid.clone();+ state.regs.rax = original.rax ^ 1;+ for count in [0, kvm_bindings::KVM_MAX_CPUID_ENTRIES + 1] {+ state.cpuid.resize(count, original_cpuid[0]);+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(matches!(error, Error::ConfigureVcpu { ref source, .. }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.to_string() == "invalid CPUID count"));+ assert_eq!(cpu.fd.get_regs().unwrap(), original);+ assert!(!cpu.restore_started);+ assert_eq!(+ cpu.fd+ .get_cpuid2(kvm_bindings::KVM_MAX_CPUID_ENTRIES)+ .unwrap()+ .as_slice(),+ original_cpuid+ );+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_skips_set_xcrs_when_nr_xcrs_is_zero() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ state.xcrs.nr_xcrs = 0;+ state.xcrs.flags = 1;+ let original = cpu.fd.get_regs().unwrap();+ state.regs.rax = original.rax ^ 1;+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(matches!(error, Error::ConfigureVcpu { ref source, .. }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.to_string() == "invalid XSAVE/XCR snapshot shape"));+ assert_eq!(cpu.fd.get_regs().unwrap(), original);++ state.xcrs.flags = 0;+ cpu.restore_state(&state).unwrap();+ assert_eq!(cpu.fd.get_regs().unwrap(), state.regs);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_rejects_xsave_and_xcr_shapes_before_writing_registers() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let valid = cpu.save_state().unwrap();+ let original = cpu.fd.get_regs().unwrap();+ for case in 0..4 {+ let mut state = valid.clone();+ state.regs.rax = original.rax ^ 0x1234;+ match case {+ 0 => state.xsave.clear(),+ 1 => {+ state.xsave.pop();+ }+ 2 => state.xsave.push(0),+ 3 => state.xcrs.nr_xcrs = state.xcrs.xcrs.len() as u32 + 1,+ _ => unreachable!(),+ }+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { id: 0, operation: "restore CPU state", ref source }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.to_string() == "invalid XSAVE/XCR snapshot shape"),+ "{error:?}"+ );+ assert_eq!(cpu.fd.get_regs().unwrap(), original);+ }+ // A real capture is still accepted after every pre-write rejection.+ cpu.restore_state(&valid).unwrap();+ assert_eq!(cpu.fd.get_regs().unwrap(), valid.regs);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_rejects_a_cpu_after_interrupted_entry() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let state = cpu.save_state().unwrap();+ cpu.fd.set_kvm_immediate_exit(1);+ assert!(matches!(cpu.run().unwrap(), VcpuExit::Interrupted));+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(matches!(error, Error::ConfigureVcpu { ref source, .. }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.to_string() == "restore requires a fresh, never-entered vCPU"));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_handles_empty_and_multiple_msr_batches() {+ let mut failures = Vec::new();+ for count in [+ 0,+ kvm_bindings::KVM_MAX_MSR_ENTRIES - 1,+ kvm_bindings::KVM_MAX_MSR_ENTRIES,+ kvm_bindings::KVM_MAX_MSR_ENTRIES + 1,+ MAX_SNAPSHOT_MSR_ENTRIES,+ ] {+ // Failed restores are not transactional: use a fresh destination+ // for each boundary and report all failures, not just the first.+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ state.msrs = (0..count)+ .map(|i| kvm_bindings::kvm_msr_entry {+ index: 0xc0000102,+ data: (i + 1) as u64,+ ..Default::default()+ })+ .collect();+ // The codec's 4096-entry ceiling exceeds one KVM ioctl batch.+ let encoded = postcard::to_allocvec(&state).unwrap();+ let decoded = postcard::from_bytes(&encoded).unwrap();+ if let Err(error) = cpu.restore_state(&decoded) {+ failures.push((count, error));+ continue;+ }+ vm.save_state().unwrap();+ let actual = cpu.save_state().unwrap();+ assert_eq!(+ actual+ .msrs+ .iter()+ .find(|e| e.index == 0xc0000102)+ .unwrap()+ .data,+ count as u64+ );+ }+ assert!(+ failures.is_empty(),+ "MSR batch restore failures: {failures:?}"+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_matches_kvm_for_a_changed_tsc_scale() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ assert!(state.tsc_khz > 1);+ let original = state.tsc_khz;+ state.tsc_khz /= 2;+ // Query the real ioctl as the oracle: hosts without TSC scaling+ // reject a lower rate. Restore must preserve that failure too.+ let expected = cpu.fd.set_tsc_khz(state.tsc_khz);+ cpu.fd.set_tsc_khz(original).unwrap();+ match expected {+ Ok(()) => {+ cpu.restore_state(&state).unwrap();+ assert_eq!(get_tsc_khz(&cpu.fd).unwrap(), state.tsc_khz);+ }+ Err(expected) => {+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "restore CPU state", ref source, .. }+ if source.raw_os_error() == Some(expected.errno()))+ );+ }+ }+ }++ const MSR_MTRR_DEF_TYPE: u32 = 0x2ff;++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_reports_the_first_rejected_msr() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ state.msrs = vec![kvm_bindings::kvm_msr_entry {+ index: MSR_MTRR_DEF_TYPE,+ data: u64::MAX,+ ..Default::default()+ }];+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "restore CPU state", ref source, .. }+ if source.to_string() == "KVM wrote 0 of 1 MSRs; first rejected index 0x2ff")+ );+ assert!(cpu.restore_started);+ state.msrs.clear();+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(matches!(error, Error::ConfigureVcpu { ref source, .. }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.to_string() == "restore requires a fresh, never-entered vCPU"));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_reports_first_rejected_msr_in_second_batch() {+ const FS_BASE: u32 = 0xc000_0100;+ const KERNEL_GS_BASE: u32 = 0xc000_0102;+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ state.msrs = (1..=(MAX_MSR_BATCH_ENTRIES + 2))+ .map(|data| kvm_msr_entry {+ index: KERNEL_GS_BASE,+ data: data as u64,+ ..Default::default()+ })+ .collect();+ state.msrs[MAX_MSR_BATCH_ENTRIES + 1].index = FS_BASE;+ state.msrs.push(kvm_msr_entry {+ index: MSR_MTRR_DEF_TYPE,+ data: u64::MAX,+ ..Default::default()+ });+ let error = cpu.restore_state(&state).unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "restore CPU state", ref source, .. }+ if source.to_string() == "KVM wrote 2 of 3 MSRs; first rejected index 0x2ff")+ );+ let actual = snapshot_msrs(&cpu.fd, &[KERNEL_GS_BASE, FS_BASE]).unwrap();+ assert_eq!(actual, state.msrs[MAX_MSR_BATCH_ENTRIES..][..2]);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_vcpus_share_the_kvm_advertised_msr_index_cache() {+ let vm = KvmVm::new().unwrap();+ let first = vm.create_vcpu(0).unwrap();+ let indices = Arc::clone(first.fd.snapshot.msr_indices().unwrap());+ // One worker owns at most one reserved kick signal at a time.+ drop(first);+ let second = vm.create_vcpu(1).unwrap();+ let advertised = kvm_msr_index_list(&kvm_ioctls::Kvm::new().unwrap()).unwrap();+ assert_eq!(indices, build_snapshot_msr_indices(&advertised));+ assert!(Arc::ptr_eq(+ &indices,+ second.fd.snapshot.msr_indices().unwrap()+ ));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_legacy_xsave_capture_uses_the_fixed_region() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ // Exercise the pre-XSAVE2 fallback on an XSAVE2-capable host too.+ // GET_XSAVE is always the fixed-size ioctl; do not issue SET_XSAVE2+ // with a buffer smaller than the real destination's capability.+ cpu.xsave_size = Ok(0);+ let fixed = cpu.fd.get_xsave().unwrap();+ vm.save_state().unwrap();+ let state = cpu.save_state().unwrap();+ assert_eq!(state.xsave.len(), XSAVE_REGION_WORDS);+ assert_eq!(state.xsave, fixed.region);+ for extra_bytes in [1, 4, 5] {+ let xsave_size = size_of::<kvm_bindings::kvm_xsave>() + extra_bytes;+ assert_eq!(+ KvmVcpu::xsave_buffer(xsave_size).unwrap().as_slice().len(),+ extra_bytes.div_ceil(4)+ );+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_round_trips_tsc_via_msr_without_offset_controls() {+ use std::time::Instant;++ let vm = KvmVm::new().unwrap();+ let mut cpu = snapshot_cpu(&vm);+ cpu.tsc_offset = Some(false);+ cpu.write_msr_batches(&[kvm_msr_entry {+ index: MSR_IA32_TSC,+ data: 1 << 40,+ ..Default::default()+ }])+ .unwrap();+ let read_tsc = |cpu: &KvmVcpu| snapshot_msrs(&cpu.fd, &[MSR_IA32_TSC]).unwrap()[0].data;+ let platform = vm.save_state().unwrap();+ let before = read_tsc(&cpu);+ let state = cpu.save_state().unwrap();+ let error = cpu.save_state().unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "save CPU state", ref source, .. }+ if source.to_string() == "save VM state before recapturing vCPU state")+ );+ let saved_tsc = state+ .msrs+ .iter()+ .find(|entry| entry.index == MSR_IA32_TSC)+ .unwrap()+ .data;+ assert!((before..=read_tsc(&cpu)).contains(&saved_tsc));+ drop(cpu);++ let vm = KvmVm::new().unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.tsc_offset = Some(false);+ let before_restore = Instant::now();+ cpu.restore_state(&state).unwrap();+ let restored_tsc = read_tsc(&cpu);+ let elapsed = before_restore.elapsed() + std::time::Duration::from_millis(5);+ let max_cycles = ns_to_tsc_cycles(elapsed.as_nanos() as u64, state.tsc_khz);+ assert!(restored_tsc.wrapping_sub(saved_tsc) <= max_cycles);+ }+#[test]fn completion_consumes_pending_io_only_after_interrupted_reentry() {let mut pending = PendingIo::default();diff --git a/src/hypervisor/src/kvm/vm.rs b/src/hypervisor/src/kvm/vm.rsindex 7f8d4a072..df6f254d8 100644--- a/src/hypervisor/src/kvm/vm.rs+++ b/src/hypervisor/src/kvm/vm.rs@@ -1,26 +1,60 @@// Copyright 2026 BoxLite Contributors// SPDX-License-Identifier: Apache-2.0-use std::{io, os::fd::AsRawFd, sync::Mutex};+use std::{+ io,+ os::fd::AsRawFd,+ sync::{Arc, Mutex},+};-use kvm_bindings::{KVM_API_VERSION, KVM_PIT_SPEAKER_DUMMY, kvm_pit_config};+use kvm_bindings::{+ KVM_API_VERSION, KVM_IRQCHIP_IOAPIC, KVM_IRQCHIP_PIC_MASTER, KVM_IRQCHIP_PIC_SLAVE,+ KVM_PIT_SPEAKER_DUMMY, kvm_clock_data, kvm_pit_config,+};use kvm_ioctls::{Cap, Kvm, VmFd};use super::KvmVcpu;+use super::features::{build_snapshot_msr_indices, kvm_msr_index_list};use super::memory::{MAX_PAGES_PER_SLOT, MemorySlots};+use super::vcpu::{CachedIoError, VcpuSnapshotShared};use crate::{Error, MemoryRegion, Result};/// An x86_64 KVM VM with an in-kernel interrupt controller and timer.////// Memory backing remains owned by the caller, under the same lifetime contract-/// as [`crate::Vm::map_memory`]. Dropping this value closes the VM descriptor.+/// as [`crate::Vm::map_memory`]. vCPUs share the VM descriptor for clock sampling.#[derive(Debug)]pub struct KvmVm {- fd: VmFd,+ fd: Arc<VmFd>,slots: Mutex<MemorySlots>,run_size: usize,kick_signal: i32,cpuid: Vec<crate::X86CpuidEntry>,+ vcpu_snapshot: Arc<VcpuSnapshotShared>,+}++fn parse_xsave2_size(ret: i32, last_err: io::Error) -> io::Result<usize> {+ if ret < 0 {+ return Err(match last_err.raw_os_error() {+ Some(errno) if errno != 0 => last_err,+ _ => io::Error::other(format!(+ "KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) failed with {ret}"+ )),+ });+ }+ let size = ret as usize;+ let legacy_size = size_of::<kvm_bindings::kvm_xsave>();+ if size != 0 && size < legacy_size {+ return Err(io::Error::other(format!(+ "KVM_CAP_XSAVE2 returned {size} bytes, below the {legacy_size}-byte legacy size"+ )));+ }+ Ok(size)+}++fn xsave2_size(fd: &VmFd) -> io::Result<usize> {+ let ret = fd.check_extension_int(Cap::Xsave2);+ parse_xsave2_size(ret, io::Error::last_os_error())}/// A checked KVM system handle and the supported CPUID for a prospective VM.@@ -100,12 +134,18 @@ impl PreparedKvm {..Default::default()}).map_err(io::Error::from)?;+ let msr_indices = kvm_msr_index_list(&kvm)+ .map(|list| build_snapshot_msr_indices(&list))+ .map_err(CachedIoError::from_io);+ let fd = Arc::new(fd);+ let vcpu_snapshot = Arc::new(VcpuSnapshotShared::new(Arc::clone(&fd), msr_indices));Ok(KvmVm {fd,slots: Mutex::new(MemorySlots::new(kvm.get_nr_memslots(), page_size as usize)),run_size: kvm.get_vcpu_mmap_size().map_err(io::Error::from)?,kick_signal,cpuid,+ vcpu_snapshot,})}}@@ -133,6 +173,80 @@ impl KvmVm {prepared.create().map_err(Error::CreateVm)}+ /// Captures the global platform and starts a new snapshot round. Stop all+ /// vCPUs and IRQ producers, complete userspace I/O, then save this image+ /// before capturing each vCPU once in the round.+ pub fn save_state(&self) -> Result<crate::X86VmState> {+ let capture = || -> io::Result<_> {+ let mut irqchips = std::array::from_fn(|chip_id| kvm_bindings::kvm_irqchip {+ chip_id: chip_id as u32,+ ..Default::default()+ });+ for chip in &mut irqchips {+ self.fd.get_irqchip(chip).map_err(io::Error::from)?;+ }+ Ok(crate::X86VmState {+ // SAFETY: each buffer was fully zeroed before GET_IRQCHIP.+ irqchips: irqchips.map(|chip| unsafe {+ match chip.chip_id {+ 0 | 1 => crate::X86IrqchipState::pic(chip.chip_id, chip.chip.pic),+ _ => crate::X86IrqchipState::ioapic(chip.chip.ioapic),+ }+ }),+ pit: Some(self.fd.get_pit2().map_err(io::Error::from)?),+ clock: self.fd.get_clock().map_err(io::Error::from)?,+ })+ };+ let state = capture().map_err(|source| Error::vm_state("save", source))?;+ self.vcpu_snapshot.record_tsc_save_clock(state.clock.clock);+ Ok(state)+ }++ /// Sets the VM clock offset after RAM mapping, before restoring any vCPU.+ pub fn restore_before_vcpus(&self, state: &crate::X86VmState) -> Result<()> {+ // Zero flags exclude suspend time and are accepted by older kernels.+ self.fd+ .set_clock(&kvm_clock_data {+ flags: 0,+ ..state.clock+ })+ .map_err(|source| Error::vm_state("restore", source.into()))?;+ self.vcpu_snapshot.clear_tsc_save_anchor();+ self.vcpu_snapshot+ .record_tsc_restore_clock(state.clock.clock);+ Ok(())+ }++ /// Restores IRQ chips and then the PIT after all vCPUs are restored and+ /// before any guest entry. Discard the destination after an ioctl failure.+ pub fn restore_after_vcpus(&self, state: &crate::X86VmState) -> Result<()> {+ let restore = || -> io::Result<()> {+ let ids = state.irqchips.each_ref().map(|chip| chip.as_kvm().chip_id);+ if ids+ != [+ KVM_IRQCHIP_PIC_MASTER,+ KVM_IRQCHIP_PIC_SLAVE,+ KVM_IRQCHIP_IOAPIC,+ ]+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "expected IRQ chip IDs in PIC master, PIC slave, IOAPIC order",+ ));+ }+ for chip in &state.irqchips {+ self.fd+ .set_irqchip(chip.as_kvm())+ .map_err(io::Error::from)?;+ }+ if let Some(pit) = &state.pit {+ self.fd.set_pit2(pit).map_err(io::Error::from)?;+ }+ Ok(())+ };+ restore().map_err(|source| Error::vm_state("restore", source))+ }+/// KVM-supported guest CPUID before the VMM applies guest topology/policy.pub fn supported_cpuid(&self) -> &[crate::X86CpuidEntry] {&self.cpuid@@ -146,8 +260,18 @@ impl KvmVm {.fd.create_vcpu(u64::from(id)).map_err(io::Error::from)?;+ self.vcpu_snapshot.clear_tsc_save_anchor();+ // KVM locks guest XSTATE permissions when it creates the first vCPU.+ let xsave_size = xsave2_size(&self.fd).map_err(CachedIoError::from_io);kick.configure(fd.as_raw_fd())?;- Ok(KvmVcpu::new(fd, id, self.run_size, kick))+ Ok(KvmVcpu::new(+ fd,+ id,+ self.run_size,+ kick,+ xsave_size,+ Arc::clone(&self.vcpu_snapshot),+ ))};create().map_err(|source| Error::CreateVcpu { id, source })}@@ -245,6 +369,18 @@ impl crate::Vm for KvmVm {}impl crate::X86Vm for KvmVm {+ fn save_state(&self) -> Result<crate::X86VmState> {+ Self::save_state(self)+ }++ fn restore_before_vcpus(&self, state: &crate::X86VmState) -> Result<()> {+ Self::restore_before_vcpus(self, state)+ }++ fn restore_after_vcpus(&self, state: &crate::X86VmState) -> Result<()> {+ Self::restore_after_vcpus(self, state)+ }+fn supported_cpuid(&self) -> &[crate::X86CpuidEntry] {Self::supported_cpuid(self)}@@ -254,18 +390,160 @@ impl crate::X86Vm for KvmVm {mod tests {use std::ptr::NonNull;use std::sync::{+ Barrier,atomic::{AtomicU8, Ordering},mpsc,};use std::{thread,- time::{Duration, Instant},+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},};- use kvm_bindings::{KVM_IRQCHIP_IOAPIC, kvm_irqchip, kvm_regs};+ use kvm_bindings::{Msrs, kvm_irqchip, kvm_msr_entry, kvm_regs};+ use super::super::features::{MSR_IA32_TSC, MSR_IA32_TSC_DEADLINE, snapshot_msrs};use super::*;- use crate::{VcpuExit, VcpuHandle};+ use crate::{VcpuExit, VcpuHandle, X86Msr};++ fn snapshot_cpuid(vm: &KvmVm) -> Vec<crate::X86CpuidEntry> {+ let mut cpuid = vm.supported_cpuid().to_vec();+ for entry in &mut cpuid {+ if entry.leaf == 7 && (!entry.subleaf_required || entry.subleaf == 0) {+ entry.ecx &= !(1 << 7); // CET shadow stack is outside the snapshot contract.+ }+ }+ cpuid+ }++ fn saved_tsc(state: &crate::X86VcpuState) -> u64 {+ state+ .msrs+ .iter()+ .find(|msr| msr.index == MSR_IA32_TSC)+ .unwrap()+ .data+ }++ fn assert_vcpu_save_error(error: Error, message: &str) {+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "save CPU state", ref source, .. }+ if source.kind() == io::ErrorKind::Other && source.to_string() == message),+ "{error:?}"+ );+ }++ #[test]+ fn parse_xsave2_size_preserves_negative_ioctl_errno() {+ let result = parse_xsave2_size(-1, io::Error::from_raw_os_error(libc::ENOTTY));+ assert_eq!(result.unwrap_err().raw_os_error(), Some(libc::ENOTTY));+ for error in [io::Error::from_raw_os_error(0), io::Error::other("unknown")] {+ let error = parse_xsave2_size(-2, error).unwrap_err();+ assert_eq!(+ error.to_string(),+ "KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) failed with -2"+ );+ }+ }++ #[test]+ fn parse_xsave2_size_accepts_unsupported_and_valid_sizes() {+ let parse = |ret| parse_xsave2_size(ret, io::Error::from_raw_os_error(libc::ENOTTY));+ assert_eq!(parse(0).unwrap(), 0);+ assert_eq!(parse(4096).unwrap(), 4096);+ assert_eq!(parse(8192).unwrap(), 8192);+ }++ #[test]+ fn parse_xsave2_size_rejects_sizes_below_the_legacy_abi() {+ for size in [1, 4095] {+ let error = parse_xsave2_size(size, io::Error::from_raw_os_error(0)).unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::Other);+ assert!(+ error+ .to_string()+ .contains("below the 4096-byte legacy size")+ );+ }+ }++ /// Replace the owned VM fd with a valid non-KVM fd to force ioctl failure.+ fn vm_with_failing_ioctls() -> (KvmVm, crate::X86VmState) {+ let vm = KvmVm::new().unwrap();+ let state = vm.save_state().unwrap();+ let file = std::fs::File::open("/dev/null").unwrap();+ // SAFETY: both fds are valid and distinct; vm exclusively owns the+ // destination fd and continues to own its replacement until drop.+ assert_eq!(+ unsafe { libc::dup2(file.as_raw_fd(), vm.fd.as_raw_fd()) },+ vm.fd.as_raw_fd()+ );+ (vm, state)+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn xsave2_size_propagates_extension_query_error() {+ let (vm, _) = vm_with_failing_ioctls();+ let error = xsave2_size(&vm.fd).unwrap_err();+ assert_eq!(error.raw_os_error(), Some(libc::ENOTTY));+ }++ fn assert_vm_state_ioctl_error(error: Error, operation: &'static str) {+ let cause = std::error::Error::source(&error)+ .and_then(|source| source.downcast_ref::<io::Error>())+ .expect("original ioctl error");+ assert_eq!(cause.raw_os_error(), Some(libc::ENOTTY));+ assert_eq!(+ cause.kind(),+ io::Error::from_raw_os_error(libc::ENOTTY).kind()+ );+ assert!(std::error::Error::source(cause).is_none());+ assert_eq!(error.to_string(), format!("failed to {operation} VM state"));+ assert!(matches!(error, Error::VmState { operation: actual, .. } if actual == operation));+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn save_vm_state_preserves_the_ioctl_error() {+ let (vm, _) = vm_with_failing_ioctls();+ assert_vm_state_ioctl_error(vm.save_state().unwrap_err(), "save");+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn restore_vm_state_preserves_the_ioctl_error() {+ let (vm, state) = vm_with_failing_ioctls();+ assert_vm_state_ioctl_error(vm.restore_before_vcpus(&state).unwrap_err(), "restore");+ assert_vm_state_ioctl_error(vm.restore_after_vcpus(&state).unwrap_err(), "restore");+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn restore_after_vcpus_rejects_invalid_irqchip_ids() {+ let (vm, mut state) = vm_with_failing_ioctls();+ for ids in [+ [KVM_IRQCHIP_PIC_MASTER; 3],+ [KVM_IRQCHIP_PIC_MASTER, KVM_IRQCHIP_PIC_SLAVE, u32::MAX],+ [+ KVM_IRQCHIP_PIC_SLAVE,+ KVM_IRQCHIP_PIC_MASTER,+ KVM_IRQCHIP_IOAPIC,+ ],+ ] {+ state.irqchips = ids.map(|id| crate::X86IrqchipState::pic(id, Default::default()));+ // Any write would fail with ENOTTY instead of the validation error.+ let error = vm.restore_after_vcpus(&state).unwrap_err();+ assert!(+ matches!(+ error,+ Error::VmState { operation: "restore", ref source }+ if source.kind() == io::ErrorKind::InvalidInput+ && source.raw_os_error().is_none()+ ),+ "IRQ chip IDs {ids:?}: {error:?}"+ );+ }+ }struct Ram(NonNull<u8>);@@ -302,6 +580,1276 @@ mod tests {}}+ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_msr_probe_error_does_not_prevent_vcpu_creation_or_run() {+ let ram = Ram::new();+ // SAFETY: the two-byte OUT 0x80, AL instruction fits in private RAM.+ unsafe { ram.0.as_ptr().cast::<[u8; 2]>().write([0xe6, 0x80]) };+ let mut vm = KvmVm::new().unwrap();+ // SAFETY: RAM outlives the VM and its vCPU.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ vm.vcpu_snapshot = Arc::new(VcpuSnapshotShared::new(+ Arc::clone(&vm.fd),+ Err(CachedIoError::from_io(io::Error::from_raw_os_error(+ libc::EPERM,+ ))),+ ));+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(&snapshot_cpuid(&vm), &[]).unwrap();+ let mut sregs = cpu.fd.get_sregs().unwrap();+ sregs.cs.base = 0;+ sregs.cs.selector = 0;+ cpu.fd.set_sregs(&sregs).unwrap();+ cpu.fd+ .set_regs(&kvm_regs {+ rip: ram.region().guest_addr,+ rflags: 2,+ ..Default::default()+ })+ .unwrap();+ assert!(matches!(+ cpu.run().unwrap(),+ VcpuExit::IoOut { port: 0x80, .. }+ ));+ cpu.complete_pending_io().unwrap();+ vm.save_state().unwrap();+ let error = cpu.save_state().unwrap_err();+ assert!(+ matches!(error, Error::ConfigureVcpu { operation: "save CPU state", ref source, .. }+ if source.raw_os_error() == Some(libc::EPERM))+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_preserves_mtrr_def_type_and_mtrrs() {+ let mtrrs = [+ (0x2ff, 0x806),+ (0x250, 0x0606_0606_0606_0606),+ (0x200, 0x20_0006),+ (0x201, 0xffe0_0800),+ ];+ // .code16: MOV ECX,0x2ff; RDMSR; OUT 0x80,EAX.+ let program = [+ 0x66, 0xb9, 0xff, 0x02, 0x00, 0x00, 0x0f, 0x32, 0x66, 0xe7, 0x80,+ ];+ let ram = Ram::new();+ // SAFETY: the program fits in the private, unmapped page.+ unsafe { std::ptr::copy_nonoverlapping(program.as_ptr(), ram.0.as_ptr(), program.len()) };+ let vm = KvmVm::new().unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(+ &snapshot_cpuid(&vm),+ &mtrrs.map(|(index, value)| X86Msr { index, value }),+ )+ .unwrap();+ let mut sregs = cpu.fd.get_sregs().unwrap();+ sregs.cs.base = 0;+ sregs.cs.selector = 0;+ cpu.fd.set_sregs(&sregs).unwrap();+ cpu.fd+ .set_regs(&kvm_regs {+ rip: 0x1000,+ rflags: 2,+ ..Default::default()+ })+ .unwrap();+ let platform = vm.save_state().unwrap();+ let state = cpu.save_state().unwrap();+ drop(cpu);++ let destination = KvmVm::new().unwrap();+ // SAFETY: the page outlives the destination VM and vCPU.+ unsafe { destination.map_memory(&ram.region()) }.unwrap();+ destination.restore_before_vcpus(&platform).unwrap();+ let mut cpu = destination.create_vcpu(0).unwrap();+ cpu.restore_state(&state).unwrap();+ destination.restore_after_vcpus(&platform).unwrap();+ let mut readback = Msrs::from_entries(&mtrrs.map(|(index, _)| kvm_msr_entry {+ index,+ ..Default::default()+ }))+ .unwrap();+ assert_eq!(cpu.fd.get_msrs(&mut readback).unwrap(), mtrrs.len());+ for (entry, (index, value)) in readback.as_slice().iter().zip(mtrrs) {+ assert_eq!((entry.index, entry.data), (index, value));+ }+ match cpu.run().unwrap() {+ VcpuExit::IoOut { port: 0x80, bytes } => assert_eq!(bytes, &0x806u32.to_le_bytes()),+ exit => panic!("expected guest MTRR_DEF_TYPE, got {exit:?}"),+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with KVM TSC offset controls"]+ fn snapshot_restore_preserves_inter_vcpu_tsc_skew_and_sync() {+ #[derive(Clone, Copy, Debug)]+ enum CaptureOrder {+ VmFirst,+ ReorderedRetry,+ NoopIoCompletion,+ }++ let pause = Duration::from_millis(5);+ for (order, skew_ms) in [+ (CaptureOrder::VmFirst, 100),+ (CaptureOrder::VmFirst, 0),+ (CaptureOrder::ReorderedRetry, 0),+ (CaptureOrder::NoopIoCompletion, 0),+ ] {+ let vm = KvmVm::new().unwrap();+ // Spawn both vCPU owners from the test thread so each inherits an unblocked kick signal.+ let states = thread::scope(|scope| {+ let (send_offset, wait_for_offset) = mpsc::channel();+ let (ready, prepared) = mpsc::channel();+ let (capture, wait_for_capture) = mpsc::channel();+ let (saved, receive_state) = mpsc::channel();+ let vm = &vm;+ scope.spawn(move || {+ let Ok(offset) = wait_for_offset.recv() else {+ return;+ };+ let mut second = vm.create_vcpu(1).unwrap();+ second.set_cpu_features(&snapshot_cpuid(vm), &[]).unwrap();+ assert!(second.has_tsc_offset().unwrap());+ assert!(second.set_tsc_offset(offset).unwrap());+ assert_eq!(second.get_tsc_offset().unwrap(), Some(offset));+ ready.send(()).unwrap();+ if wait_for_capture.recv().is_ok() {+ if matches!(order, CaptureOrder::NoopIoCompletion) {+ second.complete_pending_io().unwrap();+ }+ saved.send(second.save_state().unwrap()).unwrap();+ }+ });+ let capture_first = move || {+ let mut first = vm.create_vcpu(0).unwrap();+ first.set_cpu_features(&snapshot_cpuid(vm), &[]).unwrap();+ first.has_tsc_offset().unwrap();+ let offset = first.get_tsc_offset().unwrap()?;+ let skew = u64::from(first.fd.get_tsc_khz().unwrap()) * skew_ms;+ send_offset.send(offset.wrapping_add(skew)).unwrap();+ prepared.recv().unwrap();+ let save_second = || {+ capture.send(()).unwrap();+ receive_state.recv().unwrap()+ };+ let platform = vm.save_state().unwrap();+ let (first_state, second_state) =+ if matches!(order, CaptureOrder::ReorderedRetry) {+ assert_vcpu_save_error(+ first.save_state_with_pending_io().unwrap_err(),+ "complete pending I/O before saving",+ );+ let second_state = save_second();+ thread::sleep(pause);+ let first_state = first.save_state().unwrap();+ assert_vcpu_save_error(+ first.save_state().unwrap_err(),+ "save VM state before recapturing vCPU state",+ );+ (first_state, second_state)+ } else {+ let first_state = first.save_state().unwrap();+ thread::sleep(pause);+ (first_state, save_second())+ };+ Some((platform, first_state, second_state, skew))+ };+ scope.spawn(capture_first).join().unwrap()+ });+ let Some((platform, first_state, second_state, skew)) = states else {+ eprintln!("skipping TSC snapshot test: KVM does not expose TSC offset controls");+ return;+ };+ assert_eq!(first_state.tsc_khz, second_state.tsc_khz);+ assert_eq!(+ saved_tsc(&second_state).wrapping_sub(saved_tsc(&first_state)),+ skew,+ "{order:?} capture"+ );+ let destination = KvmVm::new().unwrap();+ destination.restore_before_vcpus(&platform).unwrap();+ let restore_offset = |id, state: &crate::X86VcpuState| {+ let mut cpu = destination.create_vcpu(id).unwrap();+ cpu.restore_state(state).unwrap();+ cpu.get_tsc_offset().unwrap().unwrap()+ };+ let (first_offset, second_offset) = thread::scope(|scope| {+ let (restored_first, wait_for_first) = mpsc::channel();+ let first = scope.spawn(move || {+ let offset = restore_offset(0, &first_state);+ restored_first.send(()).unwrap();+ offset+ });+ let second = scope.spawn(move || {+ wait_for_first.recv().unwrap();+ thread::sleep(pause);+ restore_offset(1, &second_state)+ });+ (first.join().unwrap(), second.join().unwrap())+ });+ assert_eq!(+ second_offset,+ first_offset.wrapping_add(skew),+ "{order:?} restore"+ );+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with KVM TSC offset controls"]+ fn consecutive_paused_vm_first_saves_use_each_rounds_vm_clock() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(&snapshot_cpuid(&vm), &[]).unwrap();+ if !cpu.has_tsc_offset().unwrap() {+ eprintln!("skipping clock correlation test: KVM does not expose TSC offset controls");+ return;+ }++ let first_vm = vm.save_state().unwrap();+ let first_cpu = cpu.save_state().unwrap();+ thread::sleep(Duration::from_millis(50));+ let second_vm = vm.save_state().unwrap();+ let second_cpu = cpu.save_state().unwrap();++ assert_eq!(first_cpu.tsc_khz, second_cpu.tsc_khz);+ let clock_elapsed_ns = second_vm.clock.clock.wrapping_sub(first_vm.clock.clock);+ assert!(clock_elapsed_ns >= 50_000_000);+ let tsc_elapsed_ns = u128::from(saved_tsc(&second_cpu).wrapping_sub(saved_tsc(&first_cpu)))+ * 1_000_000+ / u128::from(second_cpu.tsc_khz);+ assert!(+ tsc_elapsed_ns.abs_diff(u128::from(clock_elapsed_ns)) <= 15_000_000,+ "guest TSC elapsed {tsc_elapsed_ns} ns, kvmclock elapsed {clock_elapsed_ns} ns"+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with KVM TSC offset controls"]+ fn paused_snapshot_requires_vm_save_for_each_vcpu_capture_round() {+ let vm = &KvmVm::new().unwrap();+ thread::scope(|scope| {+ let (ready, wait_for_ready) = mpsc::channel();+ let (capture, wait_for_capture) = mpsc::channel();+ let (saved, receive_state) = mpsc::channel();+ scope.spawn(move || {+ let mut cpu = vm.create_vcpu(1).unwrap();+ cpu.set_cpu_features(&snapshot_cpuid(vm), &[]).unwrap();+ cpu.has_tsc_offset().unwrap();+ ready.send(cpu.get_tsc_offset().unwrap()).unwrap();+ for () in wait_for_capture {+ saved.send(cpu.save_state().unwrap()).unwrap();+ }+ });+ let mut first = vm.create_vcpu(0).unwrap();+ first.set_cpu_features(&snapshot_cpuid(vm), &[]).unwrap();+ let second_offset = wait_for_ready.recv().unwrap();+ assert_vcpu_save_error(+ first.save_state().unwrap_err(),+ "save VM state before saving vCPU state",+ );+ first.has_tsc_offset().unwrap();+ let (Some(first_offset), Some(second_offset)) =+ (first.get_tsc_offset().unwrap(), second_offset)+ else {+ eprintln!(+ "skipping clock correlation test: KVM does not expose TSC offset controls"+ );+ return;+ };++ let capture_round = |first: &mut KvmVcpu| {+ let first_cpu = first.save_state().unwrap();+ capture.send(()).unwrap();+ let second_cpu = receive_state.recv().unwrap();+ assert_eq!(first_cpu.tsc_khz, second_cpu.tsc_khz);+ let scaled_tsc = saved_tsc(&first_cpu).wrapping_sub(first_offset);+ assert_eq!(+ scaled_tsc,+ saved_tsc(&second_cpu).wrapping_sub(second_offset)+ );+ (first_cpu.tsc_khz, scaled_tsc)+ };++ let first_vm = vm.save_state().unwrap();+ let (first_khz, first_tsc) = capture_round(&mut first);+ thread::sleep(Duration::from_millis(50));+ assert_vcpu_save_error(+ first.save_state().unwrap_err(),+ "save VM state before recapturing vCPU state",+ );++ let second_vm = vm.save_state().unwrap();+ thread::sleep(Duration::from_millis(50));+ let (second_khz, second_tsc) = capture_round(&mut first);+ assert_eq!(first_khz, second_khz);+ let elapsed_ns =+ u128::from(second_tsc.wrapping_sub(first_tsc)) * 1_000_000 / u128::from(first_khz);+ let clock_elapsed_ns = second_vm.clock.clock.wrapping_sub(first_vm.clock.clock);+ assert!(clock_elapsed_ns >= 50_000_000);+ assert!(+ elapsed_ns.abs_diff(u128::from(clock_elapsed_ns)) <= 15_000_000,+ "guest TSC elapsed {elapsed_ns} ns, kvmclock elapsed {clock_elapsed_ns} ns"+ );+ });+ }++ #[test]+ #[ignore = "requires Linux x86_64 with KVM TSC offset controls"]+ fn vm_first_restore_keeps_guest_tsc_correlated_with_kvmclock() {+ let vm = KvmVm::new().unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.set_cpu_features(&snapshot_cpuid(&vm), &[]).unwrap();+ if !cpu.has_tsc_offset().unwrap() {+ eprintln!("skipping clock correlation test: KVM does not expose TSC offset controls");+ return;+ }+ let platform = vm.save_state().unwrap();+ thread::sleep(Duration::from_millis(50));+ let state = cpu.save_state().unwrap();+ let saved_tsc = saved_tsc(&state);+ let check_correlation = |phase, vm: &KvmVm, cpu: &KvmVcpu| {+ let before = vm.fd.get_clock().unwrap().clock;+ let guest_tsc = snapshot_msrs(&cpu.fd, &[MSR_IA32_TSC]).unwrap()[0].data;+ let after = vm.fd.get_clock().unwrap().clock;++ let elapsed_ns = u128::from(guest_tsc.wrapping_sub(saved_tsc)) * 1_000_000+ / u128::from(state.tsc_khz);+ let min_ns = before.wrapping_sub(platform.clock.clock);+ let max_ns = after.wrapping_sub(platform.clock.clock);+ assert!(min_ns >= 50_000_000);+ // Allow for scheduling delays in the save and restore samples.+ let tolerance_ns = 15_000_000;+ assert!(+ (u128::from(min_ns.saturating_sub(tolerance_ns))+ ..=u128::from(max_ns + tolerance_ns))+ .contains(&elapsed_ns),+ "{phase}: guest TSC elapsed {elapsed_ns} ns, kvmclock elapsed {min_ns}..={max_ns} ns"+ );+ };+ check_correlation("save", &vm, &cpu);+ drop(cpu);++ let vm = KvmVm::new().unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ thread::sleep(Duration::from_millis(50));+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.restore_state(&state).unwrap();+ check_correlation("restore", &vm, &cpu);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with KVM TSC deadline timers"]+ fn snapshot_restore_delivers_armed_tsc_deadline_after_tsc_restore() {+ const VECTOR: u8 = 0x51;+ const TSC_DEADLINE: u32 = 1 << 24;+ let ram = Ram::new();+ let vm = KvmVm::new().unwrap();+ let mut cpuid = snapshot_cpuid(&vm);+ let leaf = cpuid.iter_mut().find(|entry| entry.leaf == 1).unwrap();+ if leaf.ecx & TSC_DEADLINE == 0 {+ let capability = Kvm::new()+ .unwrap()+ .check_extension_int(Cap::TscDeadlineTimer);+ if capability == 0 {+ eprintln!("skipping LAPIC snapshot test: KVM does not expose TSC deadline timers");+ return;+ }+ assert!(+ capability > 0,+ "KVM_CHECK_EXTENSION(KVM_CAP_TSC_DEADLINE_TIMER) failed: {}",+ io::Error::last_os_error()+ );+ // KVM can expose the in-kernel timer through the capability alone.+ leaf.ecx |= TSC_DEADLINE;+ }+ // SAFETY: the guest program, ISR and real-mode vector fit in private RAM.+ unsafe {+ let page = std::slice::from_raw_parts_mut(ram.0.as_ptr(), 4096);+ page[..2].copy_from_slice(&[0xeb, 0xfe]); // JMP $.+ page[0x100..0x105].copy_from_slice(&[0xb0, VECTOR, 0xe6, 0x80, 0xf4]);+ let gate = 0x800 + usize::from(VECTOR) * 4;+ page[gate..gate + 4].copy_from_slice(&0x1100u32.to_le_bytes());+ }+ let mut cpu = vm.create_vcpu(0).unwrap();+ let khz = u64::from(cpu.fd.get_tsc_khz().unwrap());+ cpu.set_cpu_features(+ &cpuid,+ &[X86Msr {+ index: MSR_IA32_TSC,+ value: khz * 30_000,+ }],+ )+ .unwrap();+ let mut sregs = cpu.fd.get_sregs().unwrap();+ sregs.cs.base = 0;+ sregs.cs.selector = 0;+ sregs.idt.base = 0x1800;+ sregs.idt.limit = 0x3ff;+ cpu.fd.set_sregs(&sregs).unwrap();+ cpu.fd+ .set_regs(&kvm_regs {+ rip: 0x1000,+ rsp: 0x1ff0,+ rflags: 0x202,+ ..Default::default()+ })+ .unwrap();+ let mut lapic = cpu.fd.get_lapic().unwrap();+ lapic.regs[0xf1] |= 1; // Software enable in the spurious vector register.+ let lvtt = u32::from(VECTOR) | (2 << 17);+ lapic.regs[0x320..0x324].copy_from_slice(&lvtt.to_le_bytes().map(|byte| byte as i8));+ cpu.fd.set_lapic(&lapic).unwrap();+ let current = snapshot_msrs(&cpu.fd, &[MSR_IA32_TSC]).unwrap()[0].data;+ let deadline = current.wrapping_add(khz * 250);+ let msr = Msrs::from_entries(&[kvm_msr_entry {+ index: MSR_IA32_TSC_DEADLINE,+ data: deadline,+ ..Default::default()+ }])+ .unwrap();+ assert_eq!(cpu.fd.set_msrs(&msr).unwrap(), 1);+ let platform = vm.save_state().unwrap();+ let mut state = cpu.save_state().unwrap();+ drop(cpu);+ let deadline_index = state+ .msrs+ .iter()+ .position(|entry| entry.index == MSR_IA32_TSC_DEADLINE)+ .unwrap();+ let armed = state.msrs.remove(deadline_index);+ assert_eq!(armed.data, deadline);+ let tsc_index = state+ .msrs+ .iter()+ .position(|entry| entry.index == MSR_IA32_TSC)+ .unwrap();+ state.msrs.insert(tsc_index, armed);+ let irr = 0x200 + usize::from(VECTOR / 32) * 16 + usize::from((VECTOR % 32) / 8);+ assert_eq!(state.lapic.regs[irr] & (1 << (VECTOR % 8)), 0);++ let destination = KvmVm::new().unwrap();+ // SAFETY: RAM outlives the destination VM and vCPU.+ unsafe { destination.map_memory(&ram.region()) }.unwrap();+ destination.restore_before_vcpus(&platform).unwrap();+ let mut cpu = destination.create_vcpu(0).unwrap();+ cpu.restore_state(&state).unwrap();+ destination.restore_after_vcpus(&platform).unwrap();+ let kick = cpu.handle();+ let exit = thread::scope(|scope| {+ let (done, finished) = mpsc::channel::<()>();+ scope.spawn(move || {+ if let Err(mpsc::RecvTimeoutError::Timeout) =+ finished.recv_timeout(Duration::from_secs(2))+ {+ kick.kick().unwrap();+ }+ });+ let exit = cpu.run();+ drop(done);+ exit+ });+ match exit.unwrap() {+ VcpuExit::IoOut { port: 0x80, bytes } => assert_eq!(bytes, &[VECTOR]),+ exit => panic!("expected LAPIC deadline interrupt, got {exit:?}"),+ }+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn notify_guest_stopped_succeeds_for_inactive_and_active_pvclock() {+ const MSR_KVM_SYSTEM_TIME_NEW: u32 = 0x4b56_4d01;+ let ram = Ram::new();+ let source = KvmVm::new().unwrap();+ // SAFETY: the page outlives the VMs and vCPUs, which use it in sequence.+ unsafe { source.map_memory(&ram.region()) }.unwrap();+ let mut cpu = source.create_vcpu(0).unwrap();+ cpu.notify_guest_stopped().unwrap();+ let active = ram.region().guest_addr | 1;+ cpu.set_cpu_features(+ &snapshot_cpuid(&source),+ &[X86Msr {+ index: MSR_KVM_SYSTEM_TIME_NEW,+ value: active,+ }],+ )+ .unwrap();+ cpu.fd.kvmclock_ctrl().unwrap();+ cpu.notify_guest_stopped().unwrap();+ let platform = source.save_state().unwrap();+ let state = cpu.save_state().unwrap();+ drop(cpu);+ drop(source);++ let destination = KvmVm::new().unwrap();+ // SAFETY: the source VM has released the page and it outlives the destination.+ unsafe { destination.map_memory(&ram.region()) }.unwrap();+ destination.restore_before_vcpus(&platform).unwrap();+ let mut cpu = destination.create_vcpu(0).unwrap();+ cpu.restore_state(&state).unwrap();+ destination.restore_after_vcpus(&platform).unwrap();+ cpu.fd.kvmclock_ctrl().unwrap();+ cpu.notify_guest_stopped().unwrap();+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn wall_clock_restore_preserves_epoch_across_vcpus() {+ use crate::X86Msr;+ use crate::kvm::vcpu::MSR_KVM_WALL_CLOCK_NEW;++ let source_ram = Ram::new();+ let source = KvmVm::new().unwrap();+ let region = source_ram.region();+ // SAFETY: source RAM outlives the VM and its vCPUs.+ unsafe { source.map_memory(®ion) }.unwrap();+ let offset = 7 * 24 * 60 * 60 * 1_000_000_000;+ source+ .fd+ .set_clock(&kvm_clock_data {+ clock: offset,+ ..Default::default()+ })+ .unwrap();+ let configure = |id| {+ let mut cpu = source.create_vcpu(id).unwrap();+ cpu.set_cpu_features(+ &snapshot_cpuid(&source),+ &[X86Msr {+ index: MSR_KVM_WALL_CLOCK_NEW,+ value: region.guest_addr,+ }],+ )+ .unwrap();+ cpu+ };+ let (platform, cpus) = thread::scope(|scope| {+ let (start, wait_for_start) = mpsc::channel();+ let (ready, wait_for_ready) = mpsc::channel();+ let (capture, wait_for_capture) = mpsc::channel();+ let second = scope.spawn(move || {+ wait_for_start.recv().unwrap();+ let mut cpu = configure(1);+ ready.send(()).unwrap();+ wait_for_capture.recv().unwrap();+ cpu.save_state().unwrap()+ });+ let mut first = configure(0);+ start.send(()).unwrap();+ wait_for_ready.recv().unwrap();+ let platform = source.save_state().unwrap();+ capture.send(()).unwrap();+ (+ platform,+ [first.save_state().unwrap(), second.join().unwrap()],+ )+ });+ for state in &cpus {+ assert!(state.msrs.iter().any(|entry| {+ entry.index == MSR_KVM_WALL_CLOCK_NEW && entry.data == region.guest_addr+ }));+ }+ assert!(platform.clock.clock >= offset);++ let read_wall_clock = |ram: &Ram| -> [u32; 3] {+ // SAFETY: all restore ioctls have finished and no vCPU entered KVM_RUN.+ let bytes = unsafe { std::slice::from_raw_parts(ram.0.as_ptr(), 12) };+ std::array::from_fn(|i| u32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().unwrap()))+ };+ let expected_version = {+ let ram = Ram::new();+ let vm = KvmVm::new().unwrap();+ // SAFETY: destination RAM outlives the VM and both vCPUs.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ for (id, state) in (0..).zip(&cpus) {+ vm.create_vcpu(id).unwrap().restore_state(state).unwrap();+ }+ vm.restore_after_vcpus(&platform).unwrap();+ read_wall_clock(&ram)[0]+ };+ // Each vCPU's wall-clock write advances the version by two.+ assert!(+ expected_version >= 4 && expected_version.is_multiple_of(2),+ "serial pvclock version {expected_version}"+ );++ let ram = Ram::new();+ let vm = KvmVm::new().unwrap();+ // SAFETY: destination RAM outlives the VM and both worker threads.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ let before = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ let after = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();+ let start_restore = Barrier::new(cpus.len());+ thread::scope(|scope| {+ for (id, state) in (0..).zip(&cpus) {+ let (vm, start_restore) = (&vm, &start_restore);+ scope.spawn(move || {+ let vcpu = vm.create_vcpu(id);+ start_restore.wait();+ vcpu.unwrap().restore_state(state).unwrap();+ });+ }+ });+ vm.restore_after_vcpus(&platform).unwrap();++ let [version, sec, nsec] = read_wall_clock(&ram);+ assert_eq!(version, expected_version);+ let epoch = Duration::new(u64::from(sec), nsec);+ let restored_realtime = epoch + Duration::from_nanos(platform.clock.clock);+ let tolerance = Duration::from_secs(2);+ let realtime_window = before.saturating_sub(tolerance)..=after + tolerance;+ assert!(+ realtime_window.contains(&restored_realtime),+ "pvclock epoch plus saved clock {restored_realtime:?}, host realtime window {realtime_window:?}"+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn pending_ioapic_level_irq_and_pit_deliver_after_vcpu_restore() {+ use crate::{X86BootRegisters, X86IrqchipState, X86Segment};++ const PIN: usize = 5;+ const VECTOR: u8 = 0x51;+ const REMOTE_IRR: u64 = 1 << 14;+ const LEVEL_TRIGGERED: u64 = 1 << 15;+ const IDT: usize = 0x1800;+ const GDT: usize = 0x1700;+ const ENTRY: usize = 0x1000;+ const HANDLER: usize = 0x1100;++ // Report zero if no interrupt reaches the vCPU before its first instruction.+ let entry = [0x31, 0xc0, 0xe6, 0x80, 0xf4]; // XOR EAX,EAX; OUT 0x80,AL; HLT.+ #[rustfmt::skip]+ let handler = [+ 0xb0, VECTOR, 0xe6, 0x80, // MOV AL,VECTOR; OUT 0x80,AL.+ // MOV dword [0xfee000b0],0 (xAPIC EOI).+ 0xc7, 0x05, 0xb0, 0x00, 0xe0, 0xfe, 0x00, 0x00, 0x00, 0x00,+ 0xe6, 0x81, 0xf4, // OUT 0x81,AL; HLT.+ ];+ // 32-bit interrupt gate to HANDLER in code segment 8.+ let gate = (HANDLER as u64 | (8 << 16) | (0x8e << 40)).to_le_bytes();+ let ram = Ram::new();+ // SAFETY: RAM is private and unmapped, and all the fixtures fit in the page.+ unsafe {+ let page = std::slice::from_raw_parts_mut(ram.0.as_ptr(), 4096);+ page[..entry.len()].copy_from_slice(&entry);+ let handler_offset = HANDLER - ENTRY;+ page[handler_offset..handler_offset + handler.len()].copy_from_slice(&handler);+ let gdt_offset = GDT - ENTRY;+ page[gdt_offset + 8..gdt_offset + 16]+ .copy_from_slice(&0x00cf_9b00_0000_ffffu64.to_le_bytes());+ page[gdt_offset + 16..gdt_offset + 24]+ .copy_from_slice(&0x00cf_9300_0000_ffffu64.to_le_bytes());+ let gate_offset = IDT - ENTRY + usize::from(VECTOR) * 8;+ page[gate_offset..gate_offset + 8].copy_from_slice(&gate);+ }++ let read_ioapic = |vm: &KvmVm| {+ let mut chip = kvm_irqchip {+ chip_id: KVM_IRQCHIP_IOAPIC,+ ..Default::default()+ };+ vm.fd.get_irqchip(&mut chip).unwrap();+ // SAFETY: the chip ID selects the initialized IOAPIC member.+ unsafe { chip.chip.ioapic }+ };+ let source = KvmVm::new().unwrap();+ // SAFETY: RAM outlives both VMs, and only the destination enters the guest.+ unsafe { source.map_memory(&ram.region()) }.unwrap();+ let mut cpu = source.create_vcpu(0).unwrap();+ cpu.set_cpu_features(&snapshot_cpuid(&source), &[]).unwrap();+ cpu.set_boot_registers(&X86BootRegisters {+ rip: ENTRY as u64,+ rsp: (ENTRY + 4096) as u64,+ rflags: 0x202, // IF and the reserved bit.+ cr0: 0x11, // Protected mode with paging disabled.+ code: X86Segment {+ limit: u32::MAX,+ selector: 8,+ attributes: 0xc09b,+ ..Default::default()+ },+ data: X86Segment {+ limit: u32::MAX,+ selector: 16,+ attributes: 0xc093,+ ..Default::default()+ },+ gdt_base: GDT as u64,+ gdt_limit: 23,+ idt_base: IDT as u64,+ idt_limit: u16::from(VECTOR) * 8 + 7,+ ..Default::default()+ })+ .unwrap();+ for id in [KVM_IRQCHIP_PIC_MASTER, KVM_IRQCHIP_PIC_SLAVE] {+ let pic = X86IrqchipState::pic(+ id,+ kvm_bindings::kvm_pic_state {+ imr: u8::MAX,+ ..Default::default()+ },+ );+ source.fd.set_irqchip(pic.as_kvm()).unwrap();+ }+ let mut ioapic = read_ioapic(&source);+ ioapic.redirtbl[PIN].bits = u64::from(VECTOR) | LEVEL_TRIGGERED;+ source+ .fd+ .set_irqchip(X86IrqchipState::ioapic(ioapic).as_kvm())+ .unwrap();+ // Hold the line high while the LAPIC is still software-disabled, so the+ // IOAPIC has a pending level without an outstanding LAPIC delivery.+ let mut lapic = cpu.fd.get_lapic().unwrap();+ lapic.regs[0xf1] &= !1;+ cpu.fd.set_lapic(&lapic).unwrap();+ source.set_irq_line(PIN as u32, true).unwrap();+ lapic.regs[0xf1] |= 1; // Enable the LAPIC via the spurious interrupt register.+ cpu.fd.set_lapic(&lapic).unwrap();++ let mut pit = source.fd.get_pit2().unwrap();+ let channel = &mut pit.channels[0];+ channel.count = 0x3456;+ channel.mode = 2; // Periodic rate generator, with IRQ0 masked above.+ channel.rw_mode = 3;+ channel.gate = 1;+ source.fd.set_pit2(&pit).unwrap();+ let platform = source.save_state().unwrap();+ // SAFETY: the third chip contains the initialized IOAPIC image.+ let pending = unsafe { platform.irqchips[2].as_kvm().chip.ioapic };+ assert_ne!(pending.irr & (1 << PIN), 0);+ // SAFETY: the snapshot contains an initialized IOAPIC redirection table.+ assert_eq!(unsafe { pending.redirtbl[PIN].bits } & REMOTE_IRR, 0);+ let state = cpu.save_state().unwrap();+ drop(cpu);+ drop(source);++ let vm = KvmVm::new().unwrap();+ // SAFETY: source VM is gone, and RAM outlives the destination VM and vCPU.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ let mut cpu = vm.create_vcpu(0).unwrap();+ cpu.restore_state(&state).unwrap();+ vm.restore_after_vcpus(&platform).unwrap();+ match cpu.run().unwrap() {+ VcpuExit::IoOut { port: 0x80, bytes } => assert_eq!(bytes, &[VECTOR]),+ exit => panic!("expected IOAPIC interrupt handler output, got {exit:?}"),+ }+ // SAFETY: GET_IRQCHIP initialized the redirection entries as raw bits.+ assert_ne!(+ unsafe { read_ioapic(&vm).redirtbl[PIN].bits } & REMOTE_IRR,+ 0+ );+ vm.set_irq_line(PIN as u32, false).unwrap();+ match cpu.run().unwrap() {+ VcpuExit::IoOut { port: 0x81, bytes } => assert_eq!(bytes, &[VECTOR]),+ exit => panic!("expected output after LAPIC EOI, got {exit:?}"),+ }+ cpu.complete_pending_io().unwrap();+ // SAFETY: GET_IRQCHIP initialized the redirection entries as raw bits.+ assert_eq!(+ unsafe { read_ioapic(&vm).redirtbl[PIN].bits } & REMOTE_IRR,+ 0+ );+ let saved_pit = platform.pit.unwrap().channels[0];+ let restored_pit = vm.fd.get_pit2().unwrap().channels[0];+ assert_eq!(restored_pit.count, saved_pit.count);+ assert_eq!(restored_pit.mode, saved_pit.mode);+ assert_eq!(restored_pit.rw_mode, saved_pit.rw_mode);+ assert_eq!(restored_pit.gate, saved_pit.gate);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn vm_snapshot_without_pit_leaves_destination_pit_untouched() {+ let source = KvmVm::new().unwrap();+ let mut state = source.save_state().unwrap();+ state.pit = None;+ let destination = KvmVm::new().unwrap();+ let mut pit = destination.fd.get_pit2().unwrap();+ pit.channels[2].count = 0x7654;+ pit.channels[2].mode = 3;+ destination.fd.set_pit2(&pit).unwrap();+ destination.restore_before_vcpus(&state).unwrap();+ destination.restore_after_vcpus(&state).unwrap();+ let actual = destination.fd.get_pit2().unwrap();+ assert_eq!(actual.channels[2].count, pit.channels[2].count);+ assert_eq!(actual.channels[2].mode, pit.channels[2].mode);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn vm_snapshot_platform_values_survive_restore() {+ let source = KvmVm::new().unwrap();+ let mut programmed = source.save_state().unwrap();+ for (id, mask) in [(0, 0xa5), (1, 0x5a)] {+ // SAFETY: captured wrappers contain completely initialized images.+ let mut pic = unsafe { programmed.irqchips[id].as_kvm().chip.pic };+ pic.imr = mask;+ programmed.irqchips[id] = crate::X86IrqchipState::pic(id as u32, pic);+ }+ let redirection = 0x71 | (1u64 << 16) | (3u64 << 56);+ // SAFETY: captured wrappers contain completely initialized images.+ let mut ioapic = unsafe { programmed.irqchips[2].as_kvm().chip.ioapic };+ ioapic.redirtbl[7].bits = redirection;+ programmed.irqchips[2] = crate::X86IrqchipState::ioapic(ioapic);+ for chip in &programmed.irqchips {+ source.fd.set_irqchip(chip.as_kvm()).unwrap();+ }+ let pit = programmed.pit.as_mut().unwrap();+ pit.flags = kvm_bindings::KVM_PIT_FLAGS_SPEAKER_DATA_ON;+ for (i, channel) in pit.channels.iter_mut().enumerate() {+ channel.count = 0x3456 + i as u32;+ channel.mode = i as u8;+ channel.rw_mode = 3;+ channel.gate = 0;+ }+ source.fd.set_pit2(pit).unwrap();+ let clock_offset = 7 * 24 * 60 * 60 * 1_000_000_000u64;+ source+ .fd+ .set_clock(&kvm_bindings::kvm_clock_data {+ clock: clock_offset,+ ..Default::default()+ })+ .unwrap();+ let mut state = crate::X86Vm::save_state(&source).unwrap();+ assert!(state.clock.clock >= clock_offset);+ let started = Instant::now();+ // A stale wall-clock correlation must not advance the restored clock.+ if state.clock.flags & kvm_bindings::KVM_CLOCK_REALTIME != 0 {+ state.clock.realtime -= 60 * 1_000_000_000;+ }+ let destination = KvmVm::new().unwrap();+ crate::X86Vm::restore_before_vcpus(&destination, &state).unwrap();+ crate::X86Vm::restore_after_vcpus(&destination, &state).unwrap();+ for (id, expected) in state.irqchips.iter().enumerate() {+ let mut actual = kvm_irqchip {+ chip_id: id as u32,+ ..Default::default()+ };+ destination.fd.get_irqchip(&mut actual).unwrap();+ // SAFETY: GET_IRQCHIP initializes each full union image.+ assert_eq!(unsafe { actual.chip.dummy }, unsafe {+ expected.as_kvm().chip.dummy+ });+ }+ // SAFETY: these chip IDs select the PIC and IOAPIC union members.+ unsafe {+ assert_eq!(state.irqchips[0].as_kvm().chip.pic.imr, 0xa5);+ assert_eq!(state.irqchips[1].as_kvm().chip.pic.imr, 0x5a);+ assert_eq!(+ state.irqchips[2].as_kvm().chip.ioapic.redirtbl[7].bits,+ redirection+ );+ }+ let actual_pit = destination.fd.get_pit2().unwrap();+ assert_eq!(+ actual_pit.flags,+ kvm_bindings::KVM_PIT_FLAGS_SPEAKER_DATA_ON+ );+ for (i, channel) in actual_pit.channels.iter().enumerate() {+ assert_eq!(channel.count, 0x3456 + i as u32);+ assert_eq!(+ (channel.mode, channel.rw_mode, channel.gate),+ (i as u8, 3, 0)+ );+ }+ let actual_clock = destination.fd.get_clock().unwrap();+ assert!(actual_clock.clock >= state.clock.clock);+ assert!(+ actual_clock.clock - state.clock.clock+ < started.elapsed().as_nanos() as u64 + 1_000_000_000+ );+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn vm_snapshot_preserves_unused_pit() {+ let source = KvmVm::new().unwrap();+ let state = source.save_state().unwrap();+ assert!(state.pit.is_some(), "created, unused PIT is not absent");+ let destination = KvmVm::new().unwrap();+ let mut dirty = destination.fd.get_pit2().unwrap();+ dirty.channels[2].count = 0x7654;+ dirty.channels[2].mode = 3;+ destination.fd.set_pit2(&dirty).unwrap();+ destination.restore_before_vcpus(&state).unwrap();+ destination.restore_after_vcpus(&state).unwrap();+ let actual = destination.fd.get_pit2().unwrap();+ let mut expected = state.pit.unwrap();+ // SET_PIT2 reloads channels 1/2 against destination host monotonic time;+ // their host timestamps are not restored verbatim by the kernel.+ for i in 1..3 {+ assert!(actual.channels[i].count_load_time >= expected.channels[i].count_load_time);+ expected.channels[i].count_load_time = actual.channels[i].count_load_time;+ }+ assert_eq!(actual.channels, expected.channels);+ assert_eq!(actual.flags, expected.flags);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_state_runs_on_a_fresh_vcpu() {+ snapshot_run_sse_and_msrs(false);+ }++ #[test]+ #[ignore = "requires Linux x86_64 with access to /dev/kvm"]+ fn snapshot_restore_preserves_xsave_when_fpu_image_diverges() {+ snapshot_run_sse_and_msrs(true);+ }++ fn snapshot_run_sse_and_msrs(diverging_fpu: bool) {+ // .code16: load DS=0x10/ES=0x20; enable SSE in CR4; load XMM0 from+ // CS:0x1700 and fill XMM3 with ones; WRMSR KERNEL_GS_BASE=0x12345678;+ // load EAX/EBX/ESI/EDI with distinct values; OUT 0x80.+ // Continuation: store GPRs, selectors, XMM0/XMM3 and RDMSR's result+ // through CS (DS has a nonzero base); OUT 0x81 signals completion.+ let program = [+ 0xb8, 0x10, 0x00, 0x8e, 0xd8, 0xb8, 0x20, 0x00, 0x8e, 0xc0, 0x0f, 0x20, 0xe0, 0x66,+ 0x0d, 0x00, 0x06, 0x00, 0x00, 0x0f, 0x22, 0xe0, 0x2e, 0xf3, 0x0f, 0x6f, 0x06, 0x00,+ 0x17, 0x66, 0x0f, 0x76, 0xdb, 0x66, 0xb9, 0x02, 0x01, 0x00, 0xc0, 0x66, 0xb8, 0x78,+ 0x56, 0x34, 0x12, 0x66, 0x31, 0xd2, 0x0f, 0x30, 0x66, 0xb8, 0x44, 0x33, 0x22, 0x11,+ 0x66, 0xbb, 0x88, 0x77, 0x66, 0x55, 0x66, 0xbe, 0xcc, 0xbb, 0xaa, 0x99, 0x66, 0xbf,+ 0x00, 0xff, 0xee, 0xdd, 0xe6, 0x80, 0x2e, 0x66, 0xa3, 0x00, 0x18, 0x2e, 0x66, 0x89,+ 0x1e, 0x04, 0x18, 0x2e, 0x66, 0x89, 0x36, 0x08, 0x18, 0x2e, 0x66, 0x89, 0x3e, 0x0c,+ 0x18, 0x8c, 0xd8, 0x2e, 0xa3, 0x10, 0x18, 0x8c, 0xc0, 0x2e, 0xa3, 0x12, 0x18, 0x2e,+ 0xf3, 0x0f, 0x7f, 0x06, 0x20, 0x18, 0x2e, 0xf3, 0x0f, 0x7f, 0x1e, 0x30, 0x18, 0x66,+ 0xb9, 0x02, 0x01, 0x00, 0xc0, 0x0f, 0x32, 0x2e, 0x66, 0xa3, 0x40, 0x18, 0x2e, 0x66,+ 0x89, 0x16, 0x44, 0x18, 0xe6, 0x81,+ ];+ let ram = Ram::new();+ let xmm: [u8; 16] = std::array::from_fn(|i| (i * 13 + 7) as u8);+ // SAFETY: RAM is not yet registered with a VM; both ranges fit.+ unsafe {+ std::ptr::copy_nonoverlapping(program.as_ptr(), ram.0.as_ptr(), program.len());+ std::ptr::copy_nonoverlapping(xmm.as_ptr(), ram.0.as_ptr().add(0x700), xmm.len());+ }+ let vm = KvmVm::new().unwrap();+ // SAFETY: RAM outlives both VMs and their CPUs; only one runs at a time.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ let mut source = vm.create_vcpu(0).unwrap();+ source.set_cpu_features(&snapshot_cpuid(&vm), &[]).unwrap();+ let mut segments = source.fd.get_sregs().unwrap();+ segments.cs.base = 0;+ segments.cs.selector = 0;+ source.fd.set_sregs(&segments).unwrap();+ source+ .fd+ .set_regs(&kvm_regs {+ rip: 0x1000,+ rflags: 2,+ ..Default::default()+ })+ .unwrap();+ assert!(matches!(+ source.run().unwrap(),+ VcpuExit::IoOut { port: 0x80, .. }+ ));+ assert_vcpu_save_error(+ source.save_state().unwrap_err(),+ "complete pending I/O before saving",+ );+ source.complete_pending_io().unwrap();+ let platform = vm.save_state().unwrap();+ let mut state = crate::X86Vcpu::save_state(&mut source).unwrap();+ assert_eq!(state.regs.rip, 0x104c);+ assert_eq!(state.fpu.xmm[0], xmm);+ if diverging_fpu {+ // The standard XSAVE layout starts XMM0 at byte 160.+ let saved_xmm: Vec<_> = state.xsave[40..44]+ .iter()+ .flat_map(|word| word.to_le_bytes())+ .collect();+ assert_eq!(saved_xmm, xmm);+ state.fpu.xmm[0] = xmm.map(|byte| !byte);+ }+ drop(source);+ drop(vm);++ let destination_vm = KvmVm::new().unwrap();+ // SAFETY: same lifetime/serialization contract as the source mapping.+ unsafe { destination_vm.map_memory(&ram.region()) }.unwrap();+ destination_vm.restore_before_vcpus(&platform).unwrap();+ let mut destination = destination_vm.create_vcpu(0).unwrap();+ crate::X86Vcpu::restore_state(&mut destination, &state).unwrap();+ destination_vm.restore_after_vcpus(&platform).unwrap();+ assert_eq!(destination.fd.get_regs().unwrap(), state.regs);+ if !diverging_fpu {+ assert_eq!(destination.fd.get_fpu().unwrap(), state.fpu);+ }+ assert_eq!(destination.fd.get_xcrs().unwrap(), state.xcrs);+ assert_eq!(destination.fd.get_debug_regs().unwrap(), state.debug_regs);+ assert_eq!(destination.fd.get_mp_state().unwrap(), state.mp_state);+ // SAFETY: neither CPU is running, and this range is within RAM.+ let output = unsafe { std::slice::from_raw_parts(ram.0.as_ptr().add(0x800), 0x48) };+ assert!(+ output.iter().all(|&byte| byte == 0),+ "restore must not enter the guest"+ );+ // End the host borrow before KVM writes into the page.+ assert!(matches!(+ destination.run().unwrap(),+ VcpuExit::IoOut { port: 0x81, .. }+ ));+ // SAFETY: KVM_RUN has returned; no concurrent guest or host writes.+ let output = unsafe { std::slice::from_raw_parts(ram.0.as_ptr().add(0x800), 0x48) };+ for (offset, expected) in [+ (0, 0x11223344u32),+ (4, 0x55667788),+ (8, 0x99aabbcc),+ (12, 0xddeeff00),+ ] {+ assert_eq!(&output[offset..offset + 4], &expected.to_le_bytes());+ }+ assert_eq!(&output[0x10..0x14], &[0x10, 0, 0x20, 0]);+ assert_eq!(&output[0x20..0x30], &xmm);+ assert_eq!(&output[0x30..0x40], &[0xff; 16]);+ assert_eq!(&output[0x40..0x48], &0x12345678u64.to_le_bytes());+ }++ #[test]+ #[ignore = "requires /dev/kvm"]+ fn snapshot_restores_ap_at_pending_sipi_vector() {+ use crate::{X86BootRegisters, X86Segment};+ use kvm_bindings::{KVM_MP_STATE_INIT_RECEIVED, KVM_MP_STATE_RUNNABLE, kvm_mp_state};++ const SIPI_VECTOR: u8 = 0x02;+ const SIPI_ENTRY: u64 = (SIPI_VECTOR as u64) << 12;+ const STALE_ENTRY: u64 = 0x1000;+ const BSP_ENTRY: u64 = 0x1100;++ let ram = Ram::new();+ let sipi_ram = Ram::new();+ let sipi_region = MemoryRegion {+ guest_addr: SIPI_ENTRY,+ ..sipi_ram.region()+ };+ // Real mode: MOV AL, byte; OUT 0x80, AL; HLT.+ let stale_code = [0xb0, b'X', 0xe6, 0x80, 0xf4];+ let sipi_code = [0xb0, b'S', 0xe6, 0x80, 0xf4];+ // Flat 32-bit mode: write the xAPIC registers, then signal completion.+ #[rustfmt::skip]+ let bsp_code = [+ // MOV dword [0xfee000f0], 0x1ff (enable the LAPIC).+ 0xc7, 0x05, 0xf0, 0x00, 0xe0, 0xfe, 0xff, 0x01, 0x00, 0x00,+ // MOV dword [0xfee00310], 0x01000000 (ICR high, APIC ID 1).+ 0xc7, 0x05, 0x10, 0x03, 0xe0, 0xfe, 0x00, 0x00, 0x00, 0x01,+ // MOV dword [0xfee00300], 0x4602 (ICR low, assert SIPI).+ 0xc7, 0x05, 0x00, 0x03, 0xe0, 0xfe, SIPI_VECTOR, 0x46, 0x00, 0x00,+ 0xe6, 0x81, 0xf4, // OUT 0x81, AL; HLT.+ ];+ // SAFETY: both pages are private and unmapped from the guest, and each+ // program fits at its offset without overlapping another program.+ unsafe {+ std::ptr::copy_nonoverlapping(stale_code.as_ptr(), ram.0.as_ptr(), stale_code.len());+ std::ptr::copy_nonoverlapping(+ bsp_code.as_ptr(),+ ram.0.as_ptr().add((BSP_ENTRY - STALE_ENTRY) as usize),+ bsp_code.len(),+ );+ std::ptr::copy_nonoverlapping(sipi_code.as_ptr(), sipi_ram.0.as_ptr(), sipi_code.len());+ }+ let vm = KvmVm::new().unwrap();+ // SAFETY: both pages outlive the VM and all vCPUs.+ unsafe {+ vm.map_memory(&ram.region()).unwrap();+ vm.map_memory(&sipi_region).unwrap();+ }+ let (platform, state) = thread::scope(|scope| {+ let vm = &vm;+ let (ap_ready, wait_for_ap) = mpsc::channel();+ // Spawn before creating the AP so the BSP worker inherits an+ // unblocked kick signal that it can reserve for itself.+ let bsp = scope.spawn(move || {+ let mut bsp = vm.create_vcpu(0).unwrap();+ bsp.set_cpu_features(&snapshot_cpuid(vm), &[]).unwrap();+ bsp.set_boot_registers(&X86BootRegisters {+ rip: BSP_ENTRY,+ rflags: 2,+ cr0: 0x11, // Protected mode, ET, paging disabled.+ code: X86Segment {+ limit: u32::MAX,+ selector: 8,+ attributes: 0xc09b,+ ..Default::default()+ },+ data: X86Segment {+ limit: u32::MAX,+ selector: 16,+ attributes: 0xc093,+ ..Default::default()+ },+ ..Default::default()+ })+ .unwrap();+ wait_for_ap.recv().unwrap();+ assert!(matches!(+ bsp.run().unwrap(),+ VcpuExit::IoOut { port: 0x81, .. }+ ));+ bsp.complete_pending_io().unwrap();+ });++ let mut ap = vm.create_vcpu(1).unwrap();+ ap.set_cpu_features(&snapshot_cpuid(vm), &[]).unwrap();+ let mut segments = ap.fd.get_sregs().unwrap();+ segments.cs.selector = 0;+ segments.cs.base = 0;+ ap.fd.set_sregs(&segments).unwrap();+ ap.fd+ .set_regs(&kvm_regs {+ rip: STALE_ENTRY,+ rflags: 2,+ ..Default::default()+ })+ .unwrap();+ ap.fd+ .set_mp_state(kvm_mp_state {+ mp_state: KVM_MP_STATE_INIT_RECEIVED,+ })+ .unwrap();++ // The BSP queues the SIPI while the AP stays out of KVM_RUN.+ ap_ready.send(()).unwrap();+ bsp.join().unwrap();+ (vm.save_state().unwrap(), ap.save_state().unwrap())+ });++ assert_eq!(state.mp_state.mp_state, KVM_MP_STATE_RUNNABLE);+ assert_eq!(state.sregs.cs.selector, u16::from(SIPI_VECTOR) << 8);+ assert_eq!(state.sregs.cs.base, SIPI_ENTRY);+ assert_eq!(state.regs.rip, 0);+ drop(vm);++ let destination = KvmVm::new().unwrap();+ // SAFETY: the source VM is gone, and both pages outlive the destination.+ unsafe {+ destination.map_memory(&ram.region()).unwrap();+ destination.map_memory(&sipi_region).unwrap();+ }+ destination.restore_before_vcpus(&platform).unwrap();+ let mut ap_dst = destination.create_vcpu(1).unwrap();+ ap_dst.restore_state(&state).unwrap();+ destination.restore_after_vcpus(&platform).unwrap();+ let exit = thread::scope(|scope| {+ let kick = ap_dst.handle();+ let (finished, done) = mpsc::channel::<()>();+ scope.spawn(move || {+ let timeout = Duration::from_secs(5);+ if let Err(mpsc::RecvTimeoutError::Timeout) = done.recv_timeout(timeout) {+ kick.kick().unwrap();+ }+ });+ let exit = ap_dst.run();+ drop(finished);+ exit+ });+ match exit.unwrap() {+ VcpuExit::IoOut { port: 0x80, bytes } => assert_eq!(bytes, b"S"),+ exit => panic!("expected AP output at the SIPI vector, got {exit:?}"),+ }+ ap_dst.complete_pending_io().unwrap();+ }++ #[test]+ #[ignore = "requires Linux x86_64 with AVX and access to /dev/kvm"]+ fn snapshot_restores_ymm_high_halves_on_a_fresh_vcpu() {+ use crate::{X86BootRegisters, X86Segment};++ // .code32: enable x87/SSE/AVX in XCR0; VMOVDQU YMM0,[0x1700]; OUT 0x80.+ // After restore: VMOVDQU [0x1800],YMM0; OUT 0x81.+ let program = [+ 0x31, 0xc9, 0xb8, 0x07, 0x00, 0x00, 0x00, 0x31, 0xd2, 0x0f, 0x01, 0xd1, 0xc5, 0xfe,+ 0x6f, 0x05, 0x00, 0x17, 0x00, 0x00, 0xe6, 0x80, 0xc5, 0xfe, 0x7f, 0x05, 0x00, 0x18,+ 0x00, 0x00, 0xe6, 0x81,+ ];+ let ymm: [u8; 32] = std::array::from_fn(|i| (i * 7 + 1) as u8);+ let ram = Ram::new();+ // SAFETY: neither range is registered or concurrently accessed; both fit.+ unsafe {+ std::ptr::copy_nonoverlapping(program.as_ptr(), ram.0.as_ptr(), program.len());+ std::ptr::copy_nonoverlapping(ymm.as_ptr(), ram.0.as_ptr().add(0x700), ymm.len());+ }+ let vm = KvmVm::new().unwrap();+ let leaf1 = vm+ .supported_cpuid()+ .iter()+ .find(|entry| entry.leaf == 1)+ .unwrap();+ if leaf1.ecx & (1 << 28) == 0 {+ eprintln!("skipping YMM snapshot test: KVM does not expose AVX");+ return;+ }+ // SAFETY: RAM outlives both VMs; only one CPU executes at a time.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ let mut source = vm.create_vcpu(0).unwrap();+ source.set_cpu_features(&snapshot_cpuid(&vm), &[]).unwrap();+ source+ .set_boot_registers(&X86BootRegisters {+ rip: 0x1000,+ rflags: 2,+ cr0: 0x11, // Protected mode, ET; EM and TS clear.+ cr4: (1 << 18) | (1 << 10) | (1 << 9), // OSXSAVE, OSXMMEXCPT, OSFXSR.+ code: X86Segment {+ limit: u32::MAX,+ selector: 8,+ attributes: 0xc09b,+ ..Default::default()+ },+ data: X86Segment {+ limit: u32::MAX,+ selector: 16,+ attributes: 0xc093,+ ..Default::default()+ },+ ..Default::default()+ })+ .unwrap();+ assert!(matches!(+ source.run().unwrap(),+ VcpuExit::IoOut { port: 0x80, .. }+ ));+ source.complete_pending_io().unwrap();+ let platform = vm.save_state().unwrap();+ let state = source.save_state().unwrap();+ // The standard XSAVE layout starts YMM_Hi128 at byte 576.+ let high: Vec<_> = state.xsave[144..148]+ .iter()+ .flat_map(|word| word.to_le_bytes())+ .collect();+ assert_eq!(high, ymm[16..]);+ drop(source);+ drop(vm);++ let vm = KvmVm::new().unwrap();+ // SAFETY: same backing lifetime and serialized access as above.+ unsafe { vm.map_memory(&ram.region()) }.unwrap();+ vm.restore_before_vcpus(&platform).unwrap();+ let mut destination = vm.create_vcpu(0).unwrap();+ destination.restore_state(&state).unwrap();+ vm.restore_after_vcpus(&platform).unwrap();+ assert!(matches!(+ destination.run().unwrap(),+ VcpuExit::IoOut { port: 0x81, .. }+ ));+ // SAFETY: guest execution has stopped and the output lies within RAM.+ let output = unsafe { std::slice::from_raw_parts(ram.0.as_ptr().add(0x800), 32) };+ assert_eq!(+ &output[16..],+ &ymm[16..],+ "YMM high half lost during restore"+ );+ assert_eq!(output, &ymm);+ }+#[test]#[ignore = "requires Linux x86_64 with access to /dev/kvm"]fn constructor_creates_interrupt_controller_and_timer() {diff --git a/src/hypervisor/src/vcpu.rs b/src/hypervisor/src/vcpu.rsindex b8633e2c6..d5a52d87e 100644--- a/src/hypervisor/src/vcpu.rs+++ b/src/hypervisor/src/vcpu.rs@@ -25,10 +25,34 @@ pub trait Vcpu {/// subsequent call does not complete it twice.fn complete_pending_io(&mut self) -> Result<()>;+ /// Notifies the guest that its clock was interrupted, while stopped on+ /// the owning thread. An unused guest clock is a successful no-op; backends+ /// without this capability report Unsupported (with placeholder CPU id 0).+ ///+ /// On a KVM destination, call this on each vCPU's owning thread after+ /// `X86Vcpu::restore_state` installs its pvclock MSRs and before its first+ /// [`Vcpu::run`].+ fn notify_guest_stopped(&mut self) -> Result<()> {+ Err(crate::Error::ConfigureVcpu {+ id: 0,+ operation: "notify guest stopped (unsupported backend)",+ source: std::io::Error::from(std::io::ErrorKind::Unsupported),+ })+ }+/// Returns a handle other threads use to kick this vCPU.fn handle(&self) -> Self::Handle;}+#[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))]+pub(crate) fn kvmclock_ctrl_result(result: std::io::Result<()>) -> std::io::Result<()> {+ match result {+ // KVM's kvm_set_guest_paused returns EINVAL when pv_time is inactive.+ Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => Ok(()),+ result => result,+ }+}+/// Forces one vCPU out of the guest, from any thread.pub trait VcpuHandle: Clone + Send + Sync {/// Makes the vCPU's [`Vcpu::run`] return [`VcpuExit::Interrupted`].@@ -37,3 +61,66 @@ pub trait VcpuHandle: Clone + Send + Sync {/// Kicking a dropped vCPU does nothing.fn kick(&self) -> Result<()>;}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io;++ #[test]+ fn kvmclock_inactive_pvclock_is_a_noop() {+ assert!(kvmclock_ctrl_result(Err(io::Error::from(io::ErrorKind::InvalidInput))).is_ok());+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ assert!(kvmclock_ctrl_result(Err(io::Error::from_raw_os_error(libc::EINVAL))).is_ok());+ assert!(kvmclock_ctrl_result(Ok(())).is_ok());+ }++ #[test]+ fn notify_guest_stopped_defaults_to_unsupported() {+ #[derive(Clone)]+ struct Cpu;++ impl VcpuHandle for Cpu {+ fn kick(&self) -> Result<()> {+ unreachable!()+ }+ }++ impl Vcpu for Cpu {+ type Handle = Self;++ fn run(&mut self) -> Result<VcpuExit<'_>> {+ unreachable!()+ }++ fn complete_pending_io(&mut self) -> Result<()> {+ unreachable!()+ }++ fn handle(&self) -> Self::Handle {+ Self+ }+ }++ assert!(matches!(+ Cpu.notify_guest_stopped(),+ Err(crate::Error::ConfigureVcpu {+ id: 0,+ operation: "notify guest stopped (unsupported backend)",+ source,+ }) if source.kind() == io::ErrorKind::Unsupported+ ));+ }++ #[test]+ fn kvmclock_ioctl_failures_are_preserved() {+ for kind in [io::ErrorKind::PermissionDenied, io::ErrorKind::Unsupported] {+ assert_eq!(+ kvmclock_ctrl_result(Err(io::Error::from(kind)))+ .unwrap_err()+ .kind(),+ kind+ );+ }+ }+}diff --git a/src/hypervisor/src/x86.rs b/src/hypervisor/src/x86.rsindex 7759a5b69..3b6bb8b17 100644--- a/src/hypervisor/src/x86.rs+++ b/src/hypervisor/src/x86.rs@@ -58,17 +58,80 @@ pub struct X86BootRegisters {pub idt_limit: u16,}-/// The x86 operations a VM offers the machine's boot loader.+/// Boot configuration and paused platform-state transfer for an x86 VM.pub trait X86Vm: Vm<Vcpu: X86Vcpu> {+ /// Captures VM-global state and starts a snapshot round with all vCPUs and+ /// IRQ producers stopped. Complete pending userspace I/O first, then save+ /// the VM and call [`X86Vcpu::save_state`] once per vCPU in the round.+ /// Non-snapshot backends report Unsupported.+ #[cfg(target_os = "linux")]+ fn save_state(&self) -> Result<X86VmState> {+ Err(crate::Error::vm_state(+ "save",+ std::io::Error::new(std::io::ErrorKind::Unsupported, "unsupported backend"),+ ))+ }++ /// Restores the VM clock offset after RAM is mapped and before any+ /// [`X86Vcpu::restore_state`] call on the identically configured destination.+ /// Discard the destination after any ioctl error: writes are not transactional.+ #[cfg(target_os = "linux")]+ fn restore_before_vcpus(&self, _state: &X86VmState) -> Result<()> {+ Err(crate::Error::vm_state(+ "restore",+ std::io::Error::new(std::io::ErrorKind::Unsupported, "unsupported backend"),+ ))+ }++ /// Restores PIC0, PIC1, IOAPIC and PIT2 after every vCPU has completed+ /// [`X86Vcpu::restore_state`] and before any [`Vcpu::run`] call.+ /// Discard the destination after any ioctl error: writes are not transactional.+ #[cfg(target_os = "linux")]+ fn restore_after_vcpus(&self, _state: &X86VmState) -> Result<()> {+ Err(crate::Error::vm_state(+ "restore",+ std::io::Error::new(std::io::ErrorKind::Unsupported, "unsupported backend"),+ ))+ }+/// Host-supported CPUID values, before the VMM applies guest topology and/// policy. They are a ceiling: a guest must not see features beyond them.fn supported_cpuid(&self) -> &[X86CpuidEntry];}-/// The x86 state a vCPU needs before its first guest entry.-///-/// Both writes are not transactional: discard the vCPU after any error.+/// Boot configuration and paused-state transfer for an x86 vCPU.pub trait X86Vcpu: Vcpu {+ /// Captures a stopped CPU without entering the guest. Complete I/O first.+ /// Start each snapshot round with [`X86Vm::save_state`]. KVM rejects saves+ /// before that call and permits one successful save per vCPU in the round.+ /// A failed capture can be retried in the same round.+ /// The image is architecture- and host-version-specific. The default reports+ /// Unsupported (with placeholder CPU id 0) for non-snapshot backends/mocks.+ #[cfg(target_os = "linux")]+ fn save_state(&mut self) -> Result<X86VcpuState> {+ Err(crate::Error::ConfigureVcpu {+ id: 0,+ operation: "save CPU state (unsupported backend)",+ source: std::io::Error::from(std::io::ErrorKind::Unsupported),+ })+ }++ /// Overwrites a fresh CPU after [`X86Vm::restore_before_vcpus`] without+ /// entering the guest. Discard the destination VM on any error once the+ /// first restore write is attempted. The default reports Unsupported+ /// (with placeholder CPU id 0) for non-snapshot backends/mocks.+ /// After this Linux-only restore installs the pvclock MSRs, call the+ /// cross-platform [`Vcpu::notify_guest_stopped`] on each vCPU's owning+ /// thread before its first [`Vcpu::run`].+ #[cfg(target_os = "linux")]+ fn restore_state(&mut self, _state: &X86VcpuState) -> Result<()> {+ Err(crate::Error::ConfigureVcpu {+ id: 0,+ operation: "restore CPU state (unsupported backend)",+ source: std::io::Error::from(std::io::ErrorKind::Unsupported),+ })+ }+/// Installs the machine's CPUID and MSR policy. Call it before/// [`set_boot_registers`](Self::set_boot_registers).fn set_cpu_features(&mut self, cpuid: &[X86CpuidEntry], msrs: &[X86Msr]) -> Result<()>;@@ -78,20 +141,31 @@ pub trait X86Vcpu: Vcpu {fn set_boot_registers(&mut self, state: &X86BootRegisters) -> Result<()>;}-#[cfg(target_os = "linux")]-const MAX_SNAPSHOT_CPUID_ENTRIES: usize = 256;--/// VM-global KVM x86 platform state for the same host and KVM environment.-/// The wire format is unstable. RAM, per-vCPU state, IRQ routing and-/// device/irqfd configuration are separate.+/// VM-global KVM x86 platform state; not a portable or stable wire format.+///+/// Only supported on the same host and KVM environment, with the same enabled+/// VM capabilities (including in-kernel IRQ chips and PIT creation flags). All vCPUs,+/// userspace I/O and external IRQ producers must be quiescent during transfer.+/// RAM, per-vCPU state, IRQ routing and device/irqfd configuration are separate.+/// KVM's running timers make capture non-atomic even with stopped vCPUs.+/// KVM_SET_PIT2 rebases the host `count_load_time` for channels 1 and 2 and+/// restarts channel 0 with its initial `count`. This loses sub-tick phase+/// and can re-arm one-shot modes 0, 1 and 4.+///+/// A created PIT is captured even if the guest never programmed it: its reset+/// channels/flags must overwrite the destination, not be confused with no PIT.#[cfg(target_os = "linux")]#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]pub struct X86VmState {/// PIC master (0), PIC slave (1), IOAPIC (2), in that order.pub irqchips: [X86IrqchipState; 3],/// None only when the source never created an in-kernel PIT.+ #[serde(with = "exact_abi_option_serde")]pub pit: Option<kvm_bindings::kvm_pit_state2>,- /// Full KVM clock image with guest nanoseconds, flags, realtime and host TSC.+ /// Full GET_CLOCK image: guest nanoseconds (from which SET_CLOCK rebuilds+ /// the offset), flags, realtime and host TSC correlation. Restore excludes+ /// snapshot downtime by passing zero flags to SET_CLOCK.+ #[serde(with = "exact_abi_serde")]pub clock: kvm_bindings::kvm_clock_data,}@@ -99,11 +173,11 @@ pub struct X86VmState {////// Unlike a public raw union, the private image cannot be replaced with a/// partially initialized member. Constructors zero it before writing a payload;-/// deserialization zero-fills the backing buffer. Exposes only shared access.+/// deserialization requires a full ABI image. Exposes only shared access.#[cfg(target_os = "linux")]#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]#[serde(transparent)]-pub struct X86IrqchipState(kvm_bindings::kvm_irqchip);+pub struct X86IrqchipState(#[serde(with = "exact_abi_serde")] kvm_bindings::kvm_irqchip);#[cfg(target_os = "linux")]impl X86IrqchipState {@@ -159,25 +233,49 @@ impl PartialEq for X86IrqchipState {.zip(&b.redirtbl).all(|(a, b)| a.bits == b.bits)}- // Unknown IDs remain comparable; KVM handles ioctl validation.+ // Unknown IDs compare deterministically. Restore validates the+ // expected IRQ chip IDs before issuing ioctls._ => a.chip.dummy == b.chip.dummy,}}}}-/// A paused KVM x86 CPU image specific to the host CPU and KVM/kernel version.-/// The wire format is unstable.+/// A paused KVM x86 CPU image, specific to this architecture, host CPU and+/// KVM/kernel version; not a portable or stable wire format.+///+/// KVM_SET_XSAVE restores x87, SSE and enabled extended state from `xsave`.+/// The image also carries the dedicated FPU capture and owned CPUID/MSR arrays.+/// Capture probes KVM's advertised MSRs plus the 28 writable MTRRs, IA32_XSS,+/// and IA32_DEBUGCTLMSR. Capture and restore gate SGX launch key hashes on+/// SGX_LC and IA32_PERF_CAPABILITIES on PDCM and a nonzero PMU version in CPUID.+/// It excludes MTRRcap, Hyper-V's+/// `0x4000_0000..=0x4000_01ff` window and the x2APIC range carried by `lapic`.+/// MCE bank configuration via KVM_X86_SETUP_MCE is outside this interface.+///+/// When KVM exposes KVM_VCPU_TSC_OFFSET, vCPUs share a host TSC reference per+/// frequency at the VM clock capture and restore points. The resulting offsets+/// preserve their relative TSC skew. Legacy kernels use direct TSC MSR access.+/// Restore writes TSC_ADJUST and TSC first. The async page-fault interrupt+/// vector and IA32_PERF_CAPABILITIES precede ordinary MSRs, followed by+/// IA32_FEATURE_CONTROL, TSC_DEADLINE, then RTIT_CTL. APICv requires the host+/// kernel fix `9cfec6d097c6` or its backport for LAPIC transfer.///-/// Includes the entire XSAVE area (including AVX and newer enabled components)-/// in addition to the dedicated FPU image. CPUID/MSR flexible arrays are owned.-/// The LAPIC image represents the x2APIC register range. The TSC frequency is-/// per-vCPU. Nested virtualization, Hyper-V SynIC, guest-debug configuration,-/// VM-wide state and RAM are outside this image.+/// Requires completed userspace I/O and a stopped vCPU. Nested virtualization,+/// Hyper-V SynIC, guest-debug configuration, VM clock/irqchip/PIT state and RAM+/// are intentionally outside this image; restore those separately if used.+/// Restore requires a fresh, never-entered vCPU so omitted optional facilities+/// retain reset state, never arbitrary destination state. Do not enable dynamic+/// host XSTATE permissions after creating either the source or destination vCPU.+/// Capture and restore reject paged 32-bit PAE because SREGS omits cached PDPTRs.+/// They also reject CPUID that exposes CET shadow stack (SHSTK) because the+/// image cannot represent its complete state. Both require a nonempty CPUID.#[cfg(target_os = "linux")]#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]pub struct X86VcpuState {+ #[serde(with = "exact_abi_serde")]pub regs: kvm_bindings::kvm_regs,+ #[serde(with = "exact_abi_serde")]pub sregs: kvm_bindings::kvm_sregs,#[serde(with = "fpu_serde")]pub fpu: kvm_bindings::kvm_fpu,@@ -186,25 +284,119 @@ pub struct X86VcpuState {/// with room for host XSTATE components beyond the fixed KVM region.#[serde(deserialize_with = "vcpu_state_serde::words::<_, _, 65536>")]pub xsave: Vec<u32>,- /// Captured CPUID leaves, with a decode limit of 256 entries matching KVM.- #[serde(deserialize_with = "vcpu_state_serde::entries::<_, _, MAX_SNAPSHOT_CPUID_ENTRIES>")]+ /// Captured CPUID leaves; decoding uses KVM's maximum entry count,+ /// matching the buffer accepted by the restore path.+ #[serde(+ deserialize_with = "vcpu_state_serde::entries::<_, _, { kvm_bindings::KVM_MAX_CPUID_ENTRIES }>"+ )]pub cpuid: Vec<kvm_bindings::kvm_cpuid_entry2>,- /// Readable KVM-advertised MSRs; decoding permits at most 4096 entries.+ /// Readable MSRs from the filtered KVM-advertised and supplemental list.+ /// Decoding permits at most 4096 entries./// This is a decoding policy, not KVM's per-ioctl MSR batch limit.- #[serde(deserialize_with = "vcpu_state_serde::entries::<_, _, 4096>")]+ #[serde(deserialize_with = "vcpu_state_serde::entries::<_, _, MAX_SNAPSHOT_MSR_ENTRIES>")]pub msrs: Vec<kvm_bindings::kvm_msr_entry>,+ #[serde(with = "exact_abi_serde")]pub xcrs: kvm_bindings::kvm_xcrs,+ #[serde(with = "exact_abi_serde")]pub debug_regs: kvm_bindings::kvm_debugregs,+ #[serde(with = "exact_abi_serde")]pub events: kvm_bindings::kvm_vcpu_events,+ #[serde(with = "exact_abi_serde")]pub mp_state: kvm_bindings::kvm_mp_state,+ #[serde(with = "exact_abi_serde")]pub lapic: kvm_bindings::kvm_lapic_state,pub tsc_khz: u32,}+#[cfg(target_os = "linux")]+pub(crate) const MAX_SNAPSHOT_MSR_ENTRIES: usize = 4096;++#[cfg(target_os = "linux")]+mod exact_abi_serde {+ use serde::{Deserialize, Deserializer, Serialize, Serializer, de};+ use std::{fmt, marker::PhantomData};++ pub(super) fn serialize<S: Serializer, T: Serialize>(+ value: &T,+ s: S,+ ) -> Result<S::Ok, S::Error> {+ value.serialize(s)+ }++ pub(super) fn deserialize<'de, D: Deserializer<'de>, T: de::DeserializeOwned>(+ d: D,+ ) -> Result<T, D::Error> {+ struct AbiBytes<T>(PhantomData<T>);++ impl<'de, T: de::DeserializeOwned> de::Visitor<'de> for AbiBytes<T> {+ type Value = T;++ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "exactly {} ABI bytes", size_of::<T>())+ }++ fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<T, E> {+ if bytes.len() != size_of::<T>() {+ return Err(E::invalid_length(bytes.len(), &self));+ }+ T::deserialize(de::value::BorrowedBytesDeserializer::new(bytes))+ }++ fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<T, A::Error> {+ let expected = size_of::<T>();+ if let Some(len) = seq.size_hint().filter(|&len| len != expected) {+ return Err(de::Error::invalid_length(len, &self));+ }+ let mut bytes = Vec::with_capacity(expected);+ for i in 0..expected {+ bytes.push(+ seq.next_element::<u8>()?+ .ok_or_else(|| de::Error::invalid_length(i, &self))?,+ );+ }+ if seq.next_element::<u8>()?.is_some() {+ return Err(de::Error::invalid_length(expected + 1, &self));+ }+ self.visit_bytes(&bytes)+ }+ }++ d.deserialize_bytes(AbiBytes(PhantomData))+ }++ pub(super) struct ExactAbi<T>(pub(super) T);++ impl<'de, T: de::DeserializeOwned> Deserialize<'de> for ExactAbi<T> {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ deserialize(d).map(Self)+ }+ }+}++#[cfg(target_os = "linux")]+mod exact_abi_option_serde {+ use super::exact_abi_serde::ExactAbi;+ use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};++ pub(super) fn serialize<S: Serializer, T: Serialize>(+ value: &Option<T>,+ s: S,+ ) -> Result<S::Ok, S::Error> {+ value.serialize(s)+ }++ pub(super) fn deserialize<'de, D: Deserializer<'de>, T: DeserializeOwned>(+ d: D,+ ) -> Result<Option<T>, D::Error> {+ Option::<ExactAbi<T>>::deserialize(d).map(|value| value.map(|entry| entry.0))+ }+}+// Bounds are checked before reading elements; never reserve from an untrusted// length. These guards also protect callers that decode X86VcpuState directly.#[cfg(target_os = "linux")]mod vcpu_state_serde {+ use super::exact_abi_serde::ExactAbi;use serde::{Deserialize, Deserializer,de::{self, SeqAccess, Visitor},@@ -254,9 +446,10 @@ mod vcpu_state_serde {pub(super) fn entries<'de, D, T, const N: usize>(d: D) -> Result<Vec<T>, D::Error>whereD: Deserializer<'de>,- T: Deserialize<'de>,+ T: de::DeserializeOwned,{- bounded::<D, T, N>(d)+ bounded::<D, ExactAbi<T>, N>(d)+ .map(|entries| entries.into_iter().map(|entry| entry.0).collect())}}@@ -333,64 +526,101 @@ mod fpu_serde {#[cfg(all(test, target_os = "linux"))]mod tests {- #[test]- fn cpu_sequences_enforce_declared_count_and_bound_before_elements() {- use serde::{- Deserializer,- de::{- DeserializeSeed, SeqAccess, Visitor,- value::{Error, U8Deserializer},- },- };- struct Sequence {- declared: usize,- actual: usize,- reads: usize,+ use super::MAX_SNAPSHOT_MSR_ENTRIES;+ use kvm_bindings::KVM_MAX_CPUID_ENTRIES;+ use serde::{+ Deserializer,+ de::{+ DeserializeSeed, SeqAccess, Visitor,+ value::{Error, U8Deserializer},+ },+ };+ struct Sequence {+ declared: Option<usize>,+ actual: usize,+ reads: usize,+ }+ impl<'de> SeqAccess<'de> for &mut Sequence {+ type Error = Error;+ fn size_hint(&self) -> Option<usize> {+ self.declared}- impl<'de> SeqAccess<'de> for &mut Sequence {- type Error = Error;- fn size_hint(&self) -> Option<usize> {- Some(self.declared)- }- fn next_element_seed<T: DeserializeSeed<'de>>(- &mut self,- seed: T,- ) -> Result<Option<T::Value>, Error> {- self.reads += 1;- if self.actual == 0 {- return Ok(None);- }- self.actual -= 1;- seed.deserialize(U8Deserializer::new(42)).map(Some)+ fn next_element_seed<T: DeserializeSeed<'de>>(+ &mut self,+ seed: T,+ ) -> Result<Option<T::Value>, Error> {+ self.reads += 1;+ if self.actual == 0 {+ return Ok(None);}+ self.actual -= 1;+ seed.deserialize(U8Deserializer::new(42)).map(Some)}- impl<'de> Deserializer<'de> for &mut Sequence {- type Error = Error;- fn deserialize_any<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Error> {- v.visit_seq(self)- }- serde::forward_to_deserialize_any! {- bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string- bytes byte_buf option unit unit_struct newtype_struct seq tuple- tuple_struct map struct enum identifier ignored_any+ }+ impl<'de> Deserializer<'de> for &mut Sequence {+ type Error = Error;+ fn deserialize_any<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Error> {+ v.visit_seq(self)+ }+ serde::forward_to_deserialize_any! {+ bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string+ bytes byte_buf option unit unit_struct newtype_struct seq tuple+ tuple_struct map struct enum identifier ignored_any+ }+ }++ #[test]+ fn exact_abi_sequence_checks_hints_and_actual_length() {+ type Image = kvm_bindings::kvm_mp_state;+ let width = size_of::<Image>();+ for declared in [Some(0), Some(width - 1), Some(width + 1), Some(usize::MAX)] {+ let mut seq = Sequence {+ declared,+ actual: width,+ reads: 0,+ };+ assert!(super::exact_abi_serde::deserialize::<_, Image>(&mut seq).is_err());+ assert_eq!(seq.reads, 0);+ }+ for declared in [None, Some(width)] {+ for actual in [0, width - 1, width, width + 1] {+ let mut seq = Sequence {+ declared,+ actual,+ reads: 0,+ };+ let result = super::exact_abi_serde::deserialize::<_, Image>(&mut seq);+ if actual == width {+ assert_eq!(result.unwrap().mp_state, u32::from_ne_bytes([42; 4]));+ } else {+ assert!(result.is_err(), "{declared:?}, {actual}");+ }}}- for bound in [65536, 256, 4096] {+ }++ #[test]+ fn cpu_sequences_enforce_declared_count_and_bound_before_elements() {+ for bound in [65536, KVM_MAX_CPUID_ENTRIES, MAX_SNAPSHOT_MSR_ENTRIES] {// No element can be read, hence no element storage can be allocated.let mut seq = Sequence {- declared: bound + 1,+ declared: Some(bound + 1),actual: 1,reads: 0,};let error = match bound {65536 => super::vcpu_state_serde::words::<_, u32, 65536>(&mut seq).unwrap_err(),- 256 => super::vcpu_state_serde::entries::<_, kvm_bindings::kvm_cpuid_entry2, 256>(- &mut seq,- )+ KVM_MAX_CPUID_ENTRIES => super::vcpu_state_serde::entries::<+ _,+ kvm_bindings::kvm_cpuid_entry2,+ KVM_MAX_CPUID_ENTRIES,+ >(&mut seq).unwrap_err(),- _ => super::vcpu_state_serde::entries::<_, kvm_bindings::kvm_msr_entry, 4096>(- &mut seq,- )+ _ => super::vcpu_state_serde::entries::<+ _,+ kvm_bindings::kvm_msr_entry,+ MAX_SNAPSHOT_MSR_ENTRIES,+ >(&mut seq).unwrap_err(),};assert!(error.to_string().contains("too long"));@@ -398,7 +628,7 @@ mod tests {}for (declared, actual) in [(0, 1), (1, 0), (1, 2), (1, 1)] {let mut seq = Sequence {- declared,+ declared: Some(declared),actual,reads: 0,};diff --git a/src/hypervisor/tests/snapshot/mod.rs b/src/hypervisor/tests/snapshot/mod.rsindex b8d09dc54..3f0f5197c 100644--- a/src/hypervisor/tests/snapshot/mod.rs+++ b/src/hypervisor/tests/snapshot/mod.rs@@ -3,7 +3,18 @@//! Postcard coverage for the host-specific state images, without a VMM envelope.-use super::{X86IrqchipState, X86VcpuState, X86VmState};+use kvm_bindings::KVM_MAX_CPUID_ENTRIES;+use serde::{Serialize, de::DeserializeOwned};++use super::{MAX_SNAPSHOT_MSR_ENTRIES, X86IrqchipState, X86VcpuState, X86VmState};++struct Blob<'a>(&'a [u8]);++impl Serialize for Blob<'_> {+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serializer.serialize_bytes(self.0)+ }+}fn cpu() -> X86VcpuState {let mut state = X86VcpuState {@@ -86,6 +97,13 @@ fn cpu_postcard_round_trips_every_state_field_and_rejects_truncation() {#[test]fn platform_postcard_round_trips_created_and_absent_pit() {+ let mut state = platform();+ round_trip(&state);+ state.pit = None;+ round_trip(&state);+}++fn platform() -> X86VmState {let mut state = X86VmState {irqchips: [X86IrqchipState::pic(@@ -114,9 +132,7 @@ fn platform_postcard_round_trips_created_and_absent_pit() {state.clock.clock = 0x23456789;state.clock.realtime = 0x3456789;state.clock.host_tsc = 0x456789;- round_trip(&state);- state.pit = None;- round_trip(&state);+ state}#[test]@@ -131,45 +147,229 @@ fn cpu_postcard_enforces_flexible_array_bounds() {);}state.xsave.clear();- for count in [0, 255, 256, 257] {+ for count in [+ 0,+ KVM_MAX_CPUID_ENTRIES - 1,+ KVM_MAX_CPUID_ENTRIES,+ KVM_MAX_CPUID_ENTRIES + 1,+ ] {state.cpuid.resize(count, Default::default());let bytes = postcard::to_allocvec(&state).unwrap();assert_eq!(postcard::from_bytes::<X86VcpuState>(&bytes).is_ok(),- count <= 256+ count <= KVM_MAX_CPUID_ENTRIES);}state.cpuid.clear();- for count in [0, 4095, 4096, 4097] {+ for count in [+ 0,+ MAX_SNAPSHOT_MSR_ENTRIES - 1,+ MAX_SNAPSHOT_MSR_ENTRIES,+ MAX_SNAPSHOT_MSR_ENTRIES + 1,+ ] {state.msrs.resize(count, Default::default());let bytes = postcard::to_allocvec(&state).unwrap();assert_eq!(postcard::from_bytes::<X86VcpuState>(&bytes).is_ok(),- count <= 4096+ count <= MAX_SNAPSHOT_MSR_ENTRIES);}}+fn wrong_abi_lengths(encoded: &[u8]) -> impl Iterator<Item = Vec<u8>> + '_ {+ let payload: &[u8] = postcard::from_bytes(encoded).unwrap();+ [0, payload.len() - 1, payload.len() + 1]+ .into_iter()+ .map(move |len| {+ let mut wrong = payload.to_vec();+ wrong.resize(len, 0);+ postcard::to_allocvec(&Blob(&wrong)).unwrap()+ })+}++#[test]+fn fixed_abi_fields_reject_malformed_postcard_lengths() {+ fn check<T: Serialize + DeserializeOwned>(value: &T) {+ let encoded = postcard::to_allocvec(value).unwrap();+ assert!(postcard::from_bytes::<T>(&encoded).is_ok());+ for malformed in wrong_abi_lengths(&encoded) {+ assert!(postcard::from_bytes::<T>(&malformed).is_err());+ }+ }+ check(&platform().irqchips[0]);++ #[derive(Serialize, serde::Deserialize)]+ struct Abi<T>(+ #[serde(+ with = "super::exact_abi_serde",+ bound = "T: Serialize + DeserializeOwned"+ )]+ T,+ );+ let state = cpu();+ check(&Abi(state.regs));+ check(&Abi(state.sregs));+ check(&Abi(state.xcrs));+ check(&Abi(state.debug_regs));+ check(&Abi(state.events));+ check(&Abi(state.mp_state));+ check(&Abi(state.lapic));+ check(&Abi(state.cpuid[0]));+ check(&Abi(state.msrs[0]));+ let vm = platform();+ check(&Abi(vm.clock));+ check(&Abi(vm.pit.unwrap()));+}++#[test]+fn full_snapshots_reject_malformed_abi_field_lengths() {+ fn check<T: Serialize + DeserializeOwned, F: Serialize>(state: &T, field: &F) {+ let field_type = std::any::type_name::<F>();+ let encoded = postcard::to_allocvec(state).unwrap();+ let field = postcard::to_allocvec(field).unwrap();+ let offsets: Vec<_> = encoded+ .windows(field.len())+ .enumerate()+ .filter_map(|(offset, bytes)| (bytes == field).then_some(offset))+ .collect();+ assert_eq!(offsets.len(), 1, "locating {field_type}");+ let offset = offsets[0];+ for malformed in wrong_abi_lengths(&field) {+ let mut bytes = encoded.clone();+ bytes.splice(offset..offset + field.len(), malformed);+ assert!(postcard::from_bytes::<T>(&bytes).is_err(), "{field_type}");+ }+ }+ let vm = platform();+ check(&vm, &vm.irqchips[1]);+ check(&vm, vm.pit.as_ref().unwrap());+ check(&vm, &vm.clock);+ let state = cpu();+ check(&state, &state.regs);+ check(&state, &state.sregs);+ check(&state, &state.cpuid[0]);+ check(&state, &state.msrs[0]);+ check(&state, &state.xcrs);+ check(&state, &state.debug_regs);+ check(&state, &state.events);+ check(&state, &state.mp_state);+ check(&state, &state.lapic);+}+#[test]fn fpu_postcard_rejects_non_abi_lengths() {#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]struct Fpu(#[serde(with = "super::fpu_serde")] kvm_bindings::kvm_fpu);- struct Blob<'a>(&'a [u8]);- impl serde::Serialize for Blob<'_> {- fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {- serializer.serialize_bytes(self.0)- }- }let state = Fpu(cpu().fpu);let encoded = postcard::to_allocvec(&state).unwrap();assert_eq!(postcard::from_bytes::<Fpu>(&encoded).unwrap(), state);// Obtain the ABI payload from the production serializer, not a second// implementation of the FPU layout or its postcard length prefix.- let payload: &[u8] = postcard::from_bytes(&encoded).unwrap();- for len in [0, payload.len() - 1, payload.len() + 1] {- let mut wrong = payload.to_vec();- wrong.resize(len, 0);- let bytes = postcard::to_allocvec(&Blob(&wrong)).unwrap();- assert!(postcard::from_bytes::<Fpu>(&bytes).is_err(), "length {len}");+ for malformed in wrong_abi_lengths(&encoded) {+ assert!(postcard::from_bytes::<Fpu>(&malformed).is_err());+ }+}++#[test]+fn snapshot_defaults_fail_closed_for_an_unsnapshotable_backend() {+ use crate::{MemoryRegion, Vcpu, VcpuExit, VcpuHandle, Vm, X86Vcpu, X86Vm};+ struct Backend;+ struct Cpu;+ #[derive(Clone)]+ struct Handle;+ impl VcpuHandle for Handle {+ fn kick(&self) -> crate::Result<()> {+ panic!("unexpected kick")+ }+ }+ impl Vcpu for Cpu {+ type Handle = Handle;+ fn run(&mut self) -> crate::Result<VcpuExit<'_>> {+ panic!("unexpected guest entry")+ }+ fn complete_pending_io(&mut self) -> crate::Result<()> {+ panic!("unexpected I/O completion")+ }+ fn handle(&self) -> Handle {+ Handle+ }+ }+ impl X86Vcpu for Cpu {+ fn set_cpu_features(+ &mut self,+ _: &[crate::X86CpuidEntry],+ _: &[crate::X86Msr],+ ) -> crate::Result<()> {+ panic!("unexpected boot features")+ }+ fn set_boot_registers(&mut self, _: &crate::X86BootRegisters) -> crate::Result<()> {+ panic!("unexpected boot registers")+ }+ }+ impl Vm for Backend {+ type Vcpu = Cpu;+ unsafe fn map_memory(&self, _: &MemoryRegion) -> crate::Result<()> {+ panic!("unexpected map")+ }+ fn unmap_memory(&self, _: &MemoryRegion) -> crate::Result<()> {+ panic!("unexpected unmap")+ }+ fn set_irq_line(&self, _: u32, _: bool) -> crate::Result<()> {+ panic!("unexpected IRQ")+ }+ fn create_vcpu(&self, _: u32) -> crate::Result<Cpu> {+ panic!("unexpected vCPU creation")+ }+ }+ impl X86Vm for Backend {+ fn supported_cpuid(&self) -> &[crate::X86CpuidEntry] {+ panic!("unexpected boot CPUID")+ }+ }+ let platform = X86VmState {+ irqchips: [+ X86IrqchipState::pic(0, Default::default()),+ X86IrqchipState::pic(1, Default::default()),+ X86IrqchipState::ioapic(Default::default()),+ ],+ pit: None,+ clock: Default::default(),+ };+ for (operation, error) in [+ ("save", Backend.save_state().unwrap_err()),+ (+ "restore",+ Backend.restore_before_vcpus(&platform).unwrap_err(),+ ),+ (+ "restore",+ Backend.restore_after_vcpus(&platform).unwrap_err(),+ ),+ ] {+ assert!(+ matches!(error, crate::Error::VmState { operation: actual, ref source }+ if actual == operation && source.kind() == std::io::ErrorKind::Unsupported+ && source.raw_os_error().is_none())+ );+ }+ for (operation, error) in [+ (+ "save CPU state (unsupported backend)",+ Cpu.save_state().unwrap_err(),+ ),+ (+ "restore CPU state (unsupported backend)",+ Cpu.restore_state(&cpu()).unwrap_err(),+ ),+ (+ "notify guest stopped (unsupported backend)",+ Cpu.notify_guest_stopped().unwrap_err(),+ ),+ ] {+ assert!(+ matches!(error, crate::Error::ConfigureVcpu { id: 0, operation: actual, ref source }+ if actual == operation && source.kind() == std::io::ErrorKind::Unsupported+ && source.raw_os_error().is_none())+ );}}diff --git a/src/vmm/README.md b/src/vmm/README.mdindex 2bd0f15fd..172c69720 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -693,6 +693,9 @@ no topology, so it sets:- leaf 1: APIC ID `index`, `count` rounded up to a power of two, a 64-byteCLFLUSH line whatever the host reports, HTT when `count > 1`, and thehypervisor and TSC-deadline bits;+- leaf 7 subleaf 0: SHSTK is masked because KVM snapshots do not capture the+ shadow stack pointer (SSP) via `KVM_GET_ONE_REG`. `boxlite-hypervisor` rejects+ CPUID that advertises SHSTK with `Unsupported` during capture and restore;- leaf 0xB, and 0x1F when KVM lists it: an SMT level of one thread and acore level of `count` cores whose shift of 6 covers every APIC ID up to 64;- on AMD and Hygon, 0x8000_001E (APIC and core ID `index`, node 0) anddiff --git a/src/vmm/src/cpu_features.rs b/src/vmm/src/cpu_features.rsindex 796b22e76..334008dad 100644--- a/src/vmm/src/cpu_features.rs+++ b/src/vmm/src/cpu_features.rs@@ -21,6 +21,7 @@ use crate::{const LEAF_VENDOR: u32 = 0;const LEAF_FEATURES: u32 = 1;+const LEAF_STRUCTURED_FEATURES: u32 = 7;const LEAF_TOPOLOGY: u32 = 0xb;const LEAF_TOPOLOGY_V2: u32 = 0x1f;const LEAF_AMD_ADDRESS_SIZES: u32 = 0x8000_0008;@@ -32,6 +33,8 @@ const HYPERVISOR: u32 = 1 << 31;/// Leaf 1 ECX: the TSC-deadline timer, which the in-kernel local APIC/// emulates and which spares Linux its APIC timer calibration.const TSC_DEADLINE: u32 = 1 << 24;+/// Leaf 7 subleaf 0 ECX: CET shadow stack (CET_SS or SHSTK).+const SHSTK: u32 = 1 << 7;/// Leaf 1 EDX: more than one logical processor per package.const HTT: u32 = 1 << 28;/// Leaf 1 EBX[15:8]: the CLFLUSH line in 8-byte units, 64 bytes, the same on@@ -137,8 +140,11 @@ pub(crate) fn preflight_x86(/// The CPUID of vCPU `index` of `count`: `supported` with APIC ID `index`, one/// package of `count` single-thread cores, a 64-byte CLFLUSH line, and the-/// hypervisor and TSC-deadline bits. Every other entry is kept, so all vCPUs-/// differ only in the APIC ID.+/// hypervisor and TSC-deadline bits.+///+/// The VMM masks SHSTK because KVM snapshots do not capture the shadow stack+/// pointer (SSP) via `KVM_GET_ONE_REG`. `boxlite-hypervisor` rejects CPUID that+/// advertises SHSTK with `Unsupported` during capture and restore.pub(crate) fn vcpu_cpuid(supported: &[X86CpuidEntry], index: u8, count: u8) -> Vec<X86CpuidEntry> {debug_assert!(index < count && count <= MAX_VCPUS);let apic_id = u32::from(index);@@ -163,6 +169,9 @@ pub(crate) fn vcpu_cpuid(supported: &[X86CpuidEntry], index: u8, count: u8) -> Ventry.edx & !HTT};}+ LEAF_STRUCTURED_FEATURES if !entry.subleaf_required || entry.subleaf == 0 => {+ entry.ecx &= !SHSTK;+ }// ApicIdSize in ECX[15:12] and the core count minus one in ECX[7:0].LEAF_AMD_ADDRESS_SIZES if amd => {entry.ecx = (entry.ecx & !0xf0ff) | (CORE_SHIFT << 12) | (u32::from(count) - 1);diff --git a/src/vmm/tests/cpu_features/mod.rs b/src/vmm/tests/cpu_features/mod.rsindex 5131e62df..167e2b28f 100644--- a/src/vmm/tests/cpu_features/mod.rs+++ b/src/vmm/tests/cpu_features/mod.rs@@ -109,6 +109,33 @@ fn places_each_vcpu_by_apic_id_in_one_package_of_cores() {assert_eq!(others(&cpuid), others(&supported));}+#[test]+fn masks_shadow_stack_only_on_leaf_7_subleaf_0() {+ let indexed_subleaf_1 = X86CpuidEntry {+ subleaf: 1,+ subleaf_required: true,+ ..entry(7, [0x11, 0x22, 0x180, 0x44])+ };+ for (subleaf_required, subleaf) in [(true, 0), (false, 1)] {+ let subleaf_0 = X86CpuidEntry {+ subleaf,+ subleaf_required,+ ..entry(7, [0x11, 0x22, 0x1c0, 0x44])+ };+ let cpuid = vcpu_cpuid(&[subleaf_0, indexed_subleaf_1], 0, 1);+ assert_eq!(+ subleaves(&cpuid, 7),+ [+ X86CpuidEntry {+ ecx: 0x140,+ ..subleaf_0+ },+ indexed_subleaf_1+ ]+ );+ }+}+#[test]fn amd_reports_the_apic_id_in_its_extended_topology_leaves() {let mut supported = amd();