Skip to content

Commit e07981d

Browse files
virtio: add userspace vsock save/restore
Add async device-specific saved state to the PCI and MMIO transports. Preserve vsock runtime across pause/resume and restore old guest connections as pending resets, retaining invalidations under RX backpressure. Rearm MSI-X delivery and pending state on restore, and use a writable RAM-file handle when flushing Windows snapshots. Add device, transport, and Petri regressions plus reconnect documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 0405d3a commit e07981d

22 files changed

Lines changed: 1636 additions & 124 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6748,6 +6748,7 @@ dependencies = [
67486748
"open_enum",
67496749
"pal_event",
67506750
"parking_lot",
6751+
"test_with_tracing",
67516752
"thiserror 2.0.16",
67526753
"tracelimit",
67536754
"tracing",
@@ -10600,6 +10601,7 @@ dependencies = [
1060010601
"task_control",
1060110602
"tempfile",
1060210603
"test_with_tracing",
10604+
"thiserror 2.0.16",
1060310605
"tracelimit",
1060410606
"tracing",
1060510607
"unicycle",

‎Guide/src/reference/openvmm/management/cli.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,14 @@ describes the source definitions.
289289
unless the option is supplied. For example, use
290290
`--virtio-rtc bus=pcie:rp0` to attach it to the named PCIe port `rp0`.
291291
* `--virtio-vsock-path <PATH>`: Add a virtio-vsock device using the OpenVMM
292-
hybrid Unix socket relay.
292+
hybrid Unix socket relay. This backend supports save/restore through the
293+
PCI and MMIO transports on Windows and Linux hosts. Restore resets old
294+
guest connections; applications must reconnect. Live host sockets and
295+
device-side buffered data are not restored. Ordinary pause/resume preserves
296+
connection state, although external peers may time out during a pause.
297+
A fresh VM restore needs a usable relay endpoint and the same guest CID;
298+
release the source endpoint before reusing its path. This does not change
299+
the file-backed snapshot workflow's requirement to leave the source paused.
293300
* `--virtio-vsock-bus <mmio|pci|pcie[:PORT]>`: Select the bus for a
294301
virtio-vsock device created by `--virtio-vsock-path` or
295302
`--virtio-vsock-vhost-cid`. When omitted, OpenVMM selects the bus
@@ -303,7 +310,7 @@ describes the source definitions.
303310
`/dev/vhost-vsock`, the `vhost_vsock` kernel module, and shared file-backed
304311
guest RAM (the default memory backing). It uses identity-mapped DMA and
305312
does not support a non-identity virtual IOMMU. It conflicts with
306-
`--virtio-vsock-path`.
313+
`--virtio-vsock-path`. This kernel backend does not support save/restore.
307314
* `--vhost-user <SOCKET_PATH>,type=<TYPE>[,tag=<NAME>][,num_queues=<N>][,queue_size=<N>][,pcie_port=<PORT>]`: Attach a
308315
vhost-user device backed by an external process over a Unix socket (Linux
309316
only). The backend process must already be listening on `SOCKET_PATH`.

‎openvmm/openvmm_entry/src/vm_controller.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,11 @@ impl VmController {
482482
let saved_state_bytes = mesh::payload::encode(saved_state_msg);
483483

484484
// Fsync the memory backing file.
485-
let memory_file = fs_err::File::open(memory_file_path)?;
485+
// FlushFileBuffers requires a writable handle on Windows.
486+
let memory_file = fs_err::OpenOptions::new()
487+
.read(true)
488+
.write(true)
489+
.open(memory_file_path)?;
486490
memory_file
487491
.sync_all()
488492
.context("failed to fsync memory backing file")?;

‎petri/src/vm/openvmm/modify.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ use openvmm_defs::config::PcieMmioRangeConfig;
3030
use openvmm_defs::config::PciePortConfig;
3131
use openvmm_defs::config::PcieRootComplexConfig;
3232
use openvmm_defs::config::PcieSwitchConfig;
33+
use openvmm_defs::config::VirtioBus;
3334
use openvmm_defs::config::VpciDeviceConfig;
3435
use openvmm_defs::config::Vtl2BaseAddressType;
3536
use vm_resource::IntoResource;
@@ -42,6 +43,20 @@ impl PetriVmConfigOpenVmm {
4243
self
4344
}
4445

46+
/// Attach the userspace virtio-vsock device via MMIO instead of PCIe.
47+
///
48+
/// Requires [`crate::PetriVmBuilder::with_virtio_vsock`] to be enabled.
49+
pub fn with_virtio_vsock_mmio(mut self) -> Self {
50+
let index = self
51+
.private_virtio_devices
52+
.iter()
53+
.position(|(_, resource)| resource.id() == "virtio-vsock")
54+
.expect("enable userspace virtio-vsock before selecting MMIO");
55+
let (_, device) = self.private_virtio_devices.remove(index);
56+
self.config.virtio_devices.push((VirtioBus::Mmio, device));
57+
self
58+
}
59+
4560
/// Enable the VTL0 alias map.
4661
// TODO: Remove once #912 is fixed.
4762
pub fn with_vtl0_alias_map(mut self) -> Self {

‎petri/src/vm/openvmm/runtime.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,10 @@ impl PetriVmOpenVmm {
367367
/// survives a save/restore round-trip.
368368
pub async fn verify_save_restore(&mut self) -> anyhow::Result<()>
369369
);
370+
petri_vm_fn!(
371+
/// Perform one save/reset/restore pulse, failing if reset is unsupported.
372+
pub async fn pulse_save_restore(&mut self) -> anyhow::Result<()>
373+
);
370374
petri_vm_fn!(pub(crate) async fn launch_linux_direct_pipette(&mut self) -> anyhow::Result<()>);
371375

372376
/// Wrap the provided future in a race with the worker process's halt
@@ -799,6 +803,13 @@ impl PetriVmInner {
799803
Ok(())
800804
}
801805

806+
async fn pulse_save_restore(&self) -> anyhow::Result<()> {
807+
self.worker
808+
.pulse_save_restore()
809+
.await
810+
.context("save/restore pulse failed")
811+
}
812+
802813
async fn verify_save_restore(&self) -> anyhow::Result<()> {
803814
for i in 0..2 {
804815
let result = self.worker.pulse_save_restore().await;

‎petri/src/vm/openvmm/start.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,21 +84,25 @@ impl PetriVmConfigOpenVmm {
8484
// TODO: PCAT needs vga device support
8585
// TODO: arm64 is broken?
8686
// TODO: VPCI and some PCIe endpoints (NVMe/GDMA) don't support
87-
// TODO: virtio vsock and console don't support save/restore yet
87+
// TODO: kernel vhost-vsock and virtio console don't support save/restore yet
8888
// TODO: 9p shares don't support save/restore yet
8989
// TODO: nested virt doesn't support save/restore yet
9090
let has_unsupported_pcie_save_restore_device = config
9191
.pcie_devices
9292
.iter()
9393
.any(|device| matches!(device.resource.id(), "nvme" | "gdma"));
94+
#[cfg(target_os = "linux")]
95+
let has_kernel_vsock = resources.properties.vhost_vsock_guest_cid.is_some();
96+
#[cfg(not(target_os = "linux"))]
97+
let has_kernel_vsock = false;
9498
let supports_save_restore = !skip_save_restore
9599
&& !resources.properties.is_openhcl
96100
&& !resources.properties.is_isolated
97101
&& !resources.properties.is_pcat
98102
&& !matches!(arch, MachineArch::Aarch64)
99103
&& !resources.properties.using_vpci
100104
&& !has_unsupported_pcie_save_restore_device
101-
&& !resources.properties.use_virtio_vsock
105+
&& !has_kernel_vsock
102106
&& !resources.properties.use_virtio_console
103107
&& !has_guest_shares
104108
&& !config.hypervisor.nested_virt;

‎vm/devices/pci/pci_core/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,9 @@ thiserror.workspace = true
2222
tracelimit.workspace = true
2323
tracing.workspace = true
2424
zerocopy.workspace = true
25+
26+
[dev-dependencies]
27+
test_with_tracing.workspace = true
28+
2529
[lints]
2630
workspace = true

‎vm/devices/pci/pci_core/src/capabilities/msix.rs‎

Lines changed: 101 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -559,14 +559,16 @@ mod save_restore {
559559
type SavedState = state::SavedState;
560560

561561
fn save(&mut self) -> Result<Self::SavedState, SaveError> {
562-
let state = self.state.lock();
562+
let mut state = self.state.lock();
563+
let enabled = state.enabled;
563564
let saved_state = state::SavedState {
564-
enabled: state.enabled,
565+
enabled,
565566
vectors: {
566567
state
567568
.vectors
568-
.iter()
569+
.iter_mut()
569570
.map(|vec| {
571+
vec.check_is_pending(enabled);
570572
let EntryState {
571573
address,
572574
data,
@@ -591,7 +593,6 @@ mod save_restore {
591593
let state::SavedState { enabled, vectors } = state;
592594

593595
let mut state = self.state.lock();
594-
state.enabled = enabled;
595596

596597
if vectors.len() != state.vectors.len() {
597598
return Err(RestoreError::InvalidSavedState(
@@ -600,12 +601,22 @@ mod save_restore {
600601
));
601602
}
602603

604+
state.enabled = enabled;
603605
for (new_vec, vec) in vectors.into_iter().zip(state.vectors.iter_mut()) {
606+
// Replace delivery state as well as register state, including
607+
// pending interrupts from execution after the snapshot.
608+
vec.msi.disable();
609+
vec.msi.drain_pending();
604610
vec.state = EntryState {
605611
address: new_vec.address,
606612
data: new_vec.data,
607613
control: new_vec.control,
608614
is_pending: new_vec.is_pending,
615+
};
616+
if vec.is_enabled(enabled) {
617+
vec.msi
618+
.enable(vec.state.address, vec.state.data, vec.state.is_pending);
619+
vec.state.is_pending = false;
609620
}
610621
}
611622

@@ -621,6 +632,92 @@ mod tests {
621632
use crate::test_helpers::TestPciInterruptController;
622633
use crate::test_helpers::read_cap_u32;
623634
use crate::test_helpers::write_cap_u32;
635+
use test_with_tracing::test;
636+
use vmcore::save_restore::ProtobufSaveRestore;
637+
638+
#[test]
639+
fn restore_rearms_enabled_interrupts() {
640+
for fresh in [false, true] {
641+
let connection = MsiConnection::new();
642+
let controller = TestPciInterruptController::new();
643+
connection.connect(controller.signal_msi());
644+
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
645+
write_cap_u32(&mut cap, 0, 0x80000000);
646+
msix.write_u32(0, 0xfee00000);
647+
msix.write_u32(8, 0x42);
648+
msix.write_u32(12, 0);
649+
let saved = cap.save().unwrap();
650+
cap.reset();
651+
if fresh {
652+
(msix, cap) = MsixEmulator::new(2, 1, &connection.target());
653+
}
654+
cap.restore(saved).unwrap();
655+
msix.interrupt(0).unwrap().deliver();
656+
assert_eq!(controller.get_next_interrupt(), Some((0xfee00000, 0x42)));
657+
}
658+
}
659+
660+
#[test]
661+
fn restore_preserves_masked_pending_interrupts() {
662+
let connection = MsiConnection::new();
663+
let controller = TestPciInterruptController::new();
664+
connection.connect(controller.signal_msi());
665+
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
666+
write_cap_u32(&mut cap, 0, 0x80000000);
667+
msix.write_u32(0, 0xfee00000);
668+
msix.write_u32(8, 0x42);
669+
msix.interrupt(0).unwrap().deliver();
670+
let saved = cap.save().unwrap();
671+
672+
let (mut restored, mut cap) = MsixEmulator::new(2, 1, &connection.target());
673+
cap.restore(saved).unwrap();
674+
assert_eq!(controller.get_next_interrupt(), None);
675+
assert_eq!(restored.read_u32(16), 1);
676+
restored.write_u32(12, 0);
677+
assert_eq!(controller.get_next_interrupt(), Some((0xfee00000, 0x42)));
678+
assert_eq!(controller.get_next_interrupt(), None);
679+
assert_eq!(restored.read_u32(16), 0);
680+
}
681+
682+
#[test]
683+
fn restore_discards_newer_pending_interrupts() {
684+
let connection = MsiConnection::new();
685+
let controller = TestPciInterruptController::new();
686+
connection.connect(controller.signal_msi());
687+
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
688+
write_cap_u32(&mut cap, 0, 0x80000000);
689+
msix.write_u32(0, 0xfee00000);
690+
msix.write_u32(8, 0x42);
691+
msix.write_u32(12, 0);
692+
let saved = cap.save().unwrap();
693+
cap.reset();
694+
msix.interrupt(0).unwrap().deliver();
695+
cap.restore(saved).unwrap();
696+
assert_eq!(controller.get_next_interrupt(), None);
697+
msix.interrupt(0).unwrap().deliver();
698+
assert_eq!(controller.get_next_interrupt(), Some((0xfee00000, 0x42)));
699+
}
700+
701+
#[test]
702+
fn restore_rearms_kernel_route() {
703+
let (irqfd, calls) = mock_irqfd(1);
704+
let connection = MsiConnection::new();
705+
connection.connect_irqfd(irqfd);
706+
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
707+
msix.interrupt(0).unwrap().event();
708+
write_cap_u32(&mut cap, 0, 0x80000000);
709+
msix.write_u32(0, 0xfee00000);
710+
msix.write_u32(8, 0x42);
711+
msix.write_u32(12, 0);
712+
let saved = cap.save().unwrap();
713+
cap.reset();
714+
calls[0].lock().clear();
715+
cap.restore(saved).unwrap();
716+
assert!(calls[0].lock().contains(&RouteCall::SetMsi {
717+
address: 0xfee00000,
718+
data: 0x42,
719+
}));
720+
}
624721

625722
#[test]
626723
fn msix_check() {

‎vm/devices/virtio/virtio/src/common.rs‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -396,31 +396,46 @@ impl VirtioQueue {
396396
self.complete_prepared(work.into_completion(), bytes_written);
397397
}
398398

399+
/// Complete a descriptor, returning an error if publication to the used
400+
/// ring fails. The completion token is consumed even on failure.
401+
pub fn try_complete(
402+
&mut self,
403+
work: VirtioQueueCallbackWork,
404+
bytes_written: u32,
405+
) -> Result<(), QueueError> {
406+
self.try_complete_prepared(work.into_completion(), bytes_written)
407+
}
408+
399409
/// Completes a descriptor from a lightweight [`QueueCompletion`] token
400410
/// previously obtained via [`VirtioQueueCallbackWork::into_completion`].
401411
///
402412
/// Equivalent to [`complete`](Self::complete) but does not require holding
403413
/// the payload, so callers that buffer completions can store only the
404414
/// token.
405415
pub fn complete_prepared(&mut self, completion: QueueCompletion, bytes_written: u32) {
416+
if let Err(err) = self.try_complete_prepared(completion, bytes_written) {
417+
tracelimit::error_ratelimited!(
418+
error = &err as &dyn std::error::Error,
419+
"failed to complete descriptor"
420+
);
421+
}
422+
}
423+
424+
fn try_complete_prepared(
425+
&mut self,
426+
completion: QueueCompletion,
427+
bytes_written: u32,
428+
) -> Result<(), QueueError> {
406429
// The completion token is consumed even if publishing it to the used ring
407430
// fails, so release its in-flight capacity before attempting the write.
408431
self.core.work_completed(&completion);
409-
match self
432+
if self
410433
.complete
411-
.complete_descriptor(&completion, bytes_written)
434+
.complete_descriptor(&completion, bytes_written)?
412435
{
413-
Ok(true) => {
414-
self.notify_guest.deliver();
415-
}
416-
Ok(false) => {}
417-
Err(err) => {
418-
tracelimit::error_ratelimited!(
419-
error = &err as &dyn std::error::Error,
420-
"failed to complete descriptor"
421-
);
422-
}
436+
self.notify_guest.deliver();
423437
}
438+
Ok(())
424439
}
425440

426441
fn poll_next_buffer(

0 commit comments

Comments
 (0)