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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions src/jsc/PosixSignalHandle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ impl PosixSignalHandle {
Box::new(init)
}

/// Returns `false` if the ring is full. The caller wakes the loop on `true`.
/// Never loses a signal: a full ring coalesces it into a pending bit.
#[allow(dead_code)]
pub(crate) fn enqueue(&self, signal: u8) -> bool {
self.ring.enqueue(signal)
pub(crate) fn enqueue(&self, signal: u8) {
self.ring.enqueue(signal);
}

/// Drain as many signals as possible and enqueue them as tasks in the event loop.
Expand Down Expand Up @@ -76,11 +76,10 @@ extern "C" fn Bun__onPosixSignal(number: i32) {
let Some(signal) = u8::try_from(number).ok().filter(|&s| s != 0) else {
return;
};
if handler.enqueue(signal) {
// SAFETY: same process-lifetime event loop as above; `wakeup`
// is one async-signal-safe write to the loop's wakeup fd.
unsafe { (*(*vm).event_loop()).wakeup() };
}
handler.enqueue(signal);
// SAFETY: same process-lifetime event loop as above; `wakeup`
// is one async-signal-safe write to the loop's wakeup fd.
unsafe { (*(*vm).event_loop()).wakeup() };
}
}
#[cfg(not(unix))]
Expand Down
111 changes: 91 additions & 20 deletions src/threading/signal_ring.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
//! Lock-free ring of pending POSIX signal numbers.

use core::sync::atomic::{AtomicU8, AtomicU32, Ordering};
use core::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};

/// Multi-producer, single-consumer ring of nonzero `u8` values. `enqueue` is
/// atomics only, so signal handlers on any thread may run it at once or nested.
/// `CAPACITY` is a power of two up to 32768: `u16` indices, `tail - head` fits.
/// A full ring records the signal in `overflow` instead of dropping it.
pub struct SignalRing<const CAPACITY: usize> {
/// 0 while free or claimed but not yet written (signal numbers start at 1).
slots: [AtomicU8; CAPACITY],
/// `head` (consumer) in the low half, `tail` (producer) in the high half,
/// so one load reads a consistent pair and one CAS claims against it.
state: AtomicU32,
/// Bit `n` set: signal `n` arrived while the ring was full.
overflow: [AtomicU64; 4],
}

#[inline]
const fn overflow_bit(signal: u8) -> (usize, u64) {
(signal as usize / 64, 1u64 << (signal % 64))
}

#[inline]
Expand Down Expand Up @@ -40,6 +48,7 @@ impl<const CAPACITY: usize> SignalRing<CAPACITY> {
Self {
slots: [const { AtomicU8::new(0) }; CAPACITY],
state: AtomicU32::new(0),
overflow: [const { AtomicU64::new(0) }; 4],
}
}

Expand All @@ -48,13 +57,16 @@ impl<const CAPACITY: usize> SignalRing<CAPACITY> {
&self.slots[index as usize % CAPACITY]
}

/// Producer side, any thread. Returns `false` when full. `signal` is never 0.
/// Producer side, any thread. `signal` is never 0. Returns `false` when the
/// ring was full and the signal went into `overflow`.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub fn enqueue(&self, signal: u8) -> bool {
debug_assert_ne!(signal, 0, "0 is the empty-slot sentinel");
let mut state = self.state.load(Ordering::Acquire);
loop {
let (head, tail) = unpack(state);
if usize::from(tail.wrapping_sub(head)) >= CAPACITY {
let (word, bit) = overflow_bit(signal);
self.overflow[word].fetch_or(bit, Ordering::Release);
return false;
}
match self.state.compare_exchange_weak(
Expand All @@ -72,15 +84,16 @@ impl<const CAPACITY: usize> SignalRing<CAPACITY> {
}
}

/// Consumer side, one thread only. Returns the oldest published signal.
/// Consumer side, one thread only. Returns the oldest published signal,
/// or an overflowed one once the ring is empty.
Comment thread
robobun marked this conversation as resolved.
Resolved
/// `None` means empty, or that the oldest claimed slot is still 0 because
/// its producer has not stored yet: come back after that producer's
/// wakeup, nothing behind it is skipped.
pub fn dequeue(&self) -> Option<u8> {
let mut state = self.state.load(Ordering::Acquire);
let (head, tail) = unpack(state);
if head == tail {
return None;
return self.take_overflow();
}

let signal = self.slot(head).swap(0, Ordering::AcqRel);
Expand All @@ -103,6 +116,21 @@ impl<const CAPACITY: usize> SignalRing<CAPACITY> {
}
}

/// Clears and returns the lowest overflowed signal number, if any.
fn take_overflow(&self) -> Option<u8> {
for (index, word) in self.overflow.iter().enumerate() {
let bits = word.load(Ordering::Acquire);
if bits == 0 {
continue;
}
let bit = bits.trailing_zeros();
// Only this thread clears bits, so the bit is still set here.
word.fetch_and(!(1u64 << bit), Ordering::AcqRel);
return Some((index * 64 + bit as usize) as u8);
}
None
}

/// Starts both indices at `index`, to put the `u16` wrap within reach.
#[cfg(test)]
fn starting_at(index: u16) -> Self {
Expand All @@ -115,7 +143,7 @@ impl<const CAPACITY: usize> SignalRing<CAPACITY> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::{AtomicIsize, AtomicUsize};

// Miri interprets every atomic op, so the stress stays short there.
#[cfg(miri)]
Expand All @@ -129,30 +157,31 @@ mod tests {

struct Stress {
accepted: Vec<usize>,
coalesced: Vec<usize>,
dequeued: Vec<usize>,
rejected: usize,
zeros: usize,
unknown: usize,
}

/// Producers wait while `outstanding_limit` accepted entries are in the ring.
fn stress<const CAPACITY: usize>(
ring: &SignalRing<CAPACITY>,
outstanding_limit: usize,
outstanding_limit: isize,
) -> Stress {
let done = AtomicUsize::new(0);
let outstanding = AtomicUsize::new(0);
// Signed: an overflowed signal is counted out twice, once per side.
let outstanding = AtomicIsize::new(0);
let mut dequeued = vec![0usize; usize::from(PRODUCERS)];
let mut zeros = 0;
let mut unknown = 0;

let (accepted, rejected) = std::thread::scope(|scope| {
let (accepted, coalesced) = std::thread::scope(|scope| {
let workers: Vec<_> = (1..=PRODUCERS)
.map(|signal| {
let (done, outstanding) = (&done, &outstanding);
scope.spawn(move || {
let mut accepted = 0usize;
let mut rejected = 0usize;
let mut coalesced = 0usize;
while accepted < PER_PRODUCER {
if outstanding.load(Ordering::Acquire) >= outstanding_limit {
std::thread::yield_now();
Expand All @@ -163,12 +192,12 @@ mod tests {
accepted += 1;
} else {
outstanding.fetch_sub(1, Ordering::AcqRel);
rejected += 1;
coalesced += 1;
std::thread::yield_now();
}
}
done.fetch_add(1, Ordering::Release);
(accepted, rejected)
(accepted, coalesced)
})
})
.collect();
Expand All @@ -192,19 +221,19 @@ mod tests {
}

let mut accepted = Vec::new();
let mut rejected = 0;
let mut coalesced = Vec::new();
for worker in workers {
let (a, r) = worker.join().unwrap();
let (a, c) = worker.join().unwrap();
accepted.push(a);
rejected += r;
coalesced.push(c);
}
(accepted, rejected)
(accepted, coalesced)
});

Stress {
accepted,
coalesced,
dequeued,
rejected,
zeros,
unknown,
}
Expand All @@ -213,17 +242,28 @@ mod tests {
#[test]
fn concurrent_producers_deliver_every_accepted_signal_once() {
let ring = SignalRing::<64>::new();
let result = stress(&ring, usize::MAX);
let result = stress(&ring, isize::MAX);
assert_eq!((result.zeros, result.unknown), (0, 0));
assert_eq!(result.dequeued, result.accepted);
for i in 0..usize::from(PRODUCERS) {
let (accepted, coalesced, dequeued) =
(result.accepted[i], result.coalesced[i], result.dequeued[i]);
// Slots deliver once, overflows at least once and at most once each.
assert!(dequeued >= accepted, "{i}: {dequeued} < {accepted}");
assert!(
dequeued <= accepted + coalesced,
"{i}: {dequeued} > {accepted} + {coalesced}"
);
assert_eq!(dequeued > accepted, coalesced > 0, "{i}");
}
}

/// Fullness is judged on one consistent `(head, tail)` pair, never a stale one.
#[test]
fn never_rejects_below_capacity() {
let ring = SignalRing::<64>::new();
let result = stress(&ring, 32);
assert_eq!((result.zeros, result.unknown, result.rejected), (0, 0, 0));
assert_eq!((result.zeros, result.unknown), (0, 0));
assert_eq!(result.coalesced.iter().sum::<usize>(), 0);
assert_eq!(result.dequeued, result.accepted);
}

Expand All @@ -238,10 +278,41 @@ mod tests {
for i in 0..4u8 {
assert_eq!(ring.dequeue(), Some(round * 4 + i + 1));
}
assert_eq!(ring.dequeue(), Some(99), "overflow follows the ring");
assert_eq!(ring.dequeue(), None);
}
}

/// A storm that fills the ring delays other signals but never drops them.
#[test]
fn full_ring_coalesces_each_signal_into_one_delivery() {
let ring = SignalRing::<4>::new();
for _ in 0..4 {
assert!(ring.enqueue(10));
}
for _ in 0..100 {
assert!(!ring.enqueue(10));
}
assert!(!ring.enqueue(15));
assert!(!ring.enqueue(255));
assert!(!ring.enqueue(64));
assert!(!ring.enqueue(15));

for _ in 0..4 {
assert_eq!(ring.dequeue(), Some(10));
}
assert_eq!(ring.dequeue(), Some(10));
assert_eq!(ring.dequeue(), Some(15));
assert_eq!(ring.dequeue(), Some(64));
assert_eq!(ring.dequeue(), Some(255));
assert_eq!(ring.dequeue(), None);

// Room again: the next one takes a slot.
assert!(ring.enqueue(15));
assert_eq!(ring.dequeue(), Some(15));
assert_eq!(ring.dequeue(), None);
}

#[test]
fn stops_at_a_claimed_slot_until_it_is_written() {
let ring = SignalRing::<8>::new();
Expand Down
37 changes: 37 additions & 0 deletions test/js/node/process/process.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1336,6 +1336,43 @@ describe.concurrent(() => {
expect(await new Response(child.stdout).text()).toBe("PASS\n");
});

it.skipIf(isWindows)("a signal that arrives while the pending-signal ring is full is not lost", async () => {
// kill(2) to our own pid delivers the signal to the calling thread before
// the syscall returns, so every call lands in the ring (8192 slots) with
// no kernel coalescing, and nothing drains it until the script finishes.
await using child = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
let usr1 = 0;
process.on("SIGUSR1", () => { usr1++; });
process.on("SIGTERM", () => {
console.log("SIGTERM after " + usr1 + " SIGUSR1");
process.exit(0);
});
for (let i = 0; i < 10_000; i++) process.kill(process.pid, "SIGUSR1");
process.kill(process.pid, "SIGTERM");
// Only reached when SIGTERM was dropped: every queued signal is
// delivered on the first loop tick.
setTimeout(() => {
console.log("SIGTERM lost after " + usr1 + " SIGUSR1");
process.exit(1);
}, 3000);
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "inherit",
});
const [stdout, exitCode] = await Promise.all([child.stdout.text(), child.exited]);
const match = stdout.match(/^SIGTERM after (\d+) SIGUSR1\n$/);
expect(match, stdout).not.toBeNull();
// The ring was full: every slot, plus the one coalesced overflow delivery.
expect(Number(match[1])).toBeGreaterThanOrEqual(8192);
expect(exitCode).toBe(0);
});

it.serial("process.kill(2) works", async () => {
await using child = Bun.spawn({
cmd: [bunExe(), process_sleep, "1000000"],
Expand Down
Loading