mirror of
https://github.com/NVIDIA/OpenShell.git
synced 2026-12-06 04:56:33 +08:00
perf(sandbox): block in poll(2) while the boundary is idle (#6148)
* 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 <dgude@nvidia.com> * perf(sandbox): drain stale boundary wakeups on handler install Signed-off-by: divesh <dgude@nvidia.com> * perf(sandbox): consume boundary wakeups after each poll Signed-off-by: divesh <dgude@nvidia.com> --------- Signed-off-by: Divesh <dgude@nvidia.com> Signed-off-by: divesh <dgude@nvidia.com>
This commit is contained in:
@@ -237,10 +237,62 @@ 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<std::os::fd::RawFd>, timeout: Duration) {
|
||||
let wake = BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire);
|
||||
if wake < 0 {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
return;
|
||||
}
|
||||
wait_for_wake(wake, readable, timeout);
|
||||
}
|
||||
|
||||
/// Block until `wake` or `readable` has input, or `timeout` elapses.
|
||||
/// A wakeup is consumed: a forked child can write the pipe between fork
|
||||
/// and exec without setting this process's termination flag.
|
||||
fn wait_for_wake(
|
||||
wake: std::os::fd::RawFd,
|
||||
readable: Option<std::os::fd::RawFd>,
|
||||
timeout: Duration,
|
||||
) {
|
||||
// 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.
|
||||
let ready = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };
|
||||
if ready > 0 && fds[0].revents & libc::POLLIN != 0 {
|
||||
let mut buf = [0u8; 64];
|
||||
// SAFETY: `buf` is valid for `buf.len()` bytes and the descriptor
|
||||
// is nonblocking, so the loop ends once it is empty.
|
||||
while unsafe { libc::read(wake, buf.as_mut_ptr().cast(), buf.len()) } > 0 {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_boundary(
|
||||
@@ -332,9 +384,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(),
|
||||
@@ -344,9 +414,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}"))?;
|
||||
}
|
||||
@@ -702,7 +773,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 => {}
|
||||
@@ -746,7 +817,7 @@ mod linux {
|
||||
dialer.abort();
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
wait_for_termination_signal(None, Duration::from_secs(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4855,6 +4926,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<Self> {
|
||||
match config {
|
||||
BoundaryListenerConfig::Vsock { control_port, tls } => {
|
||||
@@ -5817,6 +5896,34 @@ mod linux {
|
||||
assert_eq!(boundary_termination_signal_name(0), "unknown signal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_wait_wakes_for_a_connection_or_a_wakeup_and_consumes_the_wakeup() {
|
||||
// A private wake descriptor: other tests write the process-wide pipe.
|
||||
let (wake, mut waker) = std::os::unix::net::UnixStream::pair().unwrap();
|
||||
wake.set_nonblocking(true).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 idle_wait = |timeout| {
|
||||
let started = std::time::Instant::now();
|
||||
wait_for_wake(wake.as_raw_fd(), Some(listener.as_raw_fd()), timeout);
|
||||
started.elapsed()
|
||||
};
|
||||
|
||||
assert!(idle_wait(Duration::from_millis(50)) >= Duration::from_millis(50));
|
||||
|
||||
waker.write_all(&[1; 3]).unwrap();
|
||||
assert!(idle_wait(Duration::from_secs(30)) < Duration::from_secs(5));
|
||||
assert!(
|
||||
idle_wait(Duration::from_millis(50)) >= Duration::from_millis(50),
|
||||
"a consumed wakeup must not wake the next wait"
|
||||
);
|
||||
|
||||
let _client = std::os::unix::net::UnixStream::connect(&path).unwrap();
|
||||
assert!(idle_wait(Duration::from_secs(30)) < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supplementary_group_measurement_rejects_unexpected_groups_by_default() {
|
||||
assert!(!supplementary_groups_match(&[44, 992], &[], false));
|
||||
|
||||
Reference in New Issue
Block a user