From a838dcce6a838909fee9951404d0cfed11813089 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Wed, 14 Oct 2026 14:32:08 +0530 Subject: [PATCH 01/17] openvmm_entry: add VM-mutation gate to the ttrpc VmService Topology operations (device and resource hot add/remove) share the gate with each other; pause, resume and teardown are exclusive. A conflicting operation is rejected immediately with ABORTED. Topology RPCs are admitted before their request is processed, so a rejected call has no side effects, and the guard is released when the operation completes, fails, or is cancelled. --- openvmm/openvmm_entry/src/ttrpc/mod.rs | 59 +++++- .../openvmm_entry/src/ttrpc/operation_gate.rs | 177 ++++++++++++++++++ 2 files changed, 226 insertions(+), 10 deletions(-) create mode 100644 openvmm/openvmm_entry/src/ttrpc/operation_gate.rs diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 873a1b4fe4d..1f159d24b01 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -8,9 +8,12 @@ // The fd-passing protocol relies on `SCM_RIGHTS` and so exists only on unix. #[cfg(unix)] mod fd_passing; +mod operation_gate; #[cfg(unix)] use fd_passing::FdRegistry; +use operation_gate::VmOperation; +use operation_gate::VmOperationGate; /// On non-unix platforms the fd-passing protocol does not exist. The registry /// is still threaded through the shared NIC configuration code, so provide an @@ -376,6 +379,7 @@ impl Worker for TtrpcWorker { wait_vm_response: None, lifecycle: VmLifecycle::Uninitialized, rpc_tasks: Vec::new(), + operation_gate: VmOperationGate::default(), transport: self.transport, registry: FdRegistry::default(), }; @@ -546,6 +550,31 @@ impl VmService { Err(err) => response.send(Err(grpc_error(err))), } } + + /// Like [`Self::start_rpc`], but admits the operation through the + /// VM-mutation gate first. `build` runs only after admission, so a rejected + /// operation has no side effects, and the gate is held until the operation + /// completes or is cancelled. + fn start_gated_rpc( + &mut self, + operation: VmOperation, + response: mesh::OneshotSender>, + build: impl FnOnce(&Self) -> anyhow::Result, + ) where + F: 'static + Future> + Send, + R: 'static + MeshPayload + Send, + { + let gated = self + .operation_gate + .try_acquire(operation) + .and_then(|guard| { + build(self).map(|fut| async move { + let _guard = guard; + fut.await + }) + }); + self.start_rpc(response, gated); + } } struct Vm { @@ -679,6 +708,8 @@ struct VmService { wait_vm_response: Option<(mesh::CancelContext, mesh::OneshotSender>)>, lifecycle: VmLifecycle, rpc_tasks: Vec>, + /// Rejects an operation that conflicts with one already in flight. + operation_gate: VmOperationGate, transport: ResolvedTransport, /// Registry of file descriptors passed in over the fd-passing protocol, /// resolvable by name (e.g. for tap NIC backends). @@ -764,24 +795,29 @@ impl VmService { } } vmservice::Vm::ModifyResource(request, response) => { - let r = self.modify_resource(request); - self.start_rpc(response, r); + self.start_gated_rpc(VmOperation::Topology, response, |this| { + this.modify_resource(request) + }); } vmservice::Vm::AddPcieDevice(request, response) => { - let r = self.add_pcie_device(request); - self.start_rpc(response, r); + self.start_gated_rpc(VmOperation::Topology, response, |this| { + this.add_pcie_device(request) + }); } vmservice::Vm::RemovePcieDevice(request, response) => { - let r = self.remove_pcie_device(request); - self.start_rpc(response, r); + self.start_gated_rpc(VmOperation::Topology, response, |this| { + this.remove_pcie_device(request) + }); } vmservice::Vm::AddVpciDevice(request, response) => { - let r = self.add_vpci_device(request); - self.start_rpc(response, r); + self.start_gated_rpc(VmOperation::Topology, response, |this| { + this.add_vpci_device(request) + }); } vmservice::Vm::RemoveVpciDevice(request, response) => { - let r = self.remove_vpci_device(request); - self.start_rpc(response, r); + self.start_gated_rpc(VmOperation::Topology, response, |this| { + this.remove_vpci_device(request) + }); } } HandleAction::None @@ -1367,6 +1403,7 @@ impl VmService { } async fn teardown_vm(&mut self) -> anyhow::Result<()> { + let _gate = self.operation_gate.try_acquire(VmOperation::Teardown)?; let controller = self.vm_controller.take().context("vm not created")?; // Drop the VM's device RPC channels before waiting on the controller. // A live `ScsiControllerRequest` sender keeps the detached storvsp task @@ -1431,6 +1468,7 @@ impl VmService { } async fn pause_vm(&mut self) -> anyhow::Result<()> { + let _gate = self.operation_gate.try_acquire(VmOperation::Lifecycle)?; let vm = self.vm.clone().context("VM not created yet")?; vm.worker_rpc .call(VmRpc::Pause, ()) @@ -1444,6 +1482,7 @@ impl VmService { } async fn resume_vm(&mut self) -> anyhow::Result<()> { + let _gate = self.operation_gate.try_acquire(VmOperation::Lifecycle)?; let vm = self.vm.clone().context("VM not created yet")?; vm.worker_rpc .call(VmRpc::Resume, ()) diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs new file mode 100644 index 00000000000..fbc657eb960 --- /dev/null +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! The VM-mutation gate. +//! +//! Operations that mutate the VM are admitted through this gate. Topology +//! operations (hot add/remove of devices and resources) are independent of one +//! another and share the gate; lifecycle and teardown operations are exclusive +//! and exclude everything else. The gate never queues: a conflicting caller is +//! rejected immediately with `ABORTED`. +//! +//! The gate must be acquired before any side effect of the operation, and is +//! released when its guard drops, so completion, error, and cancellation all +//! release it. + +use anyhow::Context; +use mesh_rpc::service::Code; +use parking_lot::Mutex; +use std::sync::Arc; + +/// An operation that mutates the VM and therefore requires the gate. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum VmOperation { + /// Pause or resume. Exclusive. + Lifecycle, + /// Hot add or remove of a device or resource. Shared with other topology + /// operations. + Topology, + /// Teardown of the VM. Exclusive. + Teardown, +} + +impl VmOperation { + fn name(self) -> &'static str { + match self { + VmOperation::Lifecycle => "pause/resume", + VmOperation::Topology => "device or resource modification", + VmOperation::Teardown => "teardown", + } + } + + fn is_shared(self) -> bool { + matches!(self, VmOperation::Topology) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum State { + Idle, + /// `n` topology operations in flight. + Shared(u32), + Exclusive(VmOperation), +} + +#[derive(Clone)] +pub(crate) struct VmOperationGate { + state: Arc>, +} + +impl Default for VmOperationGate { + fn default() -> Self { + Self { + state: Arc::new(Mutex::new(State::Idle)), + } + } +} + +/// Held for the duration of a gated operation; releases the gate on drop. +#[must_use = "the gate is released as soon as the guard is dropped"] +pub(crate) struct VmOperationGuard { + state: Arc>, + operation: VmOperation, +} + +impl VmOperationGate { + /// Acquires the gate for `operation`, or fails with `ABORTED` if a + /// conflicting operation holds it. + pub(crate) fn try_acquire(&self, operation: VmOperation) -> anyhow::Result { + let mut state = self.state.lock(); + let held = match (*state, operation.is_shared()) { + (State::Idle, true) => { + *state = State::Shared(1); + None + } + (State::Idle, false) => { + *state = State::Exclusive(operation); + None + } + (State::Shared(n), true) => { + *state = State::Shared(n + 1); + None + } + (State::Shared(_), false) => Some(VmOperation::Topology), + (State::Exclusive(held), _) => Some(held), + }; + if let Some(held) = held { + return Err(anyhow::Error::new(Code::Aborted)).with_context(|| { + format!( + "VM busy: {} in progress, cannot start {}", + held.name(), + operation.name() + ) + }); + } + Ok(VmOperationGuard { + state: self.state.clone(), + operation, + }) + } +} + +impl Drop for VmOperationGuard { + fn drop(&mut self) { + let mut state = self.state.lock(); + *state = match *state { + State::Shared(n) if self.operation.is_shared() && n > 1 => State::Shared(n - 1), + _ => State::Idle, + }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ttrpc::grpc_error; + use test_with_tracing::test; + + #[test] + fn exclusive_rejects_everything_with_aborted() { + let gate = VmOperationGate::default(); + let _guard = gate.try_acquire(VmOperation::Lifecycle).unwrap(); + for op in [ + VmOperation::Lifecycle, + VmOperation::Topology, + VmOperation::Teardown, + ] { + let status = grpc_error(gate.try_acquire(op).err().unwrap()); + assert_eq!(status.code, i32::from(Code::Aborted)); + assert!(status.message.contains("VM busy"), "{}", status.message); + } + } + + #[test] + fn topology_operations_share_the_gate() { + let gate = VmOperationGate::default(); + let a = gate.try_acquire(VmOperation::Topology).unwrap(); + let b = gate.try_acquire(VmOperation::Topology).unwrap(); + assert!(gate.try_acquire(VmOperation::Lifecycle).is_err()); + assert!(gate.try_acquire(VmOperation::Teardown).is_err()); + drop(a); + assert!(gate.try_acquire(VmOperation::Teardown).is_err()); + drop(b); + assert!(gate.try_acquire(VmOperation::Teardown).is_ok()); + } + + #[test] + fn releases_on_drop() { + let gate = VmOperationGate::default(); + drop(gate.try_acquire(VmOperation::Lifecycle).unwrap()); + drop(gate.try_acquire(VmOperation::Teardown).unwrap()); + } + + #[test] + fn releases_when_holding_future_is_dropped() { + let gate = VmOperationGate::default(); + let guard = gate.try_acquire(VmOperation::Topology).unwrap(); + // A spawned operation moves the guard into its future; dropping the + // unpolled future (cancellation) must release the gate. + let fut = async move { + let _guard = guard; + std::future::pending::<()>().await; + }; + assert!(gate.try_acquire(VmOperation::Teardown).is_err()); + drop(fut); + assert!(gate.try_acquire(VmOperation::Teardown).is_ok()); + } +} From 940b7e8e0e189e452877fb6486057f7e180061ee Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Wed, 14 Oct 2026 14:59:11 +0530 Subject: [PATCH 02/17] Guide: document the VM operation gate in the gRPC reference Describe which ttrpc operations are exclusive or shared, the ABORTED response for a conflicting request, and that a rejected request has no side effects. --- .../src/reference/openvmm/management/grpc.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index 15ddaaf10db..5ebb298ff4d 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -94,6 +94,28 @@ Unlike `AddPcieDevice`, VPCI does not require a root complex or a predeclared hotplug-capable PCIe port. `AddPcieDevice` remains available when standard PCIe hotplug semantics or a non-VPCI host backend is required. +## Concurrent operations + +The server admits one kind of VM-changing operation at a time. A request that +conflicts with an operation already in flight is rejected immediately with +`ABORTED` and a message naming both operations (for example, `VM busy: +pause/resume in progress, cannot start teardown`). Requests are never queued, +so callers decide whether to retry. A rejected request has no side effects. + +| Operation | Class | May run alongside | +|---|---|---| +| `PauseVM`, `ResumeVM` | Exclusive | Nothing | +| `TeardownVM` | Exclusive | Nothing | +| `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Other shared operations | + +Several device additions or removals can therefore be issued concurrently, +but none can overlap a pause, resume, or teardown. `CreateVM`, `Quit`, and the +read-only RPCs (`WaitVM`, `CapabilitiesVM`, `PropertiesVM`) are not gated. + +The gate is held until the operation finishes, whether it succeeds or fails. +A client that cancels or disconnects does not release it early, because the +operation itself keeps running to completion. + ## VFIO and accelerated SMMU On Linux, declare named host iommufd contexts in `VMConfig.iommufds`, then From cf6062f8c55410afc2c276a1f34870185ce85335 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Thu, 15 Oct 2026 22:42:51 +0530 Subject: [PATCH 03/17] openvmm_entry: address gate review feedback Split the pause/resume gate kind into separate Pause and Resume kinds so a conflict names the operation that is actually running. Make Quit wait for in-flight device and resource changes before dropping the VM. Such a change can hold a clone of a device RPC channel, and a live channel keeps the worker from stopping, so Quit could otherwise hang. Correct the Guide: pause, resume, and teardown run to completion before the server reads its next request, so requests arriving meanwhile are processed afterwards rather than rejected; ABORTED applies when one of them arrives while a device or resource change is still in flight. --- .../src/reference/openvmm/management/grpc.md | 25 ++++++++----- openvmm/openvmm_entry/src/ttrpc/mod.rs | 10 ++++-- .../openvmm_entry/src/ttrpc/operation_gate.rs | 36 ++++++++++++++----- 3 files changed, 52 insertions(+), 19 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index 5ebb298ff4d..26654c9ec6b 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -96,11 +96,15 @@ hotplug semantics or a non-VPCI host backend is required. ## Concurrent operations -The server admits one kind of VM-changing operation at a time. A request that -conflicts with an operation already in flight is rejected immediately with -`ABORTED` and a message naming both operations (for example, `VM busy: -pause/resume in progress, cannot start teardown`). Requests are never queued, -so callers decide whether to retry. A rejected request has no side effects. +VM-changing operations never overlap in a conflicting way. Device and resource +changes (`ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, +`AddVpciDevice`, `RemoveVpciDevice`) run in the background and may overlap one +another. `PauseVM`, `ResumeVM`, and `TeardownVM` are exclusive: if a device or +resource change is still in flight, they are rejected immediately with +`ABORTED` and a message naming both operations (for example, `VM busy: device +or resource modification in progress, cannot start pause`). A rejected request +has no side effects, and the server never retries it; the caller decides +whether to retry. | Operation | Class | May run alongside | |---|---|---| @@ -108,9 +112,14 @@ so callers decide whether to retry. A rejected request has no side effects. | `TeardownVM` | Exclusive | Nothing | | `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Other shared operations | -Several device additions or removals can therefore be issued concurrently, -but none can overlap a pause, resume, or teardown. `CreateVM`, `Quit`, and the -read-only RPCs (`WaitVM`, `CapabilitiesVM`, `PropertiesVM`) are not gated. +`PauseVM`, `ResumeVM`, and `TeardownVM` run to completion before the server +reads its next request. Requests that arrive while one of them is running +therefore wait and are processed after it finishes, rather than being +rejected. + +`CreateVM`, `Quit`, and the read-only RPCs (`WaitVM`, `CapabilitiesVM`, +`PropertiesVM`) are not gated. `Quit` first waits for any in-flight device or +resource changes to finish, then stops the VM. The gate is held until the operation finishes, whether it succeeds or fails. A client that cancels or disconnects does not release it early, because the diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 1f159d24b01..ab92f702f0e 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -755,6 +755,12 @@ impl VmService { response.send(map_grpc(self.teardown_vm().await)) } vmservice::Vm::Quit((), response) => { + // Let in-flight device and resource changes finish first. Each + // can hold a clone of a device RPC channel (for example the + // SCSI controller's), and a live channel keeps the worker from + // stopping, so dropping the VM under them could hang below. + // The VM is still running, so they complete normally. + futures::future::join_all(self.rpc_tasks.drain(..)).await; // Shut down the controller (which stops and joins the worker). // Drop the VM's device RPC channels first; see `teardown_vm`. self.vm.take(); @@ -1468,7 +1474,7 @@ impl VmService { } async fn pause_vm(&mut self) -> anyhow::Result<()> { - let _gate = self.operation_gate.try_acquire(VmOperation::Lifecycle)?; + let _gate = self.operation_gate.try_acquire(VmOperation::Pause)?; let vm = self.vm.clone().context("VM not created yet")?; vm.worker_rpc .call(VmRpc::Pause, ()) @@ -1482,7 +1488,7 @@ impl VmService { } async fn resume_vm(&mut self) -> anyhow::Result<()> { - let _gate = self.operation_gate.try_acquire(VmOperation::Lifecycle)?; + let _gate = self.operation_gate.try_acquire(VmOperation::Resume)?; let vm = self.vm.clone().context("VM not created yet")?; vm.worker_rpc .call(VmRpc::Resume, ()) diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index fbc657eb960..fd61bfe6321 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -5,8 +5,8 @@ //! //! Operations that mutate the VM are admitted through this gate. Topology //! operations (hot add/remove of devices and resources) are independent of one -//! another and share the gate; lifecycle and teardown operations are exclusive -//! and exclude everything else. The gate never queues: a conflicting caller is +//! another and share the gate; pause, resume, and teardown are exclusive and +//! exclude everything else. The gate never queues: a conflicting caller is //! rejected immediately with `ABORTED`. //! //! The gate must be acquired before any side effect of the operation, and is @@ -21,8 +21,10 @@ use std::sync::Arc; /// An operation that mutates the VM and therefore requires the gate. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum VmOperation { - /// Pause or resume. Exclusive. - Lifecycle, + /// Pause. Exclusive. + Pause, + /// Resume. Exclusive. + Resume, /// Hot add or remove of a device or resource. Shared with other topology /// operations. Topology, @@ -33,7 +35,8 @@ pub(crate) enum VmOperation { impl VmOperation { fn name(self) -> &'static str { match self { - VmOperation::Lifecycle => "pause/resume", + VmOperation::Pause => "pause", + VmOperation::Resume => "resume", VmOperation::Topology => "device or resource modification", VmOperation::Teardown => "teardown", } @@ -128,9 +131,10 @@ mod tests { #[test] fn exclusive_rejects_everything_with_aborted() { let gate = VmOperationGate::default(); - let _guard = gate.try_acquire(VmOperation::Lifecycle).unwrap(); + let _guard = gate.try_acquire(VmOperation::Pause).unwrap(); for op in [ - VmOperation::Lifecycle, + VmOperation::Pause, + VmOperation::Resume, VmOperation::Topology, VmOperation::Teardown, ] { @@ -140,12 +144,26 @@ mod tests { } } + #[test] + fn rejection_names_both_operations() { + let gate = VmOperationGate::default(); + let _guard = gate.try_acquire(VmOperation::Pause).unwrap(); + let status = grpc_error(gate.try_acquire(VmOperation::Resume).err().unwrap()); + assert!( + status + .message + .contains("pause in progress, cannot start resume"), + "{}", + status.message + ); + } + #[test] fn topology_operations_share_the_gate() { let gate = VmOperationGate::default(); let a = gate.try_acquire(VmOperation::Topology).unwrap(); let b = gate.try_acquire(VmOperation::Topology).unwrap(); - assert!(gate.try_acquire(VmOperation::Lifecycle).is_err()); + assert!(gate.try_acquire(VmOperation::Pause).is_err()); assert!(gate.try_acquire(VmOperation::Teardown).is_err()); drop(a); assert!(gate.try_acquire(VmOperation::Teardown).is_err()); @@ -156,7 +174,7 @@ mod tests { #[test] fn releases_on_drop() { let gate = VmOperationGate::default(); - drop(gate.try_acquire(VmOperation::Lifecycle).unwrap()); + drop(gate.try_acquire(VmOperation::Pause).unwrap()); drop(gate.try_acquire(VmOperation::Teardown).unwrap()); } From 0ced5c40a649028518c7139227e72a231dbf6521 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Fri, 16 Oct 2026 11:25:57 +0530 Subject: [PATCH 04/17] openvmm_entry: make teardown and quit terminal over in-flight changes A device or resource change can stay in flight indefinitely. For example, a Consomme port change waits for the NIC's queue processing, which is stopped while the VM is paused. Such a change held the gate, so resume and teardown were rejected with ABORTED and Quit, which waited for it, hung. Teardown and Quit are now terminal: they cancel in-flight gated changes before proceeding, and the cancelled calls return CANCELLED. Only the service-side wait is cancelled; a request already delivered to the VM is completed or discarded when the worker stops. The server's own shutdown path does the same. Consomme port changes are also rejected with FAILED_PRECONDITION unless the VM is running, since they cannot complete otherwise. --- .../src/reference/openvmm/management/grpc.md | 43 ++++---- openvmm/openvmm_entry/src/ttrpc/mod.rs | 98 ++++++++++++++++--- .../openvmm_entry/src/ttrpc/operation_gate.rs | 4 +- 3 files changed, 112 insertions(+), 33 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index 26654c9ec6b..50b2381e614 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -99,31 +99,40 @@ hotplug semantics or a non-VPCI host backend is required. VM-changing operations never overlap in a conflicting way. Device and resource changes (`ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice`) run in the background and may overlap one -another. `PauseVM`, `ResumeVM`, and `TeardownVM` are exclusive: if a device or -resource change is still in flight, they are rejected immediately with -`ABORTED` and a message naming both operations (for example, `VM busy: device -or resource modification in progress, cannot start pause`). A rejected request -has no side effects, and the server never retries it; the caller decides -whether to retry. - -| Operation | Class | May run alongside | +another. `PauseVM` and `ResumeVM` are exclusive: if a device or resource change +is still in flight, they are rejected immediately with `ABORTED` and a message +naming both operations (for example, `VM busy: device or resource modification +in progress, cannot start pause`). A rejected request has no side effects, and +the server never retries it; the caller decides whether to retry. + +`TeardownVM` and `Quit` are terminal and are never rejected by in-flight +device or resource changes. They cancel those changes first, and the cancelled +calls return `CANCELLED`. Cancellation stops the server waiting for the change; +a change already delivered to the VM is completed or discarded when the VM +stops. + +| Operation | Class | In-flight device or resource changes | |---|---|---| -| `PauseVM`, `ResumeVM` | Exclusive | Nothing | -| `TeardownVM` | Exclusive | Nothing | -| `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Other shared operations | +| `PauseVM`, `ResumeVM` | Exclusive | Rejects the request with `ABORTED` | +| `TeardownVM`, `Quit` | Terminal | Cancelled; they return `CANCELLED` | +| `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Run alongside | `PauseVM`, `ResumeVM`, and `TeardownVM` run to completion before the server reads its next request. Requests that arrive while one of them is running therefore wait and are processed after it finishes, rather than being rejected. -`CreateVM`, `Quit`, and the read-only RPCs (`WaitVM`, `CapabilitiesVM`, -`PropertiesVM`) are not gated. `Quit` first waits for any in-flight device or -resource changes to finish, then stops the VM. +`CreateVM` and the read-only RPCs (`WaitVM`, `CapabilitiesVM`, `PropertiesVM`) +are not gated. -The gate is held until the operation finishes, whether it succeeds or fails. -A client that cancels or disconnects does not release it early, because the -operation itself keeps running to completion. +Otherwise, the gate is held until the operation finishes, whether it succeeds +or fails. A client that cancels or disconnects does not release it early, +because the operation itself keeps running to completion. + +Consomme port changes (`ModifyResource` updating or removing a Consomme NIC's +ports) require a running VM and fail with `FAILED_PRECONDITION` otherwise, +because the ports are serviced by the NIC's queue processing, which is stopped +while the VM is paused. ## VFIO and accelerated SMMU diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index ab92f702f0e..97b8644dea3 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -370,6 +370,7 @@ impl Worker for TtrpcWorker { fn run(self, recv: mesh::Receiver>) -> anyhow::Result<()> { DefaultPool::run_with(async |driver| { + let (topology_cancel_ctx, topology_cancel) = mesh::CancelContext::new().with_cancel(); let mut service = VmService { driver, vm: None, @@ -380,6 +381,9 @@ impl Worker for TtrpcWorker { lifecycle: VmLifecycle::Uninitialized, rpc_tasks: Vec::new(), operation_gate: VmOperationGate::default(), + gated_tasks: Vec::new(), + gated_cancel_ctx: topology_cancel_ctx, + gated_cancel: topology_cancel, transport: self.transport, registry: FdRegistry::default(), }; @@ -508,6 +512,9 @@ impl VmService { } }; + // Cancel in-flight device and resource changes; see `cancel_gated_tasks`. + self.cancel_gated_tasks().await; + // If the controller is still alive (non-Quit exit), shut it down. if !quit { if let Some(controller) = self.vm_controller.take() { @@ -554,7 +561,8 @@ impl VmService { /// Like [`Self::start_rpc`], but admits the operation through the /// VM-mutation gate first. `build` runs only after admission, so a rejected /// operation has no side effects, and the gate is held until the operation - /// completes or is cancelled. + /// completes or is cancelled by a terminal operation (see + /// [`Self::cancel_gated_tasks`]). fn start_gated_rpc( &mut self, operation: VmOperation, @@ -564,16 +572,52 @@ impl VmService { F: 'static + Future> + Send, R: 'static + MeshPayload + Send, { - let gated = self + let fut = match self .operation_gate .try_acquire(operation) - .and_then(|guard| { - build(self).map(|fut| async move { - let _guard = guard; - fut.await - }) - }); - self.start_rpc(response, gated); + .and_then(|guard| build(self).map(|fut| (guard, fut))) + { + Ok(v) => v, + Err(err) => { + response.send(Err(grpc_error(err))); + return; + } + }; + let (guard, fut) = fut; + let mut cancel = self.gated_cancel_ctx.clone(); + let task = self.driver.spawn("ttrpc-gated-rpc", async move { + let r = match cancel.until_cancelled(fut).await { + Ok(r) => r, + Err(_) => Err(anyhow::Error::new(Code::Cancelled)) + .context("cancelled because the VM is being torn down"), + }; + drop(guard); + response.send(map_grpc(r)); + }); + self.gated_tasks.retain(|task| !task.is_finished()); + self.gated_tasks.push(task); + } + + /// Cancels every in-flight gated background operation and waits for it to + /// finish, so it releases the gate and any device RPC channel it holds. + /// + /// Used by the terminal operations (teardown and quit), which must always + /// make progress: an in-flight device or resource change has no meaning + /// once the VM is destroyed, and one can otherwise wait forever (for + /// example, a Consomme port change whose NIC is not processing its queue). + /// The cancelled callers receive `CANCELLED`. Only the service-side wait + /// is cancelled; a request already delivered to the VM is completed or + /// discarded when the VM worker stops. + /// + /// Cancellation drops the operation's future, so gated futures must be + /// safe to drop at any await point. Today they await only RPC replies and + /// blocking file I/O. They must not issue io_uring I/O on the service + /// driver, whose in-flight futures abort the process if dropped. + async fn cancel_gated_tasks(&mut self) { + let (ctx, cancel) = mesh::CancelContext::new().with_cancel(); + self.gated_cancel_ctx = ctx; + std::mem::replace(&mut self.gated_cancel, cancel).cancel(); + futures::future::join_all(self.gated_tasks.drain(..)).await; } } @@ -710,6 +754,13 @@ struct VmService { rpc_tasks: Vec>, /// Rejects an operation that conflicts with one already in flight. operation_gate: VmOperationGate, + /// In-flight gated operations that run as background tasks (device and + /// resource changes). + gated_tasks: Vec>, + /// Observed by every task in `gated_tasks`; cancelled by the terminal + /// operations (teardown and quit) through `gated_cancel`. + gated_cancel_ctx: mesh::CancelContext, + gated_cancel: mesh::Cancel, transport: ResolvedTransport, /// Registry of file descriptors passed in over the fd-passing protocol, /// resolvable by name (e.g. for tap NIC backends). @@ -755,12 +806,12 @@ impl VmService { response.send(map_grpc(self.teardown_vm().await)) } vmservice::Vm::Quit((), response) => { - // Let in-flight device and resource changes finish first. Each - // can hold a clone of a device RPC channel (for example the - // SCSI controller's), and a live channel keeps the worker from - // stopping, so dropping the VM under them could hang below. - // The VM is still running, so they complete normally. - futures::future::join_all(self.rpc_tasks.drain(..)).await; + // Quit is terminal. Cancel in-flight device and resource + // changes first: each can hold a clone of a device RPC channel + // (for example the SCSI controller's), and a live channel keeps + // the worker from stopping, so the controller wait below could + // otherwise hang. + self.cancel_gated_tasks().await; // Shut down the controller (which stops and joins the worker). // Drop the VM's device RPC channels first; see `teardown_vm`. self.vm.take(); @@ -1408,7 +1459,22 @@ impl VmService { Ok(()) } + /// Consomme port requests are serviced from the NIC's queue processing, + /// which is stopped while the VM is not running, so a request made then + /// would never complete. Reject it up front. + fn require_running_for_consomme_ports(&self) -> anyhow::Result<()> { + if !matches!(self.lifecycle, VmLifecycle::Running) { + return Err(anyhow::Error::new(Code::FailedPrecondition)) + .context("consomme port changes require a running VM"); + } + Ok(()) + } + async fn teardown_vm(&mut self) -> anyhow::Result<()> { + // Teardown is terminal: it cancels in-flight device and resource + // changes rather than being rejected by them. Pause and resume run + // inline, so none is in flight here and the gate is now free. + self.cancel_gated_tasks().await; let _gate = self.operation_gate.try_acquire(VmOperation::Teardown)?; let controller = self.vm_controller.take().context("vm not created")?; // Drop the VM's device RPC channels before waiting on the controller. @@ -1676,6 +1742,7 @@ impl VmService { vmservice::nic_config::Backend::Consomme(c) => c, _ => anyhow::bail!("port update only supported for consomme backend"), }; + self.require_running_for_consomme_ports()?; let consomme_rpc = vm .consomme_rpc .as_ref() @@ -1697,6 +1764,7 @@ impl VmService { vmservice::nic_config::Backend::Consomme(c) => c, _ => anyhow::bail!("port remove only supported for consomme backend"), }; + self.require_running_for_consomme_ports()?; let consomme_rpc = vm .consomme_rpc .as_ref() diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index fd61bfe6321..2d281a4bc4e 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -7,7 +7,9 @@ //! operations (hot add/remove of devices and resources) are independent of one //! another and share the gate; pause, resume, and teardown are exclusive and //! exclude everything else. The gate never queues: a conflicting caller is -//! rejected immediately with `ABORTED`. +//! rejected immediately with `ABORTED`. Teardown and quit are terminal: the +//! service cancels in-flight topology operations before acquiring the gate, so +//! they are never rejected by them. //! //! The gate must be acquired before any side effect of the operation, and is //! released when its guard drops, so completion, error, and cancellation all From 53d2ff7d859ac84585100c2bb1cebfd5137b2537 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Fri, 6 Nov 2026 11:14:56 +0530 Subject: [PATCH 05/17] vmm_tests: check Consomme port changes against the running-state rule Consomme port updates and removals now return FAILED_PRECONDITION unless the VM is running, since their requests are serviced by the NIC's queue processing, which is stopped while paused. test_ttrpc_interface sent malformed port requests while the VM was still paused after CreateVm and expected parse errors, so it now fails with FAILED_PRECONDITION instead. Assert FAILED_PRECONDITION for both update and removal while paused, run the malformed-port cases after ResumeVm, and check that a port change after PauseVm fails fast and doesn't block the teardown that follows. --- vmm_tests/vmm_tests/tests/tests/ttrpc.rs | 146 +++++++++++++++-------- 1 file changed, 96 insertions(+), 50 deletions(-) diff --git a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs index 9ec780db527..02d3c866d66 100644 --- a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs +++ b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs @@ -744,57 +744,50 @@ async fn test_ttrpc_interface( "memory/processor stats should be unset, not zeroed" ); - // Invalid options exercise Consomme update/remove without binding a port. - for modify_type in [vmservice::ModifyType::Update, vmservice::ModifyType::Remove] { - for (protocol, host_address, expected_error) in [ - (99, "", "invalid protocol"), - ( - vmservice::IpProtocol::Tcp as i32, - "not-an-ip-address", - "invalid host address", - ), - ( - vmservice::IpProtocol::Udp as i32, - "127.0.0.1:8080", - "invalid host address", - ), - ] { - let err = client - .call() - .start( - vmservice::Vm::ModifyResource, - vmservice::ModifyResourceRequest { - r#type: modify_type as i32, - resource: Some( - vmservice::modify_resource_request::Resource::NicConfig( - vmservice::NicConfig { - nic_id: consomme_nic_id.clone(), - mac_address: "00-15-5D-12-12-12".to_string(), - backend: Some(vmservice::nic_config::Backend::Consomme( - vmservice::ConsommeBackend { - cidr: String::new(), - ports: vec![vmservice::PortConfig { - host_port: 8080, - guest_port: 80, - protocol, - host_address: host_address.to_string(), - }], - }, - )), - ..Default::default() - }, - ), - ), + // Builds a Consomme port update or removal for the test NIC. + let consomme_port_change = + |modify_type: vmservice::ModifyType, protocol: i32, host_address: &str| { + vmservice::ModifyResourceRequest { + r#type: modify_type as i32, + resource: Some(vmservice::modify_resource_request::Resource::NicConfig( + vmservice::NicConfig { + nic_id: consomme_nic_id.clone(), + mac_address: "00-15-5D-12-12-12".to_string(), + backend: Some(vmservice::nic_config::Backend::Consomme( + vmservice::ConsommeBackend { + cidr: String::new(), + ports: vec![vmservice::PortConfig { + host_port: 8080, + guest_port: 80, + protocol, + host_address: host_address.to_string(), + }], + }, + )), + ..Default::default() }, - ) - .await - .unwrap_err(); - assert!( - err.message.contains(expected_error), - "expected {expected_error}, got: {}", - err.message - ); - } + )), + } + }; + + // Consomme port changes are serviced by the NIC's queue processing, + // which doesn't run while the VM is paused, so they are rejected until + // the VM runs. Port validation is exercised once the VM is running. + for modify_type in [vmservice::ModifyType::Update, vmservice::ModifyType::Remove] { + let err = client + .call() + .start( + vmservice::Vm::ModifyResource, + consomme_port_change(modify_type, vmservice::IpProtocol::Tcp as i32, ""), + ) + .await + .unwrap_err(); + assert_eq!( + err.code, + mesh_rpc::service::Code::FailedPrecondition as i32, + "consomme port change while paused: {}", + err.message + ); } // On iteration 0, exercise AddPcieDevice/RemovePcieDevice with @@ -1084,6 +1077,38 @@ async fn test_ttrpc_interface( "after ResumeVm, expected RUNNING" ); + // Invalid options exercise Consomme update/remove without + // binding a port. + for modify_type in [vmservice::ModifyType::Update, vmservice::ModifyType::Remove] { + for (protocol, host_address, expected_error) in [ + (99, "", "invalid protocol"), + ( + vmservice::IpProtocol::Tcp as i32, + "not-an-ip-address", + "invalid host address", + ), + ( + vmservice::IpProtocol::Udp as i32, + "127.0.0.1:8080", + "invalid host address", + ), + ] { + let err = client + .call() + .start( + vmservice::Vm::ModifyResource, + consomme_port_change(modify_type, protocol, host_address), + ) + .await + .unwrap_err(); + assert!( + err.message.contains(expected_error), + "expected {expected_error}, got: {}", + err.message + ); + } + } + client .call() .start(vmservice::Vm::PauseVm, ()) @@ -1097,6 +1122,27 @@ async fn test_ttrpc_interface( "after PauseVm, expected PAUSED" ); + // A port change after pausing fails fast instead of waiting on + // the stopped NIC, so it can't block the teardown below. + let err = client + .call() + .start( + vmservice::Vm::ModifyResource, + consomme_port_change( + vmservice::ModifyType::Update, + vmservice::IpProtocol::Tcp as i32, + "", + ), + ) + .await + .unwrap_err(); + assert_eq!( + err.code, + mesh_rpc::service::Code::FailedPrecondition as i32, + "consomme port change after PauseVm: {}", + err.message + ); + client .call() .start(vmservice::Vm::TeardownVm, ()) From 01853afa592f11af61d4e39c8dd8784f328bf1d1 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Fri, 6 Nov 2026 16:27:21 +0530 Subject: [PATCH 06/17] openvmm_entry: test cancelling an active gated operation Add a service-level regression for terminal cancellation of a gated operation that is waiting on a device reply. A SCSI disk add holds a clone of the controller sender and waits for the controller's reply; cancelling it must return CANCELLED to the caller, drop the cloned sender, and release the gate. A gated operation started afterwards must complete normally, which checks that the replacement cancellation context isn't already cancelled. --- openvmm/openvmm_entry/src/ttrpc/mod.rs | 75 ++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index bd5d31f7c28..004d5eadc48 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -3279,6 +3279,81 @@ mod tests { }); } + /// A terminal operation cancels a gated operation that is waiting on a + /// device reply: the caller gets `CANCELLED`, the operation drops its clone + /// of the device sender, the gate is released, and a gated operation started + /// afterwards isn't affected by the cancellation. + #[test] + fn terminal_cancellation_releases_active_gated_task() { + DefaultPool::run_with(async |driver| { + let mut service = service(driver, None); + let dir = tempfile::tempdir().unwrap(); + let disk_path = dir.path().join("disk.img"); + std::fs::write(&disk_path, vec![0; 0x100000]).unwrap(); + let add_disk = || vmservice::ModifyResourceRequest { + r#type: vmservice::ModifyType::Add as i32, + resource: Some(vmservice::modify_resource_request::Resource::ScsiDisk( + vmservice::ScsiDisk { + controller: 0, + lun: 0, + host_path: disk_path.to_str().unwrap().into(), + ..Default::default() + }, + )), + }; + + // Start a gated SCSI disk add and hold the controller's reply. + let (scsi_send, mut scsi_recv) = mesh::channel(); + Arc::get_mut(service.vm.as_mut().unwrap()).unwrap().scsi_rpc = Some(scsi_send); + let (send, recv) = mesh::oneshot(); + service.start_gated_rpc(VmOperation::Topology, send, |this| { + this.modify_resource(add_disk()) + }); + let ScsiControllerRequest::AddDevice(pending) = scsi_recv.next().await.unwrap() else { + panic!("expected a SCSI AddDevice request"); + }; + assert!( + service + .operation_gate + .try_acquire(VmOperation::Pause) + .is_err(), + "the gate is held while the change is in flight" + ); + + service.cancel_gated_tasks().await; + let status = recv.await.unwrap().unwrap_err(); + assert_eq!(status.code, i32::from(Code::Cancelled)); + drop( + service + .operation_gate + .try_acquire(VmOperation::Pause) + .expect("the gate is released after cancellation"), + ); + + // The cancelled operation no longer holds a controller sender: once + // the VM's own sender is dropped, the controller sees its channel + // close. + drop(pending); + Arc::get_mut(service.vm.as_mut().unwrap()).unwrap().scsi_rpc = None; + assert!(scsi_recv.next().await.is_none()); + + // A gated operation started after the cancellation completes + // normally. + let (scsi_send, mut scsi_recv) = mesh::channel(); + Arc::get_mut(service.vm.as_mut().unwrap()).unwrap().scsi_rpc = Some(scsi_send); + let (send, recv) = mesh::oneshot(); + service.start_gated_rpc(VmOperation::Topology, send, |this| { + this.modify_resource(add_disk()) + }); + let ScsiControllerRequest::AddDevice(rpc) = scsi_recv.next().await.unwrap() else { + panic!("expected a SCSI AddDevice request"); + }; + let (_config, response) = rpc.split(); + response.complete(Ok(())); + recv.await.unwrap().unwrap(); + }); + } + fn acpi_shutdown_request() -> vmservice::ShutdownVmRequest { vmservice::ShutdownVmRequest { mechanism: vmservice::shutdown_vm_request::Mechanism::Acpi as i32, From 5be0e3f5e0d7e9d02dd1f8e3c9a4639aeef3fa39 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Fri, 6 Nov 2026 16:39:39 +0530 Subject: [PATCH 07/17] openvmm_entry: clarify what terminal cancellation interrupts Cancelling a gated operation stops only the service-side wait. If the VM worker is itself blocked on the change, for example on a device backend that never responds, stopping the VM still waits for it. Say so in the gRPC reference and in the cancel_gated_tasks comment. --- Guide/src/reference/openvmm/management/grpc.md | 5 +++-- openvmm/openvmm_entry/src/ttrpc/mod.rs | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index ff82dd49c99..183a74c60a0 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -122,8 +122,9 @@ the server never retries it; the caller decides whether to retry. `TeardownVM` and `Quit` are terminal and are never rejected by in-flight device or resource changes. They cancel those changes first, and the cancelled calls return `CANCELLED`. Cancellation stops the server waiting for the change; -a change already delivered to the VM is completed or discarded when the VM -stops. +a change the VM is already processing still completes, or is discarded, when +the VM stops. If the VM is blocked on the change itself (for example, on a +device backend that never responds), stopping the VM waits for it. | Operation | Class | In-flight device or resource changes | |---|---|---| diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 004d5eadc48..19da4b3b341 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -630,7 +630,9 @@ impl VmService { /// example, a Consomme port change whose NIC is not processing its queue). /// The cancelled callers receive `CANCELLED`. Only the service-side wait /// is cancelled; a request already delivered to the VM is completed or - /// discarded when the VM worker stops. + /// discarded when the VM worker stops, and if the worker is blocked on it + /// (for example, on an unresponsive device backend), stopping the worker + /// waits for it. /// /// Cancellation drops the operation's future, so gated futures must be /// safe to drop at any await point. Today they await only RPC replies and From ea82f6d1eaabbcfa762409a6d0b784f532504359 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Tue, 10 Nov 2026 19:53:13 +0530 Subject: [PATCH 08/17] openvmm_entry: simplify the VM operation gate Teardown no longer acquires the gate after cancelling in-flight topology operations: pause and resume run inline, so the acquire could never fail. Remove the now-unused Teardown operation and the unused Clone on the gate. Document why Consomme NIC changes require a running VM: while paused they would hold the gate and block ResumeVM. The check is best effort; the root fix is servicing Consomme requests outside queue processing. Check that PauseVM returns ABORTED while a change is in flight, fold overlapping gate tests, and tighten the concurrent-operations guide. --- .../src/reference/openvmm/management/grpc.md | 59 +++++++------------ openvmm/openvmm_entry/src/ttrpc/mod.rs | 33 ++++++----- .../openvmm_entry/src/ttrpc/operation_gate.rs | 57 ++++++------------ 3 files changed, 60 insertions(+), 89 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index 183a74c60a0..4d7b4342dee 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -110,44 +110,29 @@ hotplug semantics or a non-VPCI host backend is required. ## Concurrent operations -VM-changing operations never overlap in a conflicting way. Device and resource -changes (`ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, -`AddVpciDevice`, `RemoveVpciDevice`) run in the background and may overlap one -another. `PauseVM` and `ResumeVM` are exclusive: if a device or resource change -is still in flight, they are rejected immediately with `ABORTED` and a message -naming both operations (for example, `VM busy: device or resource modification -in progress, cannot start pause`). A rejected request has no side effects, and -the server never retries it; the caller decides whether to retry. - -`TeardownVM` and `Quit` are terminal and are never rejected by in-flight -device or resource changes. They cancel those changes first, and the cancelled -calls return `CANCELLED`. Cancellation stops the server waiting for the change; -a change the VM is already processing still completes, or is discarded, when -the VM stops. If the VM is blocked on the change itself (for example, on a -device backend that never responds), stopping the VM waits for it. - -| Operation | Class | In-flight device or resource changes | +The server rejects a VM-changing request that conflicts with one already in +flight, rather than queuing it. + +| Operation | Class | While a device or resource change is in flight | |---|---|---| -| `PauseVM`, `ResumeVM` | Exclusive | Rejects the request with `ABORTED` | -| `TeardownVM`, `Quit` | Terminal | Cancelled; they return `CANCELLED` | -| `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Run alongside | - -`PauseVM`, `ResumeVM`, and `TeardownVM` run to completion before the server -reads its next request. Requests that arrive while one of them is running -therefore wait and are processed after it finishes, rather than being -rejected. - -`CreateVM` and the read-only RPCs (`WaitVM`, `CapabilitiesVM`, `PropertiesVM`) -are not gated. - -Otherwise, the gate is held until the operation finishes, whether it succeeds -or fails. A client that cancels or disconnects does not release it early, -because the operation itself keeps running to completion. - -Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme NIC, -including ports, DNS records, and virtual addresses) require a running VM and -fail with `FAILED_PRECONDITION` otherwise, because they are serviced by the -NIC's queue processing, which is stopped while the VM is paused. +| `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Runs alongside it | +| `PauseVM`, `ResumeVM` | Exclusive | Rejected with `ABORTED` | +| `TeardownVM`, `Quit` | Terminal | Cancels it; the change returns `CANCELLED` | + +- A rejected request has no side effects, and the server never retries it. +- `PauseVM`, `ResumeVM`, and `TeardownVM` complete before the server reads its + next request, so requests that arrive meanwhile wait instead of being + rejected. +- Cancelling a change stops the server waiting for it. A change the VM has + already received still completes, or is discarded when the VM stops; if the + VM is blocked on it (for example, on an unresponsive device backend), + stopping the VM waits for it. +- A client that cancels or disconnects does not end the operation early. +- `CreateVM`, `WaitVM`, `CapabilitiesVM`, and `PropertiesVM` are not gated. +- Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme + NIC, including ports, DNS records, and virtual addresses) require a running + VM and otherwise fail with `FAILED_PRECONDITION`, because the NIC processes + them only while the VM runs. ## Hvsocket relay listeners diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 167c55f5ae6..ff7dfd299d9 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -387,7 +387,7 @@ impl Worker for TtrpcWorker { fn run(self, recv: mesh::Receiver>) -> anyhow::Result<()> { DefaultPool::run_with(async |driver| { - let (topology_cancel_ctx, topology_cancel) = mesh::CancelContext::new().with_cancel(); + let (gated_cancel_ctx, gated_cancel) = mesh::CancelContext::new().with_cancel(); let mut service = VmService { driver, vm: None, @@ -399,8 +399,8 @@ impl Worker for TtrpcWorker { rpc_tasks: Vec::new(), operation_gate: VmOperationGate::default(), gated_tasks: Vec::new(), - gated_cancel_ctx: topology_cancel_ctx, - gated_cancel: topology_cancel, + gated_cancel_ctx, + gated_cancel, transport: self.transport, registry: FdRegistry::default(), }; @@ -1551,9 +1551,15 @@ impl VmService { } /// Consomme NIC changes (port, DNS record, and virtual-address requests) - /// are serviced from the NIC's queue processing, which is stopped while - /// the VM is not running, so a request made then would never complete. - /// Reject it up front. + /// are serviced only from the NIC's queue processing, which is stopped + /// while the VM is not running. Such a request would never complete, and + /// while waiting it would hold the gate, so `ResumeVM` would be rejected + /// and the VM could not run again until teardown. Reject it up front. + /// + /// This is best effort: a running guest that stops processing traffic can + /// still stall the request (teardown cancels it). The root fix is to + /// service these requests outside queue processing (see the TODO in + /// `net_consomme`'s `poll_ready`). fn require_running_for_consomme_changes(&self) -> anyhow::Result<()> { if !matches!(self.lifecycle, VmLifecycle::Running) { return Err(anyhow::Error::new(Code::FailedPrecondition)) @@ -1565,9 +1571,8 @@ impl VmService { async fn teardown_vm(&mut self) -> anyhow::Result<()> { // Teardown is terminal: it cancels in-flight device and resource // changes rather than being rejected by them. Pause and resume run - // inline, so none is in flight here and the gate is now free. + // inline, so neither can be in flight here. self.cancel_gated_tasks().await; - let _gate = self.operation_gate.try_acquire(VmOperation::Teardown)?; let controller = self.vm_controller.take().context("vm not created")?; // Drop the VM's device RPC channels before waiting on the controller. // A live `ScsiControllerRequest` sender keeps the detached storvsp task @@ -3323,12 +3328,12 @@ mod tests { let ScsiControllerRequest::AddDevice(pending) = scsi_recv.next().await.unwrap() else { panic!("expected a SCSI AddDevice request"); }; - assert!( - service - .operation_gate - .try_acquire(VmOperation::Pause) - .is_err(), - "the gate is held while the change is in flight" + let status = grpc_error(service.pause_vm().await.unwrap_err()); + assert_eq!( + status.code, + i32::from(Code::Aborted), + "PauseVM is rejected while the change is in flight: {}", + status.message ); service.cancel_gated_tasks().await; diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index 2d281a4bc4e..8f794cecf81 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -5,15 +5,15 @@ //! //! Operations that mutate the VM are admitted through this gate. Topology //! operations (hot add/remove of devices and resources) are independent of one -//! another and share the gate; pause, resume, and teardown are exclusive and -//! exclude everything else. The gate never queues: a conflicting caller is -//! rejected immediately with `ABORTED`. Teardown and quit are terminal: the -//! service cancels in-flight topology operations before acquiring the gate, so -//! they are never rejected by them. +//! another and share the gate; pause and resume are exclusive and exclude +//! everything else. The gate never queues: a conflicting caller is rejected +//! immediately with `ABORTED`. Teardown and quit are terminal and don't use +//! the gate: the service cancels in-flight topology operations instead. //! //! The gate must be acquired before any side effect of the operation, and is //! released when its guard drops, so completion, error, and cancellation all -//! release it. +//! release it. The state is behind `Arc>` because guards move into +//! spawned operation futures, which must be `Send`. use anyhow::Context; use mesh_rpc::service::Code; @@ -30,8 +30,6 @@ pub(crate) enum VmOperation { /// Hot add or remove of a device or resource. Shared with other topology /// operations. Topology, - /// Teardown of the VM. Exclusive. - Teardown, } impl VmOperation { @@ -40,7 +38,6 @@ impl VmOperation { VmOperation::Pause => "pause", VmOperation::Resume => "resume", VmOperation::Topology => "device or resource modification", - VmOperation::Teardown => "teardown", } } @@ -57,7 +54,6 @@ enum State { Exclusive(VmOperation), } -#[derive(Clone)] pub(crate) struct VmOperationGate { state: Arc>, } @@ -138,46 +134,31 @@ mod tests { VmOperation::Pause, VmOperation::Resume, VmOperation::Topology, - VmOperation::Teardown, ] { let status = grpc_error(gate.try_acquire(op).err().unwrap()); assert_eq!(status.code, i32::from(Code::Aborted)); - assert!(status.message.contains("VM busy"), "{}", status.message); + assert!( + status.message.contains(&format!( + "VM busy: pause in progress, cannot start {}", + op.name() + )), + "{}", + status.message + ); } } - #[test] - fn rejection_names_both_operations() { - let gate = VmOperationGate::default(); - let _guard = gate.try_acquire(VmOperation::Pause).unwrap(); - let status = grpc_error(gate.try_acquire(VmOperation::Resume).err().unwrap()); - assert!( - status - .message - .contains("pause in progress, cannot start resume"), - "{}", - status.message - ); - } - #[test] fn topology_operations_share_the_gate() { let gate = VmOperationGate::default(); let a = gate.try_acquire(VmOperation::Topology).unwrap(); let b = gate.try_acquire(VmOperation::Topology).unwrap(); assert!(gate.try_acquire(VmOperation::Pause).is_err()); - assert!(gate.try_acquire(VmOperation::Teardown).is_err()); drop(a); - assert!(gate.try_acquire(VmOperation::Teardown).is_err()); + assert!(gate.try_acquire(VmOperation::Resume).is_err()); drop(b); - assert!(gate.try_acquire(VmOperation::Teardown).is_ok()); - } - - #[test] - fn releases_on_drop() { - let gate = VmOperationGate::default(); - drop(gate.try_acquire(VmOperation::Pause).unwrap()); - drop(gate.try_acquire(VmOperation::Teardown).unwrap()); + drop(gate.try_acquire(VmOperation::Resume).unwrap()); + drop(gate.try_acquire(VmOperation::Topology).unwrap()); } #[test] @@ -190,8 +171,8 @@ mod tests { let _guard = guard; std::future::pending::<()>().await; }; - assert!(gate.try_acquire(VmOperation::Teardown).is_err()); + assert!(gate.try_acquire(VmOperation::Pause).is_err()); drop(fut); - assert!(gate.try_acquire(VmOperation::Teardown).is_ok()); + assert!(gate.try_acquire(VmOperation::Pause).is_ok()); } } From 094ab51d298eb9ef455ea27ae4f39d6c08abf421 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Wed, 11 Nov 2026 20:18:16 +0530 Subject: [PATCH 09/17] openvmm_entry: gate SaveVM and RestoreVM SaveVM and RestoreVM are exclusive VM operations: each is rejected with ABORTED while a device or resource change is in flight, and excludes new ones while it runs. SaveVM can be cancelled by its client while the controller keeps writing the snapshot. The service, not the request, holds the save's gate guard, so a cancelled save keeps the gate until the controller replies or the VM is torn down. --- .../src/reference/openvmm/management/grpc.md | 13 ++- openvmm/openvmm_entry/src/ttrpc/mod.rs | 108 +++++++++++++++++- .../openvmm_entry/src/ttrpc/operation_gate.rs | 17 ++- 3 files changed, 126 insertions(+), 12 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index f3d459d508b..d6aa46c029c 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -140,18 +140,21 @@ flight, rather than queuing it. | Operation | Class | While a device or resource change is in flight | |---|---|---| | `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Runs alongside it | -| `PauseVM`, `ResumeVM` | Exclusive | Rejected with `ABORTED` | +| `PauseVM`, `ResumeVM`, `SaveVM`, `RestoreVM` | Exclusive | Rejected with `ABORTED` | | `TeardownVM`, `Quit` | Terminal | Cancels it; the change returns `CANCELLED` | - A rejected request has no side effects, and the server never retries it. -- `PauseVM`, `ResumeVM`, and `TeardownVM` complete before the server reads its - next request, so requests that arrive meanwhile wait instead of being - rejected. +- `PauseVM`, `ResumeVM`, `SaveVM`, `RestoreVM`, and `TeardownVM` complete + before the server reads its next request, so requests that arrive meanwhile + wait instead of being rejected. - Cancelling a change stops the server waiting for it. A change the VM has already received still completes, or is discarded when the VM stops; if the VM is blocked on it (for example, on an unresponsive device backend), stopping the VM waits for it. -- A client that cancels or disconnects does not end the operation early. +- A client that cancels or disconnects does not end the operation early. If a + `SaveVM` client cancels, the save may still be writing the snapshot, so + device and resource changes, `PauseVM`, and `SaveVM` are rejected with + `ABORTED` until `TeardownVM`. - `CreateVM`, `WaitVM`, `CapabilitiesVM`, and `PropertiesVM` are not gated. - Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme NIC, including ports, DNS records, and virtual addresses) require a running diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index fe8915164ff..0b1104b515d 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -14,6 +14,7 @@ mod operation_gate; use fd_passing::FdRegistry; use operation_gate::VmOperation; use operation_gate::VmOperationGate; +use operation_gate::VmOperationGuard; /// On non-unix platforms the fd-passing protocol does not exist. The registry /// is still threaded through the shared NIC configuration code, so provide an @@ -401,6 +402,7 @@ impl Worker for TtrpcWorker { memory_backing_file: None, rpc_tasks: Vec::new(), operation_gate: VmOperationGate::default(), + save_guard: None, gated_tasks: Vec::new(), gated_cancel_ctx, gated_cancel, @@ -900,6 +902,11 @@ struct VmService { rpc_tasks: Vec>, /// Rejects an operation that conflicts with one already in flight. operation_gate: VmOperationGate, + /// The gate guard of a SaveVM whose controller request hasn't completed. + /// Held by the service rather than the request, so a client that cancels + /// SaveVM doesn't release the gate while the controller is still writing + /// the snapshot. Released when the save completes, or at teardown. + save_guard: Option, /// In-flight gated operations that run as background tasks (device and /// resource changes). gated_tasks: Vec>, @@ -1151,6 +1158,7 @@ impl VmService { let config = request .config .ok_or_else(|| anyhow!(Code::InvalidArgument).context("missing configuration"))?; + let _gate = self.operation_gate.try_acquire(VmOperation::Restore)?; if self.vm.is_some() { return Err(anyhow!(Code::FailedPrecondition).context("VM already created")); } @@ -1770,8 +1778,9 @@ impl VmService { async fn teardown_vm(&mut self) -> anyhow::Result<()> { // Teardown is terminal: it cancels in-flight device and resource - // changes rather than being rejected by them. Pause and resume run - // inline, so neither can be in flight here. + // changes rather than being rejected by them. Pause, resume, save, + // and restore run inline, so none can be in flight here, but a save + // whose client cancelled may still hold the gate (`save_guard`). self.cancel_gated_tasks().await; let controller = self.vm_controller.take().context("vm not created")?; // Drop the VM's device RPC channels before waiting on the controller. @@ -1788,6 +1797,7 @@ impl VmService { self.vm_controller_events.take(); self.lifecycle = VmLifecycle::Uninitialized; self.snapshot_saved = false; + self.save_guard = None; self.memory_backing_file = None; if let Some((_, response)) = self.wait_vm_response.take() { response.send(Err(grpc_error(anyhow!("VM torn down")))); @@ -1974,6 +1984,7 @@ impl VmService { anyhow!(Code::InvalidArgument).context("missing snapshot destination directory") ); } + let gate = self.operation_gate.try_acquire(VmOperation::Save)?; if !matches!(self.lifecycle, VmLifecycle::Running | VmLifecycle::Paused) { return Err( anyhow!(Code::FailedPrecondition).context("SaveVM requires a running or paused VM") @@ -2002,15 +2013,19 @@ impl VmService { // hard-links the guest memory backing file. Record that before // awaiting: if this future is dropped (the client cancelled), the // controller still finishes the save, and resuming would then write - // guest memory into the snapshot. + // guest memory into the snapshot. For the same reason the service, + // not this future, holds the gate: until the controller replies or, + // if the client cancels, until teardown. self.snapshot_saved = true; self.lifecycle = VmLifecycle::Paused; + self.save_guard = Some(gate); let result = controller .call(VmControllerRpc::SaveSnapshot, request.destination_dir) .await .map_err(anyhow::Error::from) .and_then(|r| r.map_err(anyhow::Error::from)); + self.save_guard = None; match result { Ok(snapshot_id) => Ok(vmservice::SaveVmResponse { snapshot_id: snapshot_id.to_string(), @@ -3499,6 +3514,7 @@ mod tests { memory_backing_file: None, rpc_tasks: Vec::new(), operation_gate: VmOperationGate::default(), + save_guard: None, gated_tasks: Vec::new(), gated_cancel_ctx, gated_cancel, @@ -3603,6 +3619,20 @@ mod tests { "PauseVM is rejected while the change is in flight: {}", status.message ); + let status = grpc_error( + service + .save_vm(vmservice::SaveVmRequest { + destination_dir: dir.path().join("snapshot").to_str().unwrap().into(), + }) + .await + .unwrap_err(), + ); + assert_eq!( + status.code, + i32::from(Code::Aborted), + "SaveVM is rejected while the change is in flight: {}", + status.message + ); service.cancel_gated_tasks().await; let status = recv.await.unwrap().unwrap_err(); @@ -3638,6 +3668,77 @@ mod tests { }); } + /// SaveVM holds the gate while the controller writes the snapshot. A + /// completed save releases it; a save whose client cancelled keeps it, + /// because the controller may still be writing, until teardown. + #[test] + fn save_holds_the_gate_until_the_controller_replies() { + DefaultPool::run_with(async |driver| { + let dir = tempfile::tempdir().unwrap(); + let request = |name: &str| vmservice::SaveVmRequest { + destination_dir: dir.path().join(name).to_str().unwrap().into(), + }; + let with_controller = |service: &mut VmService| { + let (send, recv) = mesh::channel(); + service.vm_controller = Some(send); + service.memory_backing_file = Some(dir.path().join("memory.bin")); + recv + }; + + // Completed save: the gate is released. + let mut svc = service(driver.clone(), None); + let mut controller = with_controller(&mut svc); + let (result, ()) = futures::join!(svc.save_vm(request("completed")), async { + let Some(VmControllerRpc::SaveSnapshot(rpc)) = controller.next().await else { + panic!("expected a SaveSnapshot request"); + }; + let (_dir, response) = rpc.split(); + response.complete(Ok(Guid::new_random())); + }); + result.unwrap(); + drop( + svc.operation_gate + .try_acquire(VmOperation::Topology) + .expect("a completed save releases the gate"), + ); + + // Cancelled save: the gate stays held until teardown. + let mut svc = service(driver, None); + let mut controller = with_controller(&mut svc); + let rpc = match futures::future::select( + std::pin::pin!(svc.save_vm(request("cancelled"))), + controller.next(), + ) + .await + { + futures::future::Either::Right((Some(VmControllerRpc::SaveSnapshot(rpc)), _)) => { + rpc + } + _ => panic!("expected a SaveSnapshot request"), + }; + let status = grpc_error( + svc.operation_gate + .try_acquire(VmOperation::Topology) + .err() + .expect("the gate stays held after the client cancels"), + ); + assert_eq!(status.code, i32::from(Code::Aborted)); + assert!( + status.message.contains("save in progress"), + "{}", + status.message + ); + let (_dir, response) = rpc.split(); + response.complete(Ok(Guid::new_random())); + svc.teardown_vm().await.unwrap(); + drop( + svc.operation_gate + .try_acquire(VmOperation::Topology) + .expect("teardown releases the gate"), + ); + }); + } + fn acpi_shutdown_request() -> vmservice::ShutdownVmRequest { vmservice::ShutdownVmRequest { mechanism: vmservice::shutdown_vm_request::Mechanism::Acpi as i32, @@ -4503,6 +4604,7 @@ mod tests { memory_backing_file: None, rpc_tasks: vec![driver.spawn("pending-rpc", std::future::pending())], operation_gate: VmOperationGate::default(), + save_guard: None, gated_tasks: Vec::new(), gated_cancel_ctx, gated_cancel, diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index 8f794cecf81..e0503969754 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -5,10 +5,11 @@ //! //! Operations that mutate the VM are admitted through this gate. Topology //! operations (hot add/remove of devices and resources) are independent of one -//! another and share the gate; pause and resume are exclusive and exclude -//! everything else. The gate never queues: a conflicting caller is rejected -//! immediately with `ABORTED`. Teardown and quit are terminal and don't use -//! the gate: the service cancels in-flight topology operations instead. +//! another and share the gate; pause, resume, save, and restore are exclusive +//! and exclude everything else. The gate never queues: a conflicting caller is +//! rejected immediately with `ABORTED`. Teardown and quit are terminal and +//! don't use the gate: the service cancels in-flight topology operations +//! instead. //! //! The gate must be acquired before any side effect of the operation, and is //! released when its guard drops, so completion, error, and cancellation all @@ -27,6 +28,10 @@ pub(crate) enum VmOperation { Pause, /// Resume. Exclusive. Resume, + /// Save a snapshot. Exclusive. + Save, + /// Restore a VM from a snapshot. Exclusive. + Restore, /// Hot add or remove of a device or resource. Shared with other topology /// operations. Topology, @@ -37,6 +42,8 @@ impl VmOperation { match self { VmOperation::Pause => "pause", VmOperation::Resume => "resume", + VmOperation::Save => "save", + VmOperation::Restore => "restore", VmOperation::Topology => "device or resource modification", } } @@ -133,6 +140,8 @@ mod tests { for op in [ VmOperation::Pause, VmOperation::Resume, + VmOperation::Save, + VmOperation::Restore, VmOperation::Topology, ] { let status = grpc_error(gate.try_acquire(op).err().unwrap()); From 55bbe59f46b76e1c89977166c900e6121f60fa0b Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Wed, 11 Nov 2026 21:34:27 +0530 Subject: [PATCH 10/17] openvmm_entry: gate only SaveVM, after its preconditions RestoreVM requires that no VM exists, so no gated change can be in flight and the gate could only replace its FAILED_PRECONDITION with ABORTED. Drop the restore kind. SaveVM now takes the gate after the checks a retry can't change, so a second save after a cancelled one fails with FAILED_PRECONDITION rather than a retryable ABORTED. --- .../src/reference/openvmm/management/grpc.md | 16 +++++++------ openvmm/openvmm_entry/src/ttrpc/mod.rs | 23 +++++++++++++++---- .../openvmm_entry/src/ttrpc/operation_gate.rs | 8 ++----- vmm_tests/vmm_tests/tests/tests/ttrpc.rs | 7 +++--- 4 files changed, 33 insertions(+), 21 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index d6aa46c029c..e467adf84d4 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -140,22 +140,24 @@ flight, rather than queuing it. | Operation | Class | While a device or resource change is in flight | |---|---|---| | `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Runs alongside it | -| `PauseVM`, `ResumeVM`, `SaveVM`, `RestoreVM` | Exclusive | Rejected with `ABORTED` | +| `PauseVM`, `ResumeVM`, `SaveVM` | Exclusive | Rejected with `ABORTED` | | `TeardownVM`, `Quit` | Terminal | Cancels it; the change returns `CANCELLED` | - A rejected request has no side effects, and the server never retries it. -- `PauseVM`, `ResumeVM`, `SaveVM`, `RestoreVM`, and `TeardownVM` complete - before the server reads its next request, so requests that arrive meanwhile - wait instead of being rejected. +- `PauseVM`, `ResumeVM`, `SaveVM`, and `TeardownVM` complete before the server + reads its next request, so requests that arrive meanwhile wait instead of + being rejected. - Cancelling a change stops the server waiting for it. A change the VM has already received still completes, or is discarded when the VM stops; if the VM is blocked on it (for example, on an unresponsive device backend), stopping the VM waits for it. - A client that cancels or disconnects does not end the operation early. If a `SaveVM` client cancels, the save may still be writing the snapshot, so - device and resource changes, `PauseVM`, and `SaveVM` are rejected with - `ABORTED` until `TeardownVM`. -- `CreateVM`, `WaitVM`, `CapabilitiesVM`, and `PropertiesVM` are not gated. + device and resource changes and `PauseVM` are rejected with `ABORTED` until + `TeardownVM`. +- `CreateVM`, `RestoreVM`, `WaitVM`, `CapabilitiesVM`, and `PropertiesVM` are + not gated. `CreateVM` and `RestoreVM` require that no VM exists, so no change + can be in flight. - Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme NIC, including ports, DNS records, and virtual addresses) require a running VM and otherwise fail with `FAILED_PRECONDITION`, because the NIC processes diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 0b1104b515d..ce724968b95 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -1158,7 +1158,6 @@ impl VmService { let config = request .config .ok_or_else(|| anyhow!(Code::InvalidArgument).context("missing configuration"))?; - let _gate = self.operation_gate.try_acquire(VmOperation::Restore)?; if self.vm.is_some() { return Err(anyhow!(Code::FailedPrecondition).context("VM already created")); } @@ -1778,9 +1777,9 @@ impl VmService { async fn teardown_vm(&mut self) -> anyhow::Result<()> { // Teardown is terminal: it cancels in-flight device and resource - // changes rather than being rejected by them. Pause, resume, save, - // and restore run inline, so none can be in flight here, but a save - // whose client cancelled may still hold the gate (`save_guard`). + // changes rather than being rejected by them. Pause, resume, and save + // run inline, so none can be in flight here, but a save whose client + // cancelled may still hold the gate (`save_guard`). self.cancel_gated_tasks().await; let controller = self.vm_controller.take().context("vm not created")?; // Drop the VM's device RPC channels before waiting on the controller. @@ -1984,7 +1983,6 @@ impl VmService { anyhow!(Code::InvalidArgument).context("missing snapshot destination directory") ); } - let gate = self.operation_gate.try_acquire(VmOperation::Save)?; if !matches!(self.lifecycle, VmLifecycle::Running | VmLifecycle::Paused) { return Err( anyhow!(Code::FailedPrecondition).context("SaveVM requires a running or paused VM") @@ -2004,6 +2002,9 @@ impl VmService { return Err(anyhow!(Code::FailedPrecondition) .context("SaveVM requires MemoryConfig.backing_file_path")); } + // After the checks above, which a retry can't change, so a conflict is + // the only reason to report `ABORTED`. + let gate = self.operation_gate.try_acquire(VmOperation::Save)?; // Check the destination before the controller pauses the VM, so a // rejected destination leaves the VM untouched. openvmm_helpers::snapshot::check_snapshot_destination(Path::new(&request.destination_dir)) @@ -3619,6 +3620,9 @@ mod tests { "PauseVM is rejected while the change is in flight: {}", status.message ); + let (controller, _controller_recv) = mesh::channel(); + service.vm_controller = Some(controller); + service.memory_backing_file = Some(dir.path().join("memory.bin")); let status = grpc_error( service .save_vm(vmservice::SaveVmRequest { @@ -3728,6 +3732,15 @@ mod tests { "{}", status.message ); + // A second save fails on its precondition, not the gate, so the + // client doesn't retry it. + let status = grpc_error(svc.save_vm(request("again")).await.unwrap_err()); + assert_eq!( + status.code, + i32::from(Code::FailedPrecondition), + "{}", + status.message + ); let (_dir, response) = rpc.split(); response.complete(Ok(Guid::new_random())); svc.teardown_vm().await.unwrap(); diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index e0503969754..4e853451ef1 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -5,8 +5,8 @@ //! //! Operations that mutate the VM are admitted through this gate. Topology //! operations (hot add/remove of devices and resources) are independent of one -//! another and share the gate; pause, resume, save, and restore are exclusive -//! and exclude everything else. The gate never queues: a conflicting caller is +//! another and share the gate; pause, resume, and save are exclusive and +//! exclude everything else. The gate never queues: a conflicting caller is //! rejected immediately with `ABORTED`. Teardown and quit are terminal and //! don't use the gate: the service cancels in-flight topology operations //! instead. @@ -30,8 +30,6 @@ pub(crate) enum VmOperation { Resume, /// Save a snapshot. Exclusive. Save, - /// Restore a VM from a snapshot. Exclusive. - Restore, /// Hot add or remove of a device or resource. Shared with other topology /// operations. Topology, @@ -43,7 +41,6 @@ impl VmOperation { VmOperation::Pause => "pause", VmOperation::Resume => "resume", VmOperation::Save => "save", - VmOperation::Restore => "restore", VmOperation::Topology => "device or resource modification", } } @@ -141,7 +138,6 @@ mod tests { VmOperation::Pause, VmOperation::Resume, VmOperation::Save, - VmOperation::Restore, VmOperation::Topology, ] { let status = grpc_error(gate.try_acquire(op).err().unwrap()); diff --git a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs index 5c7cb30c9aa..e432068facd 100644 --- a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs +++ b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs @@ -1775,8 +1775,9 @@ async fn test_ttrpc_interface( .await .unwrap_err(); - // A port change after pausing fails fast instead of waiting on - // the stopped NIC, so it can't block the teardown below. + // The VM is paused after the save, so a port change fails fast + // instead of waiting on the stopped NIC, and can't block the + // teardown below. let err = client .call() .start( @@ -1792,7 +1793,7 @@ async fn test_ttrpc_interface( assert_eq!( err.code, mesh_rpc::service::Code::FailedPrecondition as i32, - "consomme port change after PauseVm: {}", + "consomme port change while paused after SaveVm: {}", err.message ); From c6c2a6704d2ff07685dccc4d5a89f3ce8a1a22fc Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Wed, 11 Nov 2026 22:38:51 +0530 Subject: [PATCH 11/17] openvmm_entry: release a cancelled save's gate when the worker stops A save whose client cancelled holds the gate until teardown. If the worker stops first, teardown fails before releasing it, so a later VM stayed gated. Release it in the WorkerStopped cleanup, and clarify the Guide's wording on inline operations and Consomme argument errors. --- .../src/reference/openvmm/management/grpc.md | 12 ++++---- openvmm/openvmm_entry/src/ttrpc/mod.rs | 29 +++++++++++++++++-- .../openvmm_entry/src/ttrpc/operation_gate.rs | 1 + 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index e467adf84d4..cd6132d44eb 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -145,8 +145,9 @@ flight, rather than queuing it. - A rejected request has no side effects, and the server never retries it. - `PauseVM`, `ResumeVM`, `SaveVM`, and `TeardownVM` complete before the server - reads its next request, so requests that arrive meanwhile wait instead of - being rejected. + reads its next request, so they never conflict with each other. A request + sent meanwhile is read only afterwards, and is then admitted or rejected as + above. - Cancelling a change stops the server waiting for it. A change the VM has already received still completes, or is discarded when the VM stops; if the VM is blocked on it (for example, on an unresponsive device backend), @@ -154,14 +155,15 @@ flight, rather than queuing it. - A client that cancels or disconnects does not end the operation early. If a `SaveVM` client cancels, the save may still be writing the snapshot, so device and resource changes and `PauseVM` are rejected with `ABORTED` until - `TeardownVM`. + `TeardownVM` or until the VM worker stops. - `CreateVM`, `RestoreVM`, `WaitVM`, `CapabilitiesVM`, and `PropertiesVM` are not gated. `CreateVM` and `RestoreVM` require that no VM exists, so no change can be in flight. - Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme NIC, including ports, DNS records, and virtual addresses) require a running - VM and otherwise fail with `FAILED_PRECONDITION`, because the NIC processes - them only while the VM runs. + VM. A well-formed change otherwise fails with `FAILED_PRECONDITION`, because + the NIC processes these changes only while the VM runs; a malformed one is + rejected for its arguments first. ## Hvsocket relay listeners diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index ce724968b95..817cdc40a2d 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -905,7 +905,8 @@ struct VmService { /// The gate guard of a SaveVM whose controller request hasn't completed. /// Held by the service rather than the request, so a client that cancels /// SaveVM doesn't release the gate while the controller is still writing - /// the snapshot. Released when the save completes, or at teardown. + /// the snapshot. Released when the save completes, at teardown, or when + /// the worker stops. save_guard: Option, /// In-flight gated operations that run as background tasks (device and /// resource changes). @@ -2070,9 +2071,12 @@ impl VmService { response.send(Err(status)); } // Clear VM state since the worker is gone. The controller - // task will be awaited during final cleanup. + // task will be awaited during final cleanup. A save whose + // client cancelled can no longer be writing, so release its + // gate too; otherwise a later VM would stay gated. self.vm.take(); self.vm_controller.take(); + self.save_guard = None; self.lifecycle = VmLifecycle::Uninitialized; } VmControllerEvent::VncWorkerStopped { error } => { @@ -3707,7 +3711,7 @@ mod tests { ); // Cancelled save: the gate stays held until teardown. - let mut svc = service(driver, None); + let mut svc = service(driver.clone(), None); let mut controller = with_controller(&mut svc); let rpc = match futures::future::select( std::pin::pin!(svc.save_vm(request("cancelled"))), @@ -3749,6 +3753,25 @@ mod tests { .try_acquire(VmOperation::Topology) .expect("teardown releases the gate"), ); + + // Cancelled save, then the worker stops: the gate is released, so + // a later VM isn't blocked. + let mut svc = service(driver, None); + let mut controller = with_controller(&mut svc); + drop( + futures::future::select( + std::pin::pin!(svc.save_vm(request("worker-stopped"))), + controller.next(), + ) + .await, + ); + assert!(svc.save_guard.is_some()); + svc.handle_controller_event(VmControllerEvent::WorkerStopped { error: None }); + drop( + svc.operation_gate + .try_acquire(VmOperation::Topology) + .expect("a stopped worker releases the gate"), + ); }); } diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index 4e853451ef1..4db542a65e6 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -92,6 +92,7 @@ impl VmOperationGate { None } (State::Shared(n), true) => { + // Bounded by the in-flight RPC tasks, far below `u32::MAX`. *state = State::Shared(n + 1); None } From e7da7389c9d34f3618c42ba5c07f26b2c783e530 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Thu, 12 Nov 2026 13:01:57 +0530 Subject: [PATCH 12/17] openvmm_entry: check Consomme state before options; bound the shared count A Consomme NIC change on a paused VM now fails with FAILED_PRECONDITION before its options are validated. The backend is checked first, so other NIC backends keep their own error. The gate's shared-operation count uses checked_add and fails with RESOURCE_EXHAUSTED rather than wrapping. --- .../src/reference/openvmm/management/grpc.md | 6 +- openvmm/openvmm_entry/src/ttrpc/mod.rs | 60 ++++++++++++++++++- .../openvmm_entry/src/ttrpc/operation_gate.rs | 25 ++++++-- 3 files changed, 83 insertions(+), 8 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index cd6132d44eb..63bb33cdeb6 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -161,9 +161,9 @@ flight, rather than queuing it. can be in flight. - Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme NIC, including ports, DNS records, and virtual addresses) require a running - VM. A well-formed change otherwise fails with `FAILED_PRECONDITION`, because - the NIC processes these changes only while the VM runs; a malformed one is - rejected for its arguments first. + VM and otherwise fail with `FAILED_PRECONDITION`, before the rest of the + change is validated, because the NIC processes these changes only while the + VM runs. ## Hvsocket relay listeners diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 817cdc40a2d..4d0a24eb611 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -2237,8 +2237,17 @@ impl VmService { } else if request.r#type == vmservice::ModifyType::Update as i32 || request.r#type == vmservice::ModifyType::Remove as i32 { + // Check the VM state once the NIC is known to be a + // Consomme NIC, before validating the rest of the change: + // a paused VM fails fast with `FAILED_PRECONDITION`, and + // other backends still get `parse`'s backend error. + if matches!( + nic.backend, + Some(vmservice::nic_config::Backend::Consomme(_)) + ) { + self.require_running_for_consomme_changes()?; + } let modification = ConsommeNicModification::parse(nic, request.r#type)?; - self.require_running_for_consomme_changes()?; Ok(modify_consomme_nic(vm, modification)?.boxed()) } else { anyhow::bail!("unsupported NIC modify type {}", request.r#type); @@ -3584,6 +3593,55 @@ mod tests { }); } + /// While the VM is paused, a Consomme NIC change fails on the VM state + /// before the rest of the change is validated; a NIC with another backend + /// still gets the backend error. + #[test] + fn consomme_change_while_paused_checks_backend_then_state() { + DefaultPool::run_with(async |driver| { + let mut service = service(driver, None); + service.lifecycle = VmLifecycle::Paused; + let nic_update = |backend| vmservice::ModifyResourceRequest { + r#type: vmservice::ModifyType::Update as i32, + resource: Some(vmservice::modify_resource_request::Resource::NicConfig( + vmservice::NicConfig { + nic_id: Guid::new_random().to_string(), + backend: Some(backend), + ..Default::default() + }, + )), + }; + + // The invalid protocol isn't reached: the state is checked first. + let consomme = vmservice::nic_config::Backend::Consomme(vmservice::ConsommeBackend { + ports: vec![vmservice::PortConfig { + host_port: 8080, + guest_port: 80, + protocol: 99, + host_address: String::new(), + }], + ..Default::default() + }); + let status = grpc_error(service.modify_resource(nic_update(consomme)).err().unwrap()); + assert_eq!( + status.code, + i32::from(Code::FailedPrecondition), + "{}", + status.message + ); + + let tap = vmservice::nic_config::Backend::Tap(Default::default()); + let status = grpc_error(service.modify_resource(nic_update(tap)).err().unwrap()); + assert!( + status + .message + .contains("only supported for consomme backend"), + "{}", + status.message + ); + }); + } + /// A terminal operation cancels a gated operation that is waiting on a /// device reply: the caller gets `CANCELLED`, the operation drops its clone /// of the device sender, the gate is released, and a gated operation started diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index 4db542a65e6..abe8cf591f0 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -78,8 +78,9 @@ pub(crate) struct VmOperationGuard { } impl VmOperationGate { - /// Acquires the gate for `operation`, or fails with `ABORTED` if a - /// conflicting operation holds it. + /// Acquires the gate for `operation`. Fails with `ABORTED` if a + /// conflicting operation holds it, or with `RESOURCE_EXHAUSTED` if the + /// shared-operation count would overflow. pub(crate) fn try_acquire(&self, operation: VmOperation) -> anyhow::Result { let mut state = self.state.lock(); let held = match (*state, operation.is_shared()) { @@ -92,8 +93,15 @@ impl VmOperationGate { None } (State::Shared(n), true) => { - // Bounded by the in-flight RPC tasks, far below `u32::MAX`. - *state = State::Shared(n + 1); + let Some(n) = n.checked_add(1) else { + return Err(anyhow::Error::new(Code::ResourceExhausted)).with_context(|| { + format!( + "too many operations in progress, cannot start {}", + operation.name() + ) + }); + }; + *state = State::Shared(n); None } (State::Shared(_), false) => Some(VmOperation::Topology), @@ -167,6 +175,15 @@ mod tests { drop(gate.try_acquire(VmOperation::Topology).unwrap()); } + #[test] + fn shared_count_overflow_is_rejected_without_changing_state() { + let gate = VmOperationGate::default(); + *gate.state.lock() = State::Shared(u32::MAX); + let status = grpc_error(gate.try_acquire(VmOperation::Topology).err().unwrap()); + assert_eq!(status.code, i32::from(Code::ResourceExhausted)); + assert_eq!(*gate.state.lock(), State::Shared(u32::MAX)); + } + #[test] fn releases_when_holding_future_is_dropped() { let gate = VmOperationGate::default(); From 042862f882de4ff7cae190787683c4c351e33303 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Fri, 20 Nov 2026 23:17:29 +0530 Subject: [PATCH 13/17] openvmm_entry: seal mutations after SaveVM --- .../src/reference/openvmm/management/grpc.md | 24 ++- openvmm/openvmm_entry/src/ttrpc/mod.rs | 150 +++++++++++++----- .../openvmm_entry/src/ttrpc/operation_gate.rs | 43 ++++- 3 files changed, 172 insertions(+), 45 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index 63bb33cdeb6..b0cdc2c8c23 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -51,11 +51,16 @@ before their implementation is connected end to end. `state.bin`, and `memory.bin` to the requested directory. The VM must use the `MemoryConfig.backing_file_path` setting. The currently supported implementation hard-links that backing file into the snapshot, so after a -successful save the VM can't be resumed and should be torn down. Each save -generates a unique snapshot ID (a GUID string) that is stored in +successful save the VM is terminal and can't be resumed or reused. Its state +is `Halted` with halt reason `snapshot saved`; `PropertiesVM`, `WaitVM`, and +`Quit` remain available. `TeardownVM`, `CreateVM`, `RestoreVM`, and VM-changing +operations return `FAILED_PRECONDITION`. The management client must send +`Quit` and wait for process exit. Each save generates a unique snapshot ID (a +GUID string) that is stored in `manifest.bin` and returned in `SaveVMResponse.snapshot_id`. Cancelling `SaveVM` only stops the caller from waiting; the save may still -complete. +complete, so the service becomes terminal before waiting and remains terminal +until `Quit`. `RestoreVM` creates a VM from a snapshot directory and a compatible `VMConfig`. Device configuration is not stored in the snapshot and must be @@ -141,7 +146,7 @@ flight, rather than queuing it. |---|---|---| | `ModifyResource`, `AddPcieDevice`, `RemovePcieDevice`, `AddVpciDevice`, `RemoveVpciDevice` | Shared | Runs alongside it | | `PauseVM`, `ResumeVM`, `SaveVM` | Exclusive | Rejected with `ABORTED` | -| `TeardownVM`, `Quit` | Terminal | Cancels it; the change returns `CANCELLED` | +| `TeardownVM` before Save, `Quit` | Terminal | Cancels it; the change returns `CANCELLED` | - A rejected request has no side effects, and the server never retries it. - `PauseVM`, `ResumeVM`, `SaveVM`, and `TeardownVM` complete before the server @@ -154,11 +159,16 @@ flight, rather than queuing it. stopping the VM waits for it. - A client that cancels or disconnects does not end the operation early. If a `SaveVM` client cancels, the save may still be writing the snapshot, so - device and resource changes and `PauseVM` are rejected with `ABORTED` until - `TeardownVM` or until the VM worker stops. + the service remains terminal. Device and resource changes and lifecycle + operations return `FAILED_PRECONDITION`; the client must send `Quit` or + wait for the VM worker to stop. +- Once `SaveVM` commits, the VM operation gate is sealed. This prevents a + caller from accidentally resuming, mutating, tearing down, or recreating the + saved VM in the same process. - `CreateVM`, `RestoreVM`, `WaitVM`, `CapabilitiesVM`, and `PropertiesVM` are not gated. `CreateVM` and `RestoreVM` require that no VM exists, so no change - can be in flight. + can be in flight. After a committed or uncertain Save, `CreateVM` and + `RestoreVM` are rejected with `FAILED_PRECONDITION` until `Quit`. - Consomme NIC changes (`ModifyResource` `UPDATE` or `REMOVE` of a Consomme NIC, including ports, DNS records, and virtual addresses) require a running VM and otherwise fail with `FAILED_PRECONDITION`, before the rest of the diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 4d0a24eb611..a55a4f7049b 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -586,6 +586,15 @@ impl VmService { } } + fn ensure_vm_mutation_allowed(&self, operation: &str) -> anyhow::Result<()> { + if self.snapshot_saved { + return Err(anyhow::Error::new(Code::FailedPrecondition).context(format!( + "{operation} is not allowed after SaveVM; only PropertiesVM, WaitVM, and Quit are allowed" + ))); + } + Ok(()) + } + /// Like [`Self::start_rpc`], but admits the operation through the /// VM-mutation gate first. `build` runs only after admission, so a rejected /// operation has no side effects, and the gate is held until the operation @@ -600,6 +609,10 @@ impl VmService { F: 'static + Future> + Send, R: 'static + MeshPayload + Send, { + if let Err(err) = self.ensure_vm_mutation_allowed("device or resource modification") { + response.send(Err(grpc_error(err))); + return; + } let fut = match self .operation_gate .try_acquire(operation) @@ -905,8 +918,8 @@ struct VmService { /// The gate guard of a SaveVM whose controller request hasn't completed. /// Held by the service rather than the request, so a client that cancels /// SaveVM doesn't release the gate while the controller is still writing - /// the snapshot. Released when the save completes, at teardown, or when - /// the worker stops. + /// the snapshot. Released when the save completes, `Quit` terminates the + /// service, or the worker stops. save_guard: Option, /// In-flight gated operations that run as background tasks (device and /// resource changes). @@ -1079,7 +1092,10 @@ impl VmService { self.start_rpc(response, Ok(self.inspect(ctx, request))) } InspectService::Update(request, response) => { - self.start_rpc(response, Ok(self.update(ctx, request))) + let r = self + .ensure_vm_mutation_allowed("inspect update") + .map(|()| self.update(ctx, request)); + self.start_rpc(response, r) } } } @@ -1132,6 +1148,7 @@ impl VmService { } async fn create_vm(&mut self, request: vmservice::CreateVmRequest) -> anyhow::Result<()> { + self.ensure_vm_mutation_allowed("CreateVM")?; let req_config = request.config.context("missing configuration")?; self.create_vm_inner(req_config, None).await.map(drop) } @@ -1140,6 +1157,7 @@ impl VmService { &mut self, request: vmservice::RestoreVmRequest, ) -> anyhow::Result { + self.ensure_vm_mutation_allowed("RestoreVM")?; let source_dir = PathBuf::from(request.source_dir); if source_dir.as_os_str().is_empty() { return Err(anyhow!(Code::InvalidArgument).context("missing snapshot source directory")); @@ -1198,6 +1216,7 @@ impl VmService { mut req_config: vmservice::VmConfig, restore: Option, ) -> anyhow::Result> { + self.ensure_vm_mutation_allowed("CreateVM or RestoreVM")?; if self.vm.is_some() { bail!("VM already created"); } @@ -1777,10 +1796,11 @@ impl VmService { } async fn teardown_vm(&mut self) -> anyhow::Result<()> { + self.ensure_vm_mutation_allowed("TeardownVM")?; // Teardown is terminal: it cancels in-flight device and resource // changes rather than being rejected by them. Pause, resume, and save - // run inline, so none can be in flight here, but a save whose client - // cancelled may still hold the gate (`save_guard`). + // run inline, so none can be in flight here. A cancelled save is + // already terminal and was rejected above; only Quit can consume it. self.cancel_gated_tasks().await; let controller = self.vm_controller.take().context("vm not created")?; // Drop the VM's device RPC channels before waiting on the controller. @@ -1853,6 +1873,7 @@ impl VmService { mut ctx: mesh::CancelContext, request: vmservice::ShutdownVmRequest, ) -> anyhow::Result> + use<>> { + self.ensure_vm_mutation_allowed("ShutdownVM")?; use vmservice::shutdown_vm_request::Mechanism; enum ShutdownSender { @@ -1945,6 +1966,7 @@ impl VmService { } async fn pause_vm(&mut self) -> anyhow::Result<()> { + self.ensure_vm_mutation_allowed("PauseVM")?; let _gate = self.operation_gate.try_acquire(VmOperation::Pause)?; let vm = self.vm.clone().context("VM not created yet")?; vm.worker_rpc @@ -1959,9 +1981,7 @@ impl VmService { } async fn resume_vm(&mut self) -> anyhow::Result<()> { - if self.snapshot_saved { - bail!("cannot resume a VM after SaveVM"); - } + self.ensure_vm_mutation_allowed("ResumeVM")?; let _gate = self.operation_gate.try_acquire(VmOperation::Resume)?; let vm = self.vm.clone().context("VM not created yet")?; vm.worker_rpc @@ -1984,17 +2004,18 @@ impl VmService { anyhow!(Code::InvalidArgument).context("missing snapshot destination directory") ); } + // The snapshot shares the VM's memory backing file, so only one + // snapshot per VM is allowed. + if self.snapshot_saved { + return Err(anyhow!(Code::FailedPrecondition).context( + "VM is terminal after SaveVM; only PropertiesVM, WaitVM, and Quit are allowed", + )); + } if !matches!(self.lifecycle, VmLifecycle::Running | VmLifecycle::Paused) { return Err( anyhow!(Code::FailedPrecondition).context("SaveVM requires a running or paused VM") ); } - // The snapshot shares the VM's memory backing file, so only one - // snapshot per VM is allowed. - if self.snapshot_saved { - return Err(anyhow!(Code::FailedPrecondition) - .context("VM already saved; tear down the VM or restore the snapshot")); - } let controller = self .vm_controller .clone() @@ -2017,9 +2038,10 @@ impl VmService { // controller still finishes the save, and resuming would then write // guest memory into the snapshot. For the same reason the service, // not this future, holds the gate: until the controller replies or, - // if the client cancels, until teardown. + // if the client cancels, until Quit or worker failure. self.snapshot_saved = true; - self.lifecycle = VmLifecycle::Paused; + self.lifecycle = + VmLifecycle::Halted("snapshot save in progress or committed; Quit the VM".into()); self.save_guard = Some(gate); let result = controller @@ -2029,15 +2051,20 @@ impl VmService { .and_then(|r| r.map_err(anyhow::Error::from)); self.save_guard = None; match result { - Ok(snapshot_id) => Ok(vmservice::SaveVmResponse { - snapshot_id: snapshot_id.to_string(), - }), + Ok(snapshot_id) => { + self.operation_gate.seal(); + self.lifecycle = VmLifecycle::Halted("snapshot saved".into()); + Ok(vmservice::SaveVmResponse { + snapshot_id: snapshot_id.to_string(), + }) + } Err(err) => { // On failure the controller removes the files it created, so // no snapshot references guest memory and the VM may be // resumed. The prechecks above ensure the controller paused // the VM before failing, so the VM stays paused. self.snapshot_saved = false; + self.lifecycle = VmLifecycle::Paused; Err(err).context("snapshot failed") } } @@ -2073,11 +2100,19 @@ impl VmService { // Clear VM state since the worker is gone. The controller // task will be awaited during final cleanup. A save whose // client cancelled can no longer be writing, so release its - // gate too; otherwise a later VM would stay gated. + // gate too; snapshot_saved keeps subsequent operations terminal + // until Quit rather than permitting a later VM in this process. self.vm.take(); self.vm_controller.take(); self.save_guard = None; - self.lifecycle = VmLifecycle::Uninitialized; + if self.snapshot_saved { + self.operation_gate.seal(); + self.lifecycle = VmLifecycle::Halted( + "snapshot save committed or outcome uncertain; Quit the VM".into(), + ); + } else { + self.lifecycle = VmLifecycle::Uninitialized; + } } VmControllerEvent::VncWorkerStopped { error } => { if let Some(err) = &error { @@ -3735,8 +3770,8 @@ mod tests { } /// SaveVM holds the gate while the controller writes the snapshot. A - /// completed save releases it; a save whose client cancelled keeps it, - /// because the controller may still be writing, until teardown. + /// completed save seals it; a save whose client cancelled remains + /// terminal because the controller may still commit the snapshot. #[test] fn save_holds_the_gate_until_the_controller_replies() { DefaultPool::run_with(async |driver| { @@ -3751,7 +3786,7 @@ mod tests { recv }; - // Completed save: the gate is released. + // Completed save: the gate is sealed and the VM is terminal. let mut svc = service(driver.clone(), None); let mut controller = with_controller(&mut svc); let (result, ()) = futures::join!(svc.save_vm(request("completed")), async { @@ -3762,13 +3797,42 @@ mod tests { response.complete(Ok(Guid::new_random())); }); result.unwrap(); - drop( + let status = grpc_error( svc.operation_gate .try_acquire(VmOperation::Topology) - .expect("a completed save releases the gate"), + .err() + .expect("a completed save seals the gate"), ); + assert_eq!(status.code, i32::from(Code::FailedPrecondition)); + assert!(matches!( + svc.lifecycle, + VmLifecycle::Halted(ref reason) if reason == "snapshot saved" + )); + let properties = svc.build_properties(); + assert_eq!(properties.state, vmservice::VmState::Halted as i32); + assert_eq!(properties.halt_reason.as_deref(), Some("snapshot saved")); + let (response, result) = mesh::oneshot(); + assert!(matches!( + svc.handle( + mesh::CancelContext::new(), + vmservice::Vm::WaitVm((), response), + ) + .await, + HandleAction::None + )); + result.await.unwrap().unwrap(); + for operation in [ + svc.pause_vm().await, + svc.resume_vm().await, + svc.teardown_vm().await, + svc.create_vm(Default::default()).await, + svc.restore_vm(Default::default()).await.map(drop), + ] { + let status = grpc_error(operation.expect_err("operation must remain terminal")); + assert_eq!(status.code, i32::from(Code::FailedPrecondition)); + } - // Cancelled save: the gate stays held until teardown. + // Cancelled save: the gate stays held and the service stays terminal. let mut svc = service(driver.clone(), None); let mut controller = with_controller(&mut svc); let rpc = match futures::future::select( @@ -3805,15 +3869,26 @@ mod tests { ); let (_dir, response) = rpc.split(); response.complete(Ok(Guid::new_random())); - svc.teardown_vm().await.unwrap(); - drop( - svc.operation_gate - .try_acquire(VmOperation::Topology) - .expect("teardown releases the gate"), + let status = grpc_error( + svc.teardown_vm() + .await + .expect_err("teardown is not allowed after save"), ); + assert_eq!(status.code, i32::from(Code::FailedPrecondition)); + + let (response, result) = mesh::oneshot(); + assert!(matches!( + svc.handle( + mesh::CancelContext::new(), + vmservice::Vm::Quit((), response), + ) + .await, + HandleAction::Quit + )); + result.await.unwrap().unwrap(); - // Cancelled save, then the worker stops: the gate is released, so - // a later VM isn't blocked. + // Cancelled save, then the worker stops: the service remains + // terminal, so a later VM cannot reuse the process. let mut svc = service(driver, None); let mut controller = with_controller(&mut svc); drop( @@ -3825,11 +3900,14 @@ mod tests { ); assert!(svc.save_guard.is_some()); svc.handle_controller_event(VmControllerEvent::WorkerStopped { error: None }); - drop( + let status = grpc_error( svc.operation_gate .try_acquire(VmOperation::Topology) - .expect("a stopped worker releases the gate"), + .err() + .expect("a stopped worker remains terminal"), ); + assert_eq!(status.code, i32::from(Code::FailedPrecondition)); + assert!(matches!(svc.lifecycle, VmLifecycle::Halted(_))); }); } diff --git a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs index abe8cf591f0..cc26c1638e1 100644 --- a/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs +++ b/openvmm/openvmm_entry/src/ttrpc/operation_gate.rs @@ -13,8 +13,9 @@ //! //! The gate must be acquired before any side effect of the operation, and is //! released when its guard drops, so completion, error, and cancellation all -//! release it. The state is behind `Arc>` because guards move into -//! spawned operation futures, which must be `Send`. +//! release it. A committed SaveVM seals the gate permanently; the process must +//! be quit and recreated. The state is behind `Arc>` because guards +//! move into spawned operation futures, which must be `Send`. use anyhow::Context; use mesh_rpc::service::Code; @@ -56,6 +57,9 @@ enum State { /// `n` topology operations in flight. Shared(u32), Exclusive(VmOperation), + /// The VM is terminal after a committed SaveVM. Only service-level + /// read/wait operations and Quit are allowed. + Sealed, } pub(crate) struct VmOperationGate { @@ -83,6 +87,11 @@ impl VmOperationGate { /// shared-operation count would overflow. pub(crate) fn try_acquire(&self, operation: VmOperation) -> anyhow::Result { let mut state = self.state.lock(); + if *state == State::Sealed { + return Err(anyhow::Error::new(Code::FailedPrecondition)).context( + "VM is sealed after SaveVM; only PropertiesVM, WaitVM, and Quit are allowed", + ); + } let held = match (*state, operation.is_shared()) { (State::Idle, true) => { *state = State::Shared(1); @@ -106,6 +115,7 @@ impl VmOperationGate { } (State::Shared(_), false) => Some(VmOperation::Topology), (State::Exclusive(held), _) => Some(held), + (State::Sealed, _) => unreachable!("sealed state handled above"), }; if let Some(held) = held { return Err(anyhow::Error::new(Code::Aborted)).with_context(|| { @@ -121,6 +131,17 @@ impl VmOperationGate { operation, }) } + + /// Permanently rejects further gated VM mutations. The caller must release + /// the current guard before sealing. + pub(crate) fn seal(&self) { + let mut state = self.state.lock(); + assert!( + matches!(*state, State::Idle | State::Sealed), + "cannot seal while an operation is in flight" + ); + *state = State::Sealed; + } } impl Drop for VmOperationGuard { @@ -128,6 +149,7 @@ impl Drop for VmOperationGuard { let mut state = self.state.lock(); *state = match *state { State::Shared(n) if self.operation.is_shared() && n > 1 => State::Shared(n - 1), + State::Sealed => State::Sealed, _ => State::Idle, }; } @@ -198,4 +220,21 @@ mod tests { drop(fut); assert!(gate.try_acquire(VmOperation::Pause).is_ok()); } + + #[test] + fn sealed_gate_rejects_all_mutations_with_failed_precondition() { + let gate = VmOperationGate::default(); + gate.seal(); + for op in [ + VmOperation::Pause, + VmOperation::Resume, + VmOperation::Save, + VmOperation::Topology, + ] { + let status = grpc_error(gate.try_acquire(op).err().unwrap()); + assert_eq!(status.code, i32::from(Code::FailedPrecondition)); + assert!(status.message.contains("sealed after SaveVM")); + } + gate.seal(); + } } From d98dc179544bef305d6ae0229f7feffc93b7ca7c Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Sun, 22 Nov 2026 11:54:07 +0530 Subject: [PATCH 14/17] vmm_tests: use Quit after SaveVM --- vmm_tests/vmm_tests/tests/tests/ttrpc.rs | 82 ++++++++++++++---------- 1 file changed, 49 insertions(+), 33 deletions(-) diff --git a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs index 586620372c1..e80a6e0d9f2 100644 --- a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs +++ b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs @@ -676,15 +676,17 @@ async fn test_ttrpc_interface( petri_artifacts_common::tags::MachineArch::Aarch64 => "ttyAMA0", }; - let (mut child, client, stderr_task) = + let (mut child, mut client, mut stderr_task) = launch_openvmm(&driver, ¶ms, &openvmm, &socket_path, &pidfile_path).await?; - let query_props = || { - client.call().start( - vmservice::Vm::PropertiesVm, - vmservice::PropertiesVmRequest { types: Vec::new() }, - ) - }; + macro_rules! query_props { + () => { + client.call().start( + vmservice::Vm::PropertiesVm, + vmservice::PropertiesVmRequest { types: Vec::new() }, + ) + }; + } let caps = client .call() @@ -711,7 +713,7 @@ async fn test_ttrpc_interface( "only Linux direct boot is supported" ); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Uninitialized as i32, @@ -729,7 +731,7 @@ async fn test_ttrpc_interface( ) .await .unwrap_err(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Uninitialized as i32, @@ -1185,7 +1187,7 @@ async fn test_ttrpc_interface( ); } - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Paused as i32, @@ -1492,7 +1494,7 @@ async fn test_ttrpc_interface( .await .unwrap(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Running as i32, @@ -1550,7 +1552,7 @@ async fn test_ttrpc_interface( waiter.await.unwrap(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Halted as i32, @@ -1589,7 +1591,7 @@ async fn test_ttrpc_interface( .await .context("timed out reading virtio console output")??; - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Uninitialized as i32, @@ -1616,7 +1618,7 @@ async fn test_ttrpc_interface( .await .unwrap(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Running as i32, @@ -1665,7 +1667,7 @@ async fn test_ttrpc_interface( .start(vmservice::Vm::PauseVm, ()) .await .unwrap(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Paused as i32, @@ -1676,7 +1678,7 @@ async fn test_ttrpc_interface( .start(vmservice::Vm::ResumeVm, ()) .await .unwrap(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Running as i32, @@ -1706,7 +1708,7 @@ async fn test_ttrpc_interface( std::fs::read_dir(&snapshot_path).unwrap().next().is_none(), "a rejected SaveVm must not write into the existing directory" ); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Running as i32, @@ -1738,11 +1740,16 @@ async fn test_ttrpc_interface( "SaveVm should create {name}" ); } - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, - vmservice::VmState::Paused as i32, - "SaveVm should leave the VM paused" + vmservice::VmState::Halted as i32, + "SaveVm should leave the VM terminal" + ); + assert_eq!( + props.halt_reason.as_deref(), + Some("snapshot saved"), + "SaveVm should report why the VM is terminal" ); client .call() @@ -1779,9 +1786,8 @@ async fn test_ttrpc_interface( .await .unwrap_err(); - // The VM is paused after the save, so a port change fails fast - // instead of waiting on the stopped NIC, and can't block the - // teardown below. + // The VM is terminal after the save, so changes fail at the + // lifecycle gate rather than waiting on device state. let err = client .call() .start( @@ -1801,13 +1807,20 @@ async fn test_ttrpc_interface( err.message ); - client + let err = client .call() .start(vmservice::Vm::TeardownVm, ()) .await - .unwrap(); - + .unwrap_err(); + assert_eq!(err.code, mesh_rpc::service::Code::FailedPrecondition as i32); + client.call().start(vmservice::Vm::Quit, ()).await.unwrap(); waiter.await.unwrap_err(); + assert!(child.wait().await?.success()); + stderr_task + .await + .context("failed to drain OpenVMM stderr after saved-source Quit")?; + (child, client, stderr_task) = + launch_openvmm(&driver, ¶ms, &openvmm, &socket_path, &pidfile_path).await?; let err = client .call() @@ -1868,7 +1881,7 @@ async fn test_ttrpc_interface( restore_result.snapshot_id, snapshot_id, "RestoreVm should return the snapshot ID from the manifest" ); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Paused as i32, @@ -1894,7 +1907,7 @@ async fn test_ttrpc_interface( .start(vmservice::Vm::ResumeVm, ()) .await .unwrap(); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Running as i32, @@ -1926,12 +1939,15 @@ async fn test_ttrpc_interface( second_snapshot_id, snapshot_id, "each SaveVm should generate a new snapshot ID" ); - client - .call() - .start(vmservice::Vm::TeardownVm, ()) + client.call().start(vmservice::Vm::Quit, ()).await.unwrap(); + assert!(child.wait().await?.success()); + stderr_task .await - .unwrap(); + .context("failed to drain OpenVMM stderr after second SaveVm Quit")?; drop(shell); + (child, client, stderr_task) = + launch_openvmm(&driver, ¶ms, &openvmm, &socket_path, &pidfile_path) + .await?; let restore_result = client .call() @@ -1947,7 +1963,7 @@ async fn test_ttrpc_interface( .await .unwrap(); assert_eq!(restore_result.snapshot_id, second_snapshot_id); - let props = query_props().await.unwrap(); + let props = query_props!().await.unwrap(); assert_eq!( props.state, vmservice::VmState::Running as i32, From 078df413b3e0a4998d57f00b93acf20d77bfb20b Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Sun, 22 Nov 2026 11:57:57 +0530 Subject: [PATCH 15/17] vmm_tests: tolerate Quit reply loss in lifecycle test --- vmm_tests/vmm_tests/tests/tests/ttrpc.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs index e80a6e0d9f2..158c4eda86b 100644 --- a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs +++ b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs @@ -1813,7 +1813,7 @@ async fn test_ttrpc_interface( .await .unwrap_err(); assert_eq!(err.code, mesh_rpc::service::Code::FailedPrecondition as i32); - client.call().start(vmservice::Vm::Quit, ()).await.unwrap(); + let _ = client.call().start(vmservice::Vm::Quit, ()).await; waiter.await.unwrap_err(); assert!(child.wait().await?.success()); stderr_task @@ -1939,7 +1939,7 @@ async fn test_ttrpc_interface( second_snapshot_id, snapshot_id, "each SaveVm should generate a new snapshot ID" ); - client.call().start(vmservice::Vm::Quit, ()).await.unwrap(); + let _ = client.call().start(vmservice::Vm::Quit, ()).await; assert!(child.wait().await?.success()); stderr_task .await From 10346bf5063b8a8d8bbe803643f34cac9362d9f9 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Mon, 23 Nov 2026 23:45:47 +0530 Subject: [PATCH 16/17] openvmm_entry: complete terminal SaveVM waiters --- .../src/reference/openvmm/management/grpc.md | 4 ++-- openvmm/openvmm_entry/src/ttrpc/mod.rs | 22 ++++++++++++++++++- .../src/vmservice.proto | 5 +++-- vmm_tests/vmm_tests/tests/tests/ttrpc.rs | 4 ++-- 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/Guide/src/reference/openvmm/management/grpc.md b/Guide/src/reference/openvmm/management/grpc.md index 48629768a73..8b837e92f34 100644 --- a/Guide/src/reference/openvmm/management/grpc.md +++ b/Guide/src/reference/openvmm/management/grpc.md @@ -173,8 +173,8 @@ flight, rather than queuing it. - A client that cancels or disconnects does not end the operation early. If a `SaveVM` client cancels, the save may still be writing the snapshot, so the service remains terminal. Device and resource changes and lifecycle - operations return `FAILED_PRECONDITION`; the client must send `Quit` or - wait for the VM worker to stop. + operations return `FAILED_PRECONDITION`. The client must send `Quit` and + wait for process exit, even if the VM worker has already stopped. - Once `SaveVM` commits, the VM operation gate is sealed. This prevents a caller from accidentally resuming, mutating, tearing down, or recreating the saved VM in the same process. diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 3fca62a5e7c..6471abea835 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -607,6 +607,12 @@ impl VmService { Ok(()) } + fn complete_wait_vm(&mut self) { + if let Some((_, response)) = self.wait_vm_response.take() { + response.send(Ok(())); + } + } + /// Like [`Self::start_rpc`], but admits the operation through the /// VM-mutation gate first. `build` runs only after admission, so a rejected /// operation has no side effects, and the gate is held until the operation @@ -1033,6 +1039,9 @@ impl VmService { .await .map_err(anyhow::Error::from) .and_then(|r| r); + if r.is_err() && self.snapshot_saved { + self.complete_wait_vm(); + } response.send(map_grpc(r)); } vmservice::Vm::RestoreVm(request, response) => { @@ -2069,6 +2078,7 @@ impl VmService { Ok(snapshot_id) => { self.operation_gate.seal(); self.lifecycle = VmLifecycle::Halted("snapshot saved".into()); + self.complete_wait_vm(); Ok(vmservice::SaveVmResponse { snapshot_id: snapshot_id.to_string(), }) @@ -2104,7 +2114,9 @@ impl VmService { } else { tracing::info!("VM worker stopped"); } - if let Some((_, response)) = self.wait_vm_response.take() { + if self.snapshot_saved { + self.complete_wait_vm(); + } else if let Some((_, response)) = self.wait_vm_response.take() { let status = if let Some(err) = &error { grpc_error(anyhow!("VM worker stopped: {}", err)) } else { @@ -3913,6 +3925,8 @@ mod tests { // Completed save: the gate is sealed and the VM is terminal. let mut svc = service(driver.clone(), None); let mut controller = with_controller(&mut svc); + let (wait_response, wait_result) = mesh::oneshot(); + svc.wait_vm_response = Some((mesh::CancelContext::new(), wait_response)); let (result, ()) = futures::join!(svc.save_vm(request("completed")), async { let Some(VmControllerRpc::SaveSnapshot(rpc)) = controller.next().await else { panic!("expected a SaveSnapshot request"); @@ -3921,6 +3935,8 @@ mod tests { response.complete(Ok(Guid::new_random())); }); result.unwrap(); + wait_result.await.unwrap().unwrap(); + assert!(svc.wait_vm_response.is_none()); let status = grpc_error( svc.operation_gate .try_acquire(VmOperation::Topology) @@ -4015,6 +4031,8 @@ mod tests { // terminal, so a later VM cannot reuse the process. let mut svc = service(driver, None); let mut controller = with_controller(&mut svc); + let (wait_response, wait_result) = mesh::oneshot(); + svc.wait_vm_response = Some((mesh::CancelContext::new(), wait_response)); drop( futures::future::select( std::pin::pin!(svc.save_vm(request("worker-stopped"))), @@ -4024,6 +4042,8 @@ mod tests { ); assert!(svc.save_guard.is_some()); svc.handle_controller_event(VmControllerEvent::WorkerStopped { error: None }); + wait_result.await.unwrap().unwrap(); + assert!(svc.wait_vm_response.is_none()); let status = grpc_error( svc.operation_gate .try_acquire(VmOperation::Topology) diff --git a/openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto b/openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto index 17e60f892ec..c9c6df4f630 100644 --- a/openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto +++ b/openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto @@ -31,8 +31,9 @@ service VM { // a new snapshot directory and returns a unique snapshot ID, which is also // stored in the snapshot manifest. The current implementation hard-links // the guest memory backing file into the snapshot, so after a successful - // save the VM can't be resumed and should be torn down. Cancelling the - // call only stops the caller from waiting; the save may still complete. + // save the VM is terminal and cannot be resumed or reused. The caller must + // send Quit and wait for process exit. Cancelling the call only stops the + // caller from waiting; the save may still commit and requires Quit too. rpc SaveVM(SaveVMRequest) returns (SaveVMResponse); // RestoreVM creates a VM from a snapshot directory and the supplied device diff --git a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs index 158c4eda86b..9b80fed5eed 100644 --- a/vmm_tests/vmm_tests/tests/tests/ttrpc.rs +++ b/vmm_tests/vmm_tests/tests/tests/ttrpc.rs @@ -1803,7 +1803,7 @@ async fn test_ttrpc_interface( assert_eq!( err.code, mesh_rpc::service::Code::FailedPrecondition as i32, - "consomme port change while paused after SaveVm: {}", + "consomme port change after terminal SaveVm: {}", err.message ); @@ -1814,7 +1814,7 @@ async fn test_ttrpc_interface( .unwrap_err(); assert_eq!(err.code, mesh_rpc::service::Code::FailedPrecondition as i32); let _ = client.call().start(vmservice::Vm::Quit, ()).await; - waiter.await.unwrap_err(); + waiter.await.unwrap(); assert!(child.wait().await?.success()); stderr_task .await From aec0ff4d39b46e3877465bedf5fbd49be5fd0103 Mon Sep 17 00:00:00 2001 From: Manish Ranjan Mahanta Date: Tue, 24 Nov 2026 00:03:23 +0530 Subject: [PATCH 17/17] openvmm_entry: complete late terminal WaitVM --- openvmm/openvmm_entry/src/ttrpc/mod.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/openvmm/openvmm_entry/src/ttrpc/mod.rs b/openvmm/openvmm_entry/src/ttrpc/mod.rs index 6471abea835..863c4b4a1c1 100644 --- a/openvmm/openvmm_entry/src/ttrpc/mod.rs +++ b/openvmm/openvmm_entry/src/ttrpc/mod.rs @@ -1071,12 +1071,12 @@ impl VmService { self.start_rpc(response, r); } vmservice::Vm::WaitVm((), response) => { - if self.vm.is_none() { + if matches!(self.lifecycle, VmLifecycle::Halted(_)) { + response.send(Ok(())); + } else if self.vm.is_none() { response.send(Err(grpc_error(anyhow!("VM not created yet")))); } else if self.wait_vm_response.is_some() { response.send(Err(grpc_error(anyhow!("wait VM already in flight")))); - } else if matches!(self.lifecycle, VmLifecycle::Halted(_)) { - response.send(Ok(())); } else { self.wait_vm_response = Some((ctx.clone(), response)); } @@ -4052,6 +4052,16 @@ mod tests { ); assert_eq!(status.code, i32::from(Code::FailedPrecondition)); assert!(matches!(svc.lifecycle, VmLifecycle::Halted(_))); + let (response, result) = mesh::oneshot(); + assert!(matches!( + svc.handle( + mesh::CancelContext::new(), + vmservice::Vm::WaitVm((), response), + ) + .await, + HandleAction::None + )); + result.await.unwrap().unwrap(); }); }