Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6938,6 +6938,7 @@ dependencies = [
"open_enum",
"pal_event",
"parking_lot",
"test_with_tracing",
"thiserror 2.0.16",
"tracelimit",
"tracing",
Expand Down Expand Up @@ -10867,6 +10868,7 @@ dependencies = [
"task_control",
"tempfile",
"test_with_tracing",
"thiserror 2.0.16",
"tracelimit",
"tracing",
"unicycle",
Expand Down
11 changes: 9 additions & 2 deletions Guide/src/reference/openvmm/management/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,14 @@ describes the source definitions.
unless the option is supplied. For example, use
`--virtio-rtc bus=pcie:rp0` to attach it to the named PCIe port `rp0`.
* `--virtio-vsock-path <PATH>`: Add a virtio-vsock device using the OpenVMM
hybrid Unix socket relay.
hybrid Unix socket relay. This backend supports save/restore through the
PCI and MMIO transports on Windows and Linux hosts. Restore resets old
guest connections; applications must reconnect. Live host sockets and
device-side buffered data are not restored. Ordinary pause/resume preserves
connection state, although external peers may time out during a pause.
A fresh VM restore needs a usable relay endpoint and the same guest CID;
release the source endpoint before reusing its path. This does not change
the file-backed snapshot workflow's requirement to leave the source paused.
* `--virtio-vsock-bus <mmio|pci|pcie[:PORT]>`: Select the bus for a
virtio-vsock device created by `--virtio-vsock-path` or
`--virtio-vsock-vhost-cid`. When omitted, OpenVMM selects the bus
Expand All @@ -306,7 +313,7 @@ describes the source definitions.
`/dev/vhost-vsock`, the `vhost_vsock` kernel module, and shared file-backed
guest RAM (the default memory backing). It uses identity-mapped DMA and
does not support a non-identity virtual IOMMU. It conflicts with
`--virtio-vsock-path`.
`--virtio-vsock-path`. This kernel backend does not support save/restore.
* `--vhost-user <SOCKET_PATH>,type=<TYPE>[,tag=<NAME>][,num_queues=<N>][,queue_size=<N>][,pcie_port=<PORT>]`: Attach a
vhost-user device backed by an external process over a Unix socket (Linux
only). The backend process must already be listening on `SOCKET_PATH`.
Expand Down
5 changes: 5 additions & 0 deletions Guide/src/reference/openvmm/management/grpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ as not provided, so the ID isn't checked. The restored snapshot's
ID is returned in `RestoreVMResponse.snapshot_id`. Set `resume` to start the
restored VM immediately; otherwise it is created paused.

PCIe userspace virtio-vsock supports these operations, but restoration resets
existing streams; applications must reconnect. Supply the same guest CID and
make the Unix relay endpoint available before restoring. Live host streams and
device-side buffered data are not restored.

## Virtio-console file output

`VmService` can write a virtio-console stream directly to a host file. Set the
Expand Down
8 changes: 8 additions & 0 deletions Guide/src/user_guide/openvmm/snapshots.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ OpenVMM snapshots:
| virtio-pmem | Virtio (PCI/MMIO) | Yes |
| virtio-rng | Virtio (PCI/MMIO) | Yes |
| virtio-rtc | Virtio (PCI/MMIO) | Yes |
| virtio-vsock (userspace relay) | Virtio (PCI/MMIO) | Yes; applications reconnect after restore |
| virtio-vsock (kernel vhost) | Virtio (PCI/MMIO) | **No** |
| NVMe | PCI | **No** |
| VGA | PCI | **No** (`todo!()`) |
| GDMA (MANA network) | PCI | **No** (`todo!()`) |
Expand All @@ -189,6 +191,12 @@ OpenVMM snapshots:
| VMBus serial (host) | VMBus | **No** |
| Vmbfs | VMBus | **No** |

```admonish warning title="Virtio queue progress"
When a snapshot includes progress for an active virtio queue, its cursors must
be valid for the negotiated ring layout and queue size. Invalid progress is
rejected during restore rather than being discovered when queues restart.
```

```admonish tip
If you are unsure whether your VM configuration supports snapshots, try
issuing `save-snapshot` to a scratch directory. The save will fail
Expand Down
15 changes: 15 additions & 0 deletions petri/src/vm/openvmm/modify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use openvmm_defs::config::PcieMmioRangeConfig;
use openvmm_defs::config::PciePortConfig;
use openvmm_defs::config::PcieRootComplexConfig;
use openvmm_defs::config::PcieSwitchConfig;
use openvmm_defs::config::VirtioBus;
use openvmm_defs::config::VpciDeviceConfig;
use openvmm_defs::config::Vtl2BaseAddressType;
use vm_resource::IntoResource;
Expand All @@ -42,6 +43,20 @@ impl PetriVmConfigOpenVmm {
self
}

/// Attach the userspace virtio-vsock device via MMIO instead of PCIe.
///
/// Requires [`crate::PetriVmBuilder::with_virtio_vsock`] to be enabled.
pub fn with_virtio_vsock_mmio(mut self) -> Self {
let index = self
.private_virtio_devices
.iter()
.position(|(_, resource)| resource.id() == "virtio-vsock")
.expect("enable userspace virtio-vsock before selecting MMIO");
let (_, device) = self.private_virtio_devices.remove(index);
self.config.virtio_devices.push((VirtioBus::Mmio, device));
self
}

/// Enable the VTL0 alias map.
// TODO: Remove once #912 is fixed.
pub fn with_vtl0_alias_map(mut self) -> Self {
Expand Down
11 changes: 11 additions & 0 deletions petri/src/vm/openvmm/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,10 @@ impl PetriVmOpenVmm {
/// survives a save/restore round-trip.
pub async fn verify_save_restore(&mut self) -> anyhow::Result<()>
);
petri_vm_fn!(
/// Perform one save/reset/restore pulse, failing if reset is unsupported.
pub async fn pulse_save_restore(&mut self) -> anyhow::Result<()>
);
petri_vm_fn!(pub(crate) async fn launch_linux_direct_pipette(&mut self) -> anyhow::Result<()>);

/// Wrap the provided future in a race with the worker process's halt
Expand Down Expand Up @@ -838,6 +842,13 @@ impl PetriVmInner {
Ok(())
}

async fn pulse_save_restore(&self) -> anyhow::Result<()> {
self.worker
.pulse_save_restore()
.await
.context("save/restore pulse failed")
}

async fn verify_save_restore(&self) -> anyhow::Result<()> {
for i in 0..2 {
let result = self.worker.pulse_save_restore().await;
Expand Down
8 changes: 6 additions & 2 deletions petri/src/vm/openvmm/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,21 +104,25 @@ impl PetriVmConfigOpenVmm {
// TODO: PCAT needs vga device support
// TODO: arm64 is broken?
// TODO: VPCI and some PCIe endpoints (NVMe/GDMA) don't support
// TODO: virtio vsock and console don't support save/restore yet
// TODO: kernel vhost-vsock and virtio console don't support save/restore yet
// TODO: 9p shares don't support save/restore yet
// TODO: nested virt doesn't support save/restore yet
let has_unsupported_pcie_save_restore_device = config
.pcie_devices
.iter()
.any(|device| matches!(device.resource.id(), "nvme" | "gdma"));
#[cfg(target_os = "linux")]
let has_kernel_vsock = resources.properties.vhost_vsock_guest_cid.is_some();
#[cfg(not(target_os = "linux"))]
let has_kernel_vsock = false;
let supports_save_restore = !skip_save_restore
&& !resources.properties.is_openhcl
&& !resources.properties.is_isolated
&& !resources.properties.is_pcat
&& !matches!(arch, MachineArch::Aarch64)
&& !resources.properties.using_vpci
&& !has_unsupported_pcie_save_restore_device
&& !resources.properties.use_virtio_vsock
&& !has_kernel_vsock
&& !resources.properties.use_virtio_console
&& !has_guest_shares
&& !config.hypervisor.nested_virt;
Expand Down
4 changes: 4 additions & 0 deletions vm/devices/pci/pci_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,9 @@ thiserror.workspace = true
tracelimit.workspace = true
tracing.workspace = true
zerocopy.workspace = true

[dev-dependencies]
test_with_tracing.workspace = true

[lints]
workspace = true
105 changes: 101 additions & 4 deletions vm/devices/pci/pci_core/src/capabilities/msix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,14 +559,16 @@ mod save_restore {
type SavedState = state::SavedState;

fn save(&mut self) -> Result<Self::SavedState, SaveError> {
let state = self.state.lock();
let mut state = self.state.lock();
let enabled = state.enabled;
let saved_state = state::SavedState {
enabled: state.enabled,
enabled,
vectors: {
state
.vectors
.iter()
.iter_mut()
.map(|vec| {
vec.check_is_pending(enabled);
let EntryState {
address,
data,
Expand All @@ -591,7 +593,6 @@ mod save_restore {
let state::SavedState { enabled, vectors } = state;

let mut state = self.state.lock();
state.enabled = enabled;

if vectors.len() != state.vectors.len() {
return Err(RestoreError::InvalidSavedState(
Expand All @@ -600,12 +601,22 @@ mod save_restore {
));
}

state.enabled = enabled;
for (new_vec, vec) in vectors.into_iter().zip(state.vectors.iter_mut()) {
// Replace delivery state as well as register state, including
// pending interrupts from execution after the snapshot.
vec.msi.disable();
vec.msi.drain_pending();
vec.state = EntryState {
address: new_vec.address,
data: new_vec.data,
control: new_vec.control,
is_pending: new_vec.is_pending,
};
if vec.is_enabled(enabled) {
vec.msi
.enable(vec.state.address, vec.state.data, vec.state.is_pending);
vec.state.is_pending = false;
}
}

Expand All @@ -621,6 +632,92 @@ mod tests {
use crate::test_helpers::TestPciInterruptController;
use crate::test_helpers::read_cap_u32;
use crate::test_helpers::write_cap_u32;
use test_with_tracing::test;
use vmcore::save_restore::ProtobufSaveRestore;

#[test]
fn restore_rearms_enabled_interrupts() {
for fresh in [false, true] {
let connection = MsiConnection::new();
let controller = TestPciInterruptController::new();
connection.connect(controller.signal_msi());
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
write_cap_u32(&mut cap, 0, 0x80000000);
msix.write_u32(0, 0xfee00000);
msix.write_u32(8, 0x42);
msix.write_u32(12, 0);
let saved = cap.save().unwrap();
cap.reset();
if fresh {
(msix, cap) = MsixEmulator::new(2, 1, &connection.target());
}
cap.restore(saved).unwrap();
msix.interrupt(0).unwrap().deliver();
assert_eq!(controller.get_next_interrupt(), Some((0xfee00000, 0x42)));
}
}

#[test]
fn restore_preserves_masked_pending_interrupts() {
let connection = MsiConnection::new();
let controller = TestPciInterruptController::new();
connection.connect(controller.signal_msi());
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
write_cap_u32(&mut cap, 0, 0x80000000);
msix.write_u32(0, 0xfee00000);
msix.write_u32(8, 0x42);
msix.interrupt(0).unwrap().deliver();
let saved = cap.save().unwrap();

let (mut restored, mut cap) = MsixEmulator::new(2, 1, &connection.target());
cap.restore(saved).unwrap();
assert_eq!(controller.get_next_interrupt(), None);
assert_eq!(restored.read_u32(16), 1);
restored.write_u32(12, 0);
assert_eq!(controller.get_next_interrupt(), Some((0xfee00000, 0x42)));
assert_eq!(controller.get_next_interrupt(), None);
assert_eq!(restored.read_u32(16), 0);
}

#[test]
fn restore_discards_newer_pending_interrupts() {
let connection = MsiConnection::new();
let controller = TestPciInterruptController::new();
connection.connect(controller.signal_msi());
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
write_cap_u32(&mut cap, 0, 0x80000000);
msix.write_u32(0, 0xfee00000);
msix.write_u32(8, 0x42);
msix.write_u32(12, 0);
let saved = cap.save().unwrap();
cap.reset();
msix.interrupt(0).unwrap().deliver();
cap.restore(saved).unwrap();
assert_eq!(controller.get_next_interrupt(), None);
msix.interrupt(0).unwrap().deliver();
assert_eq!(controller.get_next_interrupt(), Some((0xfee00000, 0x42)));
}

#[test]
fn restore_rearms_kernel_route() {
let (irqfd, calls) = mock_irqfd(1);
let connection = MsiConnection::new();
connection.connect_irqfd(irqfd);
let (mut msix, mut cap) = MsixEmulator::new(2, 1, &connection.target());
msix.interrupt(0).unwrap().event();
write_cap_u32(&mut cap, 0, 0x80000000);
msix.write_u32(0, 0xfee00000);
msix.write_u32(8, 0x42);
msix.write_u32(12, 0);
let saved = cap.save().unwrap();
cap.reset();
calls[0].lock().clear();
cap.restore(saved).unwrap();
assert!(calls[0].lock().contains(&RouteCall::SetMsi {
address: 0xfee00000,
data: 0x42,
}));
}

#[test]
fn msix_check() {
Expand Down
39 changes: 27 additions & 12 deletions vm/devices/virtio/virtio/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,31 +396,46 @@ impl VirtioQueue {
self.complete_prepared(work.into_completion(), bytes_written);
}

/// Complete a descriptor, returning an error if publication to the used
/// ring fails. The completion token is consumed even on failure.
pub fn try_complete(
&mut self,
work: VirtioQueueCallbackWork,
bytes_written: u32,
) -> Result<(), QueueError> {
self.try_complete_prepared(work.into_completion(), bytes_written)
}

/// Completes a descriptor from a lightweight [`QueueCompletion`] token
/// previously obtained via [`VirtioQueueCallbackWork::into_completion`].
///
/// Equivalent to [`complete`](Self::complete) but does not require holding
/// the payload, so callers that buffer completions can store only the
/// token.
pub fn complete_prepared(&mut self, completion: QueueCompletion, bytes_written: u32) {
if let Err(err) = self.try_complete_prepared(completion, bytes_written) {
tracelimit::error_ratelimited!(
error = &err as &dyn std::error::Error,
"failed to complete descriptor"
);
}
}

fn try_complete_prepared(
&mut self,
completion: QueueCompletion,
bytes_written: u32,
) -> Result<(), QueueError> {
// The completion token is consumed even if publishing it to the used ring
// fails, so release its in-flight capacity before attempting the write.
self.core.work_completed(&completion);
match self
if self
.complete
.complete_descriptor(&completion, bytes_written)
.complete_descriptor(&completion, bytes_written)?
{
Ok(true) => {
self.notify_guest.deliver();
}
Ok(false) => {}
Err(err) => {
tracelimit::error_ratelimited!(
error = &err as &dyn std::error::Error,
"failed to complete descriptor"
);
}
self.notify_guest.deliver();
}
Ok(())
}

fn poll_next_buffer(
Expand Down
Loading
Loading