fix(cuda-driver): store-buffering races in the expert stager stop and MMQ host-stage finish, bound host-stage wait

stop/finish stored 'head' then loaded 'active' while a worker raised 'active' then claimed from 'head'; on x86 the
fence could return while a worker still copied from a source the caller then released. SeqCst on the four accesses.
HostStage::finish also let a helper waiting on 'released' overwrite a ring buffer still being read (re-check head after
the wait), and wait() now refuses a length beyond the bytes the job copied (page-locked buffers are uninitialised).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-18 02:01:04 +02:00
co-authored by Claude Sonnet 5.5
parent 7330ddb6d5
commit 3d9af8a0eb
2 changed files with 247 additions and 16 deletions
@@ -78,12 +78,20 @@ impl Shared {
if j >= n {
return None;
}
match self.head.compare_exchange_weak(current, current + 1, Ordering::AcqRel, Ordering::Acquire) {
// SeqCst: this successful claim and `HostStage::finish`'s `head` store / `active` load form a store-buffering
// (Dekker) pair with `work`'s `active` increment; weaker orderings let `finish` read `active == 0` while a
// helper's claim still read the pre-`finish` `head`, i.e. a copy from a bank the caller is about to release.
match self.head.compare_exchange_weak(current, current + 1, Ordering::SeqCst, Ordering::Acquire) {
Ok(_) => return Some(j),
Err(actual) => current = actual,
}
}
}
/// `finish` (or a later generation) emptied the claim word: no job of generation `seen` may be copied any more.
fn finished(&self, seen: u32) -> bool {
let head = self.head.load(Ordering::Acquire);
(head >> 32) as u32 != seen || (head >> 16) & 0xffff == 0
}
fn work(&self) {
let mut seen = 0u32;
loop {
@@ -99,7 +107,7 @@ impl Shared {
Arc::clone(&wake.jobs)
};
loop {
self.active.fetch_add(1, Ordering::AcqRel);
self.active.fetch_add(1, Ordering::SeqCst); // before the claim; pairs with `finish` (see `claim`)
let Some(j) = self.claim(seen) else {
self.active.fetch_sub(1, Ordering::AcqRel);
break;
@@ -108,14 +116,16 @@ impl Shared {
// buffer j % ring holds job j - ring until that job's DMA completed
let mut cancelled = false;
while j >= ring && self.released.load(Ordering::Acquire) <= j - ring {
if (self.head.load(Ordering::Acquire) >> 32) as u32 != seen
|| ((self.head.load(Ordering::Acquire) >> 16) & 0xffff) == 0
{
if self.finished(seen) {
cancelled = true;
break;
}
thread::yield_now();
}
// `finish` empties `head` BEFORE it raises `released` to "everything free": a helper that read only the
// raised `released` leaves the loop above without having looked at `head`, and would copy into a ring
// buffer whose previous DMA may still be reading it. Look once more, now that `released` was seen.
cancelled |= self.finished(seen);
if !cancelled {
let job = jobs[j];
let base = self.buffers[j % ring];
@@ -157,6 +167,8 @@ pub(super) struct HostStage {
api: Option<api::MappedApi>,
generation: u32,
jobs: usize,
/// bytes job `j`'s helper copies into its buffer (sum of its pieces): all `wait` may hand out
sizes: Vec<usize>,
issued: usize,
poisoned: bool,
}
@@ -200,6 +212,7 @@ impl HostStage {
api: None,
generation: 0,
jobs: 0,
sizes: Vec::new(),
issued: 0,
poisoned: false,
};
@@ -244,6 +257,12 @@ impl HostStage {
if jobs.is_empty() {
return Ok(());
}
let mut sizes = Vec::new();
sizes.try_reserve_exact(jobs.len()).map_err(|_| Error::HostAllocation)?;
for job in &jobs {
sizes.push(job.pieces.iter().try_fold(0usize, |n, piece| n.checked_add(piece.1)).ok_or(Error::InvalidSize)?);
}
self.sizes = sizes;
self.generation = self.generation.wrapping_add(1) & !NON_FINITE;
if self.generation == 0 {
self.generation = 1;
@@ -263,9 +282,10 @@ impl HostStage {
Ok(())
}
/// Job `j`'s staged bytes (`length` of them), once its copy is ready. `release` is polled while waiting: it
/// returns how many issued jobs' DMAs have completed, in order (the helpers wait for those buffers).
/// returns how many issued jobs' DMAs have completed, in order (the helpers wait for those buffers). `length`
/// may not exceed what the job's helper copied: the buffers are uninitialised page-locked memory.
pub(super) fn wait(&mut self, j: usize, length: usize, mut release: impl FnMut() -> Result<usize>) -> Result<&[u8]> {
if j >= self.jobs || j != self.issued || length > self.shared.buffer_bytes {
if j >= self.jobs || j != self.issued || length > self.shared.buffer_bytes || length > self.sizes[j] {
return Err(Error::InvalidProjectionShape);
}
loop {
@@ -297,9 +317,10 @@ impl HostStage {
}
/// No helper copies after this (the end of a layer, or an early return in the middle of one).
pub(super) fn finish(&mut self) {
self.shared.head.store(u64::from(self.generation) << 32, Ordering::Release);
// SeqCst on this store and the `active` loads below: see `Shared::claim` (store-buffering pair).
self.shared.head.store(u64::from(self.generation) << 32, Ordering::SeqCst);
self.shared.released.store(usize::MAX / 2, Ordering::Release);
while self.shared.active.load(Ordering::Acquire) != 0 {
while self.shared.active.load(Ordering::SeqCst) != 0 {
thread::yield_now();
}
self.jobs = 0;
@@ -358,4 +379,135 @@ mod tests {
}
assert!(!scales_finite(8, &[0u8; 34]));
}
/// A stage over zeroed heap buffers and no CUDA: the helper protocol (claims, ring reuse, `finish`) is host code.
fn manual_stage(ring: usize, buffer_bytes: usize, threads: usize) -> HostStage {
let layout = std::alloc::Layout::from_size_align(buffer_bytes.next_multiple_of(4096), 4096).unwrap();
let mut allocations = Vec::new();
let mut buffers = Vec::new();
for _ in 0..ring {
// SAFETY: non-zero size, valid power-of-two alignment.
let pointer = unsafe { std::alloc::alloc_zeroed(layout) };
assert!(!pointer.is_null());
allocations.push((pointer, layout));
buffers.push(pointer as usize);
}
let shared = Arc::new(Shared {
wake: Mutex::new(Wake { generation: 0, jobs: Arc::from(Vec::new()), quit: false }),
cv: Condvar::new(),
head: AtomicU64::new(0),
ready: (0..MAX_JOBS).map(|_| AtomicU32::new(0)).collect(),
released: AtomicUsize::new(0),
active: AtomicUsize::new(0),
buffers: buffers.into_boxed_slice(),
buffer_bytes,
});
let handles = (0..threads)
.map(|_| {
let shared = Arc::clone(&shared);
thread::spawn(move || shared.work())
})
.collect();
HostStage {
shared,
threads: handles,
allocations,
registered: Vec::new(),
api: None,
generation: 0,
jobs: 0,
sizes: Vec::new(),
issued: 0,
poisoned: false,
}
}
/// Three Q2_0/IQ4_NL-sized (kind 20, 18-byte) blocks with a finite FP16 scale (1.0) and `fill` payload.
fn blocks(fill: u8) -> Vec<u8> {
let mut bytes = vec![fill; 54];
for block in bytes.as_chunks_mut::<18>().0.iter_mut() {
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
}
bytes
}
fn job(bytes: &[u8]) -> Job {
let piece = |i: usize| (bytes[i * 18..].as_ptr() as usize, 18, 20);
Job { pieces: [piece(0), piece(1), piece(2)] }
}
/// `wait` hands out `length` bytes of a page-locked buffer that production allocates uninitialised: a length
/// beyond what the job's helper copied would expose bytes nobody wrote (or a previous job's).
#[test]
fn wait_refuses_a_length_beyond_the_bytes_the_job_copied() {
let mut stage = manual_stage(2, 108, 2);
let (a, b) = (blocks(0x11), blocks(0x22));
stage.start(vec![job(&a), job(&b)]).unwrap();
assert_eq!(stage.wait(0, 54, || Ok(0)).unwrap(), &a[..]);
stage.issued(0);
assert!(stage.wait(1, 108, || Ok(0)).is_err(), "108 bytes of a 54-byte job");
assert_eq!(stage.wait(1, 54, || Ok(0)).unwrap(), &b[..]);
stage.issued(1);
stage.finish();
stage.close().unwrap();
}
/// `finish` is also the early-return path of a layer whose earlier DMAs may still be reading the ring. A helper
/// already holding job 2's claim but waiting for buffer 0's DMA (`released`) must be cancelled by it, not
/// released by `finish`'s own `released = MAX` store into overwriting that buffer.
#[test]
fn finish_cancels_a_helper_that_waits_for_a_buffer_still_being_read() {
let mut stage = manual_stage(2, 54, 3);
let (a, b, c) = (blocks(0x11), blocks(0x22), blocks(0x33));
stage.start(vec![job(&a), job(&b), job(&c)]).unwrap();
assert_eq!(stage.wait(0, 54, || Ok(0)).unwrap(), &a[..]);
stage.issued(0);
assert_eq!(stage.wait(1, 54, || Ok(0)).unwrap(), &b[..]);
stage.issued(1);
// all three claimed: job 2 spins on `released > 0` (job 0's DMA never completes here)
while stage.shared.head.load(Ordering::Acquire) & 0xffff != 3 {
thread::yield_now();
}
thread::sleep(std::time::Duration::from_millis(50));
stage.finish();
// SAFETY: `finish` returned with `active == 0`: no helper touches the buffer any more.
let buffer = unsafe { std::slice::from_raw_parts(stage.shared.buffers[0] as *const u8, 54) };
assert_eq!(buffer, &a[..], "job 2 must not copy into buffer 0 after finish");
assert_eq!(stage.shared.ready[2].load(Ordering::Acquire), 0);
stage.close().unwrap();
}
/// `finish` must not return while a helper that claimed a job BEFORE it can still read the bank (the caller releases
/// the bank right after). That is a store-buffering (Dekker) pair -- `finish`: store `head`, load `active`; helper:
/// increment `active`, claim from `head` -- which needs SeqCst on all four accesses. The window is a few nanoseconds, so
/// this is a statistical guard: the bank is poisoned (scale bytes 0xff) right after `finish`, and a straggler's late copy
/// would show up as 0xff bytes in a ring buffer. HONEST LIMIT: with the four orderings reverted to AcqRel/Release/Acquire
/// it did not fail in 80 runs x 4000 rounds on an i9-11900H, whereas deleting the `active` wait in `finish` failed 2 of 40 runs:
/// it guards gross regressions, not the store-buffering window itself; that rests on the memory-model argument.
#[test]
fn finish_leaves_no_helper_copying_from_a_released_bank() {
const JOBS: usize = 8; // == ring: every claimed job copies at once (no waiting for a DMA)
let mut stage = manual_stage(JOBS, 54, 6);
for round in 0..4000usize {
let mut bank: Vec<Vec<u8>> = (0..JOBS).map(|_| blocks(0x11)).collect();
let jobs: Vec<Job> = bank.iter().map(|bytes| job(bytes)).collect();
stage.start(jobs).unwrap();
// sweep `finish` across the helpers' wake-up and claim window (0..~40 us)
for _ in 0..(round * 7919) % 1000 {
std::hint::spin_loop();
}
stage.finish();
for bytes in &mut bank {
bytes.fill(0xff);
}
// give a (buggy) straggler time to complete the copy it started
for _ in 0..50 {
std::hint::spin_loop();
}
for &buffer in stage.shared.buffers.iter() {
// SAFETY: `finish` returned with `active == 0`, so no helper may touch the ring buffers any more.
let bytes = unsafe { std::slice::from_raw_parts(buffer as *const u8, 54) };
assert!(!bytes.contains(&0xff), "round {round}: a helper copied from the bank after finish returned");
}
}
stage.close().unwrap();
}
}
@@ -313,20 +313,32 @@ impl Shared {
if j >= n {
return None;
}
// SeqCst on the success path: see `enter_claim`.
match self
.head
.compare_exchange_weak(cur, cur + 1, Ordering::AcqRel, Ordering::Acquire)
.compare_exchange_weak(cur, cur + 1, Ordering::SeqCst, Ordering::Acquire)
{
Ok(_) => return Some(j),
Err(next) => cur = next,
}
}
}
/// A worker's claim prologue: `active` is raised BEFORE `head` is read (Original finish's fence). Together with
/// `stop` this is a store-buffering (Dekker) pair -- `stop`: store `head`, load `active`; worker: increment
/// `active`, claim from `head` -- so all four accesses must be SeqCst. With Release/Acquire a worker can claim from
/// the pre-`stop` `head` while `stop` still reads `active == 0`, and then copy from sources (mapped file, retained
/// banks) that the caller releases as soon as `stop` returns.
fn enter_claim(&self, generation: u32) -> Option<(Active<'_>, usize)> {
self.active.fetch_add(1, Ordering::SeqCst);
let active = Active(self);
let j = self.claim(generation)?; // no claim: `active` drops here
Some((active, j))
}
fn stop(&self, generation: u32) {
self.head
.store(u64::from(generation) << 32, Ordering::Release);
.store(u64::from(generation) << 32, Ordering::SeqCst);
self.issued.store(1 << 30, Ordering::Release);
while self.active.load(Ordering::Acquire) != 0 {
while self.active.load(Ordering::SeqCst) != 0 {
thread::yield_now();
}
}
@@ -361,10 +373,7 @@ fn worker(api: Arc<abi::Api>, shared: Arc<Shared>, context: usize) {
}
loop {
// Active precedes the generation CAS, exactly Original finish's fence.
shared.active.fetch_add(1, Ordering::AcqRel);
let active = Active(&shared);
let Some(j) = shared.claim(seen) else {
drop(active);
let Some((active, j)) = shared.enter_claim(seen) else {
break;
};
if shared.failed.load(Ordering::Acquire) {
@@ -1172,3 +1181,73 @@ impl OriginalExpertStager<'_> {
})
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `stop` is the fence after which the caller releases the sources the workers copy from. A worker that claimed
/// before it must have left (`active == 0`) when it returns; a claim that completes AFTER it returned would copy
/// from released memory. The window is a few nanoseconds (store-buffering on `head`/`active`), so this is a
/// statistical guard: helpers run the real claim prologue and, once `stop` returned, a flag marks the source released.
#[test]
fn stop_leaves_no_worker_claiming_after_it_returns() {
let shared = Arc::new(Shared {
work: Mutex::new(Work { generation: 0, quit: false, jobs: Vec::new() }),
cv: Condvar::new(),
head: AtomicU64::new(0),
issued: AtomicUsize::new(0),
active: AtomicUsize::new(0),
ready: Vec::new(),
started: AtomicUsize::new(0),
failed: AtomicBool::new(false),
error: Mutex::new(None),
slots: Vec::new(),
});
let released = Arc::new(AtomicBool::new(false));
let late = Arc::new(AtomicUsize::new(0));
let quit = Arc::new(AtomicBool::new(false));
let round = Arc::new(std::sync::atomic::AtomicU32::new(0));
let helpers: Vec<_> = (0..6)
.map(|_| {
let (shared, released, late, quit, round) =
(shared.clone(), released.clone(), late.clone(), quit.clone(), round.clone());
thread::spawn(move || {
while !quit.load(Ordering::Acquire) {
let generation = round.load(Ordering::Acquire);
if let Some((active, _job)) = shared.enter_claim(generation) {
// the "copy from the source", then a check that the source was not released meanwhile
for _ in 0..200 {
std::hint::spin_loop();
}
if released.load(Ordering::SeqCst) {
late.fetch_add(1, Ordering::SeqCst);
}
drop(active);
} else {
std::hint::spin_loop();
}
}
})
})
.collect();
for generation in 1..=100_000u32 {
round.store(generation, Ordering::Release);
shared.head.store((u64::from(generation) << 32) | (4000 << 16), Ordering::Release);
for _ in 0..20 {
std::hint::spin_loop();
}
shared.stop(generation);
released.store(true, Ordering::SeqCst);
for _ in 0..400 {
std::hint::spin_loop();
}
released.store(false, Ordering::SeqCst);
}
quit.store(true, Ordering::Release);
for helper in helpers {
helper.join().unwrap();
}
assert_eq!(late.load(Ordering::SeqCst), 0, "a worker claimed after stop returned");
}
}