Skip to content

Commit bfaed88

Browse files
authored
sidecar_client: leave VP stopped when the driver rejects a start (#5237)
`start_async` marked the VP running before the start ioctl and left it that way if the ioctl failed. The sidecar driver rejects a start in `sidecar_claim` before starting the CPU, so no completion ever arrives: a later `run` panicked on the "stopped" assertion and a `wait` would hang. The VP state is shared, so re-acquiring the VP accessor did not reset it. This change returns the VP to stopped when the start fails. It is still marked running before the ioctl, because a completion can arrive as soon as the CPU starts. To make this unit-testable, the state transition moves unchanged into `SidecarClientState::start_vp`, which `start_async` calls with the same ioctl. Test changes (the crate's first unit tests): - A rejected `run` through the real ioctl (`/dev/null` returns `ENOTTY`) leaves the VP stopped and reusable with a re-acquired accessor (failed before). - A rejected start leaves the VP stopped and can be retried (failed before). - The VP is marked running while the start request is issued.
1 parent 8d4e031 commit bfaed88

3 files changed

Lines changed: 146 additions & 11 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8185,6 +8185,7 @@ dependencies = [
81858185
"pal_async",
81868186
"parking_lot",
81878187
"sidecar_defs",
8188+
"test_with_tracing",
81888189
"thiserror 2.0.16",
81898190
"tracing",
81908191
"zerocopy",

‎openhcl/sidecar_client/Cargo.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,8 @@ fs-err.workspace = true
2020
libc.workspace = true
2121
nix = { workspace = true, features = ["ioctl"] }
2222

23+
[target.'cfg(target_os = "linux")'.dev-dependencies]
24+
test_with_tracing.workspace = true
25+
2326
[lints]
2427
workspace = true

‎openhcl/sidecar_client/src/lib.rs‎

Lines changed: 142 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,30 @@ struct SidecarClientState {
9494
vps: Vec<Mutex<VpState>>,
9595
}
9696

97+
impl SidecarClientState {
98+
/// Marks the VP at `index` as running, then starts it with `start`.
99+
///
100+
/// The VP must be marked running before it is started, because the
101+
/// completion reader expects a running VP as soon as the VP can complete.
102+
/// If `start` fails, the VP is left stopped so that it can be started
103+
/// again.
104+
fn start_vp(
105+
&self,
106+
index: usize,
107+
start: impl FnOnce() -> std::io::Result<()>,
108+
) -> Result<(), SidecarError> {
109+
let old = std::mem::replace(&mut *self.vps[index].lock(), VpState::Running(None));
110+
assert!(matches!(old, VpState::Stopped));
111+
if let Err(err) = start() {
112+
// The driver rejects a start before starting the CPU, so no
113+
// completion will arrive for it. Return the VP to stopped.
114+
*self.vps[index].lock() = VpState::Stopped;
115+
return Err(SidecarError::Io(err));
116+
}
117+
Ok(())
118+
}
119+
}
120+
97121
#[derive(Debug)]
98122
enum VpState {
99123
Stopped,
@@ -571,17 +595,13 @@ impl<'a> SidecarVp<'a> {
571595
}
572596

573597
fn start_async(&mut self) -> Result<(), SidecarError> {
574-
let old = std::mem::replace(
575-
&mut *self.node.state.vps[self.index].lock(),
576-
VpState::Running(None),
577-
);
578-
assert!(matches!(old, VpState::Stopped));
579-
// SAFETY: no safety requirements on this ioctl.
580-
unsafe {
581-
ioctl::mshv_vtl_sidecar_start(self.node.state.file.as_raw_fd(), self.cpu)
582-
.map_err(|err| SidecarError::Io(err.into()))?;
583-
}
584-
Ok(())
598+
let fd = self.node.state.file.as_raw_fd();
599+
let cpu = self.cpu;
600+
self.node.state.start_vp(self.index, || {
601+
// SAFETY: no safety requirements on this ioctl.
602+
unsafe { ioctl::mshv_vtl_sidecar_start(fd, cpu) }?;
603+
Ok(())
604+
})
585605
}
586606

587607
fn stop_async(&mut self) {
@@ -675,3 +695,114 @@ impl Drop for SidecarRun<'_, '_> {
675695
assert!(self.waited, "failed to stop vp");
676696
}
677697
}
698+
699+
#[cfg(test)]
700+
mod tests {
701+
use super::*;
702+
use pal_async::DefaultDriver;
703+
use pal_async::async_test;
704+
use pal_async::task::Spawn;
705+
use test_with_tracing::test;
706+
707+
/// A one-VP node backed by anonymous memory and `/dev/null`, which
708+
/// rejects every sidecar ioctl with `ENOTTY`.
709+
fn test_node(driver: &DefaultDriver) -> SidecarNode {
710+
let len = size_of::<VpSharedPages>();
711+
// SAFETY: an anonymous private mapping has no preconditions. The
712+
// result is checked below and unmapped by `Mapping::drop`.
713+
let ptr = unsafe {
714+
libc::mmap(
715+
std::ptr::null_mut(),
716+
len,
717+
libc::PROT_READ | libc::PROT_WRITE,
718+
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
719+
-1,
720+
0,
721+
)
722+
};
723+
assert_ne!(ptr, libc::MAP_FAILED);
724+
SidecarNode {
725+
mapping: Mapping(NonNull::new(ptr).unwrap(), len),
726+
per_cpu_shmem_size: len,
727+
cpus: 0..1,
728+
_task: driver.spawn("test-sidecar-wait", async {}),
729+
state: Arc::new(test_state()),
730+
in_use: vec![AtomicBool::new(false)],
731+
}
732+
}
733+
734+
// Test: Run a VP through the public API when the driver rejects the
735+
// start ioctl (ENOTTY from /dev/null), then run it again with a new
736+
// accessor.
737+
// Expected: Both runs return the driver error; the VP is left stopped
738+
// after each, so the retry does not panic.
739+
#[async_test]
740+
async fn rejected_run_leaves_vp_reusable(driver: DefaultDriver) {
741+
let node = test_node(&driver);
742+
743+
for attempt in 0..2 {
744+
let mut vp = node.vp(0).unwrap();
745+
let Err(err) = vp.run() else {
746+
panic!("run {attempt} unexpectedly started the VP");
747+
};
748+
assert!(
749+
matches!(&err, SidecarError::Io(e) if e.raw_os_error() == Some(libc::ENOTTY)),
750+
"unexpected error on run {attempt}: {err:?}"
751+
);
752+
assert!(
753+
matches!(*node.state.vps[0].lock(), VpState::Stopped),
754+
"rejected run {attempt} left the VP in state {:?}",
755+
*node.state.vps[0].lock()
756+
);
757+
}
758+
}
759+
760+
fn test_state() -> SidecarClientState {
761+
SidecarClientState {
762+
file: File::open("/dev/null").unwrap(),
763+
vps: vec![Mutex::new(VpState::Stopped)],
764+
}
765+
}
766+
767+
// Test: Start a VP whose start request is rejected (as the sidecar driver
768+
// does with EBUSY before starting the CPU), then start it again.
769+
// Expected: The rejected start returns the error and leaves the VP
770+
// stopped, so the second start succeeds instead of panicking.
771+
#[test]
772+
fn rejected_start_leaves_vp_stopped() {
773+
let state = test_state();
774+
775+
let err = state
776+
.start_vp(0, || Err(std::io::Error::from_raw_os_error(libc::EBUSY)))
777+
.unwrap_err();
778+
assert!(
779+
matches!(&err, SidecarError::Io(e) if e.raw_os_error() == Some(libc::EBUSY)),
780+
"unexpected error: {err:?}"
781+
);
782+
assert!(
783+
matches!(*state.vps[0].lock(), VpState::Stopped),
784+
"rejected start left the VP in state {:?}",
785+
*state.vps[0].lock()
786+
);
787+
788+
state.start_vp(0, || Ok(())).unwrap();
789+
assert!(matches!(*state.vps[0].lock(), VpState::Running(None)));
790+
}
791+
792+
// Test: Start a stopped VP successfully.
793+
// Expected: The VP is already marked running while the start request is
794+
// issued, so a completion that arrives immediately finds it running.
795+
#[test]
796+
fn successful_start_marks_vp_running_before_starting() {
797+
let state = test_state();
798+
799+
state
800+
.start_vp(0, || {
801+
assert!(matches!(*state.vps[0].lock(), VpState::Running(None)));
802+
Ok(())
803+
})
804+
.unwrap();
805+
806+
assert!(matches!(*state.vps[0].lock(), VpState::Running(None)));
807+
}
808+
}

0 commit comments

Comments
 (0)