From 64265a556e936cae06e2a9514451fbbe11ebcd71 Mon Sep 17 00:00:00 2001 From: Divesh Date: Sun, 29 Nov 2026 12:21:32 -0800 Subject: [PATCH 1/2] perf(sandbox): block in poll(2) while the boundary is idle - Replace the 10 ms sleep loops with poll(2) on a self-pipe. - Signal handler writes to the pipe to wake the wait. - Listener mode also wakes on a pending connection. - Idle microVM cost: ~2.5% to ~0.2% of a core. Closes #6071 Signed-off-by: Divesh --- .../openshell-sandbox/src/boundary_server.rs | 90 +++++++++++++++++-- 1 file changed, 85 insertions(+), 5 deletions(-) diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 7a74565139..11ca2e5d02 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -237,10 +237,45 @@ mod linux { } static BOUNDARY_TERMINATION_REQUESTED: AtomicBool = AtomicBool::new(false); static BOUNDARY_TERMINATION_SIGNAL: AtomicI32 = AtomicI32::new(0); + // Self-pipe that wakes `wait_for_termination_signal`, so an idle boundary + // sleeps in the kernel instead of polling the termination flag. In a + // microVM every timer wakeup is a VM exit. + static BOUNDARY_TERMINATION_WAKE_READ: AtomicI32 = AtomicI32::new(-1); + static BOUNDARY_TERMINATION_WAKE_WRITE: AtomicI32 = AtomicI32::new(-1); extern "C" fn request_boundary_termination(signal: libc::c_int) { BOUNDARY_TERMINATION_SIGNAL.store(signal, Ordering::Release); BOUNDARY_TERMINATION_REQUESTED.store(true, Ordering::Release); + let fd = BOUNDARY_TERMINATION_WAKE_WRITE.load(Ordering::Acquire); + if fd >= 0 { + // SAFETY: errno access and write(2) are async-signal-safe. The pipe + // is nonblocking; when it is full a wakeup is already pending. + unsafe { + let errno = *libc::__errno_location(); + let byte = 1u8; + let _ = libc::write(fd, std::ptr::addr_of!(byte).cast(), 1); + *libc::__errno_location() = errno; + } + } + } + + /// Block until a termination signal is delivered, `readable` (when given) + /// has input, or `timeout` elapses. + fn wait_for_termination_signal(readable: Option, timeout: Duration) { + let wake = BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire); + if wake < 0 { + std::thread::sleep(Duration::from_millis(10)); + return; + } + // poll(2) ignores entries with a negative descriptor. + let mut fds = [wake, readable.unwrap_or(-1)].map(|fd| libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }); + let timeout = libc::c_int::try_from(timeout.as_millis()).unwrap_or(libc::c_int::MAX); + // SAFETY: `fds` holds two valid pollfds for the duration of the call. + unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) }; } pub fn run_boundary( @@ -331,9 +366,27 @@ mod linux { .map_err(|error| format!("disable sandbox core dumps: {error}")) } + fn create_termination_wake_pipe() -> Result<(), String> { + if BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire) >= 0 { + return Ok(()); + } + let mut fds = [-1; 2]; + // SAFETY: `fds` has room for the two descriptors pipe2 returns. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) } != 0 { + return Err(format!( + "create boundary termination pipe: {}", + io::Error::last_os_error() + )); + } + BOUNDARY_TERMINATION_WAKE_WRITE.store(fds[1], Ordering::Release); + BOUNDARY_TERMINATION_WAKE_READ.store(fds[0], Ordering::Release); + Ok(()) + } + fn install_boundary_signal_handlers() -> Result<(), String> { BOUNDARY_TERMINATION_REQUESTED.store(false, Ordering::Release); BOUNDARY_TERMINATION_SIGNAL.store(0, Ordering::Release); + create_termination_wake_pipe()?; let action = nix::sys::signal::SigAction::new( nix::sys::signal::SigHandler::Handler(request_boundary_termination), nix::sys::signal::SaFlags::empty(), @@ -343,9 +396,10 @@ mod linux { nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGINT, ] { - // SAFETY: the installed handler only performs a lock-free atomic - // store, which is async-signal-safe, and remains valid for the - // lifetime of the boundary process. + // SAFETY: the installed handler only performs lock-free atomic + // operations and a write(2) to a nonblocking pipe, which are + // async-signal-safe, and remains valid for the lifetime of the + // boundary process. unsafe { nix::sys::signal::sigaction(signal, &action) } .map_err(|error| format!("install boundary {signal:?} handler: {error}"))?; } @@ -701,7 +755,7 @@ mod linux { }); } Err(error) if error.kind() == io::ErrorKind::WouldBlock => { - std::thread::sleep(Duration::from_millis(10)); + wait_for_termination_signal(Some(listener.as_raw_fd()), Duration::from_secs(1)); } Err(error) => match control_accept_error_action(&error) { ControlAcceptErrorAction::Continue => {} @@ -745,7 +799,7 @@ mod linux { dialer.abort(); return result; } - std::thread::sleep(Duration::from_millis(10)); + wait_for_termination_signal(None, Duration::from_secs(1)); } } @@ -4827,6 +4881,14 @@ mod linux { } impl ControlListener { + fn as_raw_fd(&self) -> std::os::fd::RawFd { + match self { + Self::Vsock { listener, .. } => listener.as_raw_fd(), + Self::Unix { listener, .. } => listener.as_raw_fd(), + Self::Tcp { listener, .. } => listener.as_raw_fd(), + } + } + fn bind(config: &BoundaryListenerConfig) -> io::Result { match config { BoundaryListenerConfig::Vsock { control_port, tls } => { @@ -5789,6 +5851,24 @@ mod linux { assert_eq!(boundary_termination_signal_name(0), "unknown signal"); } + #[test] + fn an_idle_listener_wait_wakes_for_a_pending_connection() { + create_termination_wake_pipe().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("control.sock"); + let listener = std::os::unix::net::UnixListener::bind(&path).unwrap(); + listener.set_nonblocking(true).unwrap(); + + let started = std::time::Instant::now(); + wait_for_termination_signal(Some(listener.as_raw_fd()), Duration::from_millis(50)); + assert!(started.elapsed() >= Duration::from_millis(50)); + + let _client = std::os::unix::net::UnixStream::connect(&path).unwrap(); + let started = std::time::Instant::now(); + wait_for_termination_signal(Some(listener.as_raw_fd()), Duration::from_secs(30)); + assert!(started.elapsed() < Duration::from_secs(5)); + } + #[test] fn supplementary_group_measurement_rejects_unexpected_groups_by_default() { assert!(!supplementary_groups_match(&[44, 992], &[], false)); From ce641f7feea737d1379ace43e55f3022907e0a22 Mon Sep 17 00:00:00 2001 From: divesh Date: Tue, 1 Dec 2026 14:10:59 -0800 Subject: [PATCH 2/2] perf(sandbox): drain stale boundary wakeups on handler install Signed-off-by: divesh --- crates/openshell-sandbox/src/boundary_server.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 11ca2e5d02..8b57e380ae 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -367,7 +367,13 @@ mod linux { } fn create_termination_wake_pipe() -> Result<(), String> { - if BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire) >= 0 { + let wake = BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire); + if wake >= 0 { + // A stale wakeup would turn every idle wait into a busy loop. + let mut buf = [0u8; 64]; + // SAFETY: `buf` is valid for `buf.len()` bytes and the pipe is + // nonblocking, so the loop ends once it is empty. + while unsafe { libc::read(wake, buf.as_mut_ptr().cast(), buf.len()) } > 0 {} return Ok(()); } let mut fds = [-1; 2];