rt: quiesce leaves a late thread running and keeps it; the teardown joins every thread first

3ed8095758 made quiesce join every thread past its deadline. That made quiesce unbounded, which
breaks the exit contract (077c9722e3, 0071f33d2c, the README): after a false answer a thread can
still be in the driver, on NVIDIA the completion thread in an unbounded semaphore wait until a
later submission the runtime never makes, and a consumer calls quiesce with its bound from its
exit path for exactly that case. The exit-139 hazard is destruction under a live thread, and
quiesce destroys nothing.

Now, as on development, quiesce waits for each thread up to its deadline and joins one only once
it has ended; a thread past the deadline is left running and its handle kept (halt hands the left
threads back, Device::quiesce keeps them in Shared). The teardown, on whichever thread drops the
last handle, joins every runtime thread with no deadline before it destroys anything a thread can
reach: those its own stop waits for, and those a late quiesce left (join). A thread is never
joined by itself: the reaper running a teardown lets its own handle go and ends once it returns.

The late-quiesce upload test is restored as development has it (fa415d77ce undone): it states the
contract, a quiesce that answers at its deadline while host-held work keeps the GPU. The README's
quiesce section and Device::quiesce's doc are development's again, with one sentence each on the
teardown's join; bf561f5241's sentence is gone with them. The quiesce join test becomes the test
the fix needs: with the submit thread held in a scheduled handler, quiesce(0) answers false at
once and leaves it running; the last handle, dropped on another thread, has not returned half a
second later, the blocks live and the thread holds its slot; once the handler lets it go, the drop
returns and every gauge reads zero (every_device_dropped_after_a_late_quiesce_joins_the_late_thread_first,
under the validation layer as every device test).
This commit is contained in:
Anees Iqbal committed 2026-11-19 03:17:37 -08:00
1 parent e234d5dd84
commit 9ba7b2a45f
5 files changed
+160 -122

No files matched your search

+17 -18
View File
@@ -1058,26 +1058,25 @@ made, with no lock, and never rewritten for layouts.
### Quiesce and exit
`Device::quiesce(timeout)` is for a process that exits with the device alive. It stops the submit
thread (ready work is submitted, held work ends `NotRun`) and the block-maker, waits for the GPU to
complete what was submitted, lets the completion thread retire it and end, stops the reaper, and
then runs `BlockMappings::unmap` on the calling thread for every allocation still mapped. It frees
nothing: every block's memory and mapping stays valid until the process ends. After it, no runtime
thread touches a block; later calls that need a thread return `Error::Quiesced`. It answers true
once the GPU went idle and every thread ended within the timeout, and false at once in a handler
or a listener, whose thread cannot wait for itself. A second call returns at once. The timeout
bounds only the answer: every runtime thread is joined before the call returns, past the timeout
too, and so before the device's last handle can destroy the device and the instance, which a
thread still in the driver would reach. Nothing is cancelled at the timeout (held work ends
`NotRun` when the stop begins, and the GPU runs what was submitted to the end), so a false answer
outside a handler or a listener says only that this took longer than the timeout: the call
returns once the GPU has completed everything submitted and every thread has ended, as on true. A thread that never returns from a driver call keeps
quiesce, and the device's drop, from returning: on NVIDIA's driver, where the GPU faulted, the
completion thread's `vkWaitSemaphores` with no timeout does not return until a later submission,
which after quiesce the runtime never makes; a known gap on NVIDIA.
`Device::quiesce(timeout)` is for a process that exits with the device alive. With every wait
bounded by the timeout, it stops the submit thread (ready work is submitted, held work ends
`NotRun`) and the block-maker, waits for the GPU to complete what was submitted, lets the
completion thread retire it and end, and then runs `BlockMappings::unmap` on the calling thread for
every allocation still mapped. It frees nothing: every block's memory and mapping stays valid until
the process ends. After it, no runtime thread touches a block; later calls that need a thread
return `Error::Quiesced`. It answers true once the GPU went idle and every thread ended in time,
and false at once in a handler or a listener, whose thread cannot wait for itself. A second call
returns at once. After a false answer a runtime thread can still be in the driver (the completion
thread in `vkWaitSemaphores` with no timeout where the GPU did not go idle, which on NVIDIA's
driver lasts until a later submission that after quiesce the runtime never makes, or in its
retirement calls once a handler that held it returns, and the reaper or the block-maker in a
pipeline creation or a memory call that outlasted the timeout), so a process that gets false ends
without running exit handlers (`_exit`): a known gap on NVIDIA. Quiesce leaves such a thread
running and keeps its handle: the device's last handle joins it, with no deadline, before it
destroys anything the thread can reach, so a drop after a false answer waits for that thread.
The consumer quiesces before it calls `exit()`. Quiesce can also run in an `atexit` handler, on
whichever thread calls `exit()`: it waits for each thread to end and joins it, reads no
whichever thread calls `exit()`: it joins a thread only once that thread has ended, reads no
thread-local that `exit()` tears down, and takes no lock a consumer's thread can hold. Such a
handler is a fallback, not the contract: `exit()` runs handlers in the reverse order of their
registration, so it runs before the driver's own exit teardown only where it was registered after
+2 -2
View File
@@ -348,8 +348,8 @@ impl Done {
/// Tells the completion thread to end once nothing is in flight. The submit thread tells it
/// as it ends, after the last command buffers it ended came here, so none comes after the
/// thread. The thread ends then whatever a stop's deadline was: one past a quiesce's deadline
/// ends once the GPU completed what was in flight and it retired that, so nothing in flight
/// is left holding what it used, the core among it, and the stop joins it then.
/// ends alone, once the GPU completed what was in flight and it retired that, so nothing in
/// flight is left holding what it used, the core among it; the teardown joins it.
pub(crate) fn stop(&self, core: &Core) {
let mut state = self.lock();
state.stop = true;
+97 -67
View File
@@ -729,16 +729,17 @@ impl Device {
/// listener (the submit thread, which runs the scheduled handlers, and the completion thread,
/// which runs the completed handlers and listeners, cannot wait for themselves).
///
/// In order: the submit thread submits what is ready, ends every command buffer it holds or
/// has not yet submitted with [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun),
/// and ends; the block-maker thread ends; the GPU completes everything submitted; the
/// completion thread retires it, runs the completed handlers, and ends; the reaper ends; then
/// [`BlockMappings::unmap`] runs on this thread for every allocation still mapped. `timeout`
/// bounds only how long that may take before the answer is false: every thread is joined
/// before the call returns, past the timeout too, so nothing a live runtime thread can reach
/// (the device, the instance, a queue) is destroyed while it runs. A thread that never
/// returns from a driver call keeps the call from returning. After it, no runtime thread
/// touches a block, unless the call ran in a handler or a listener.
/// In order, each wait bounded by `timeout`: the submit thread submits what is ready, ends
/// every command buffer it holds or has not yet submitted with
/// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun), and ends; the
/// block-maker thread ends; the GPU completes everything submitted; the completion thread
/// retires it, runs the completed handlers, and ends; then [`BlockMappings::unmap`] runs on
/// this thread for every allocation still mapped. After it, no runtime thread touches a block,
/// unless the call answered false. A thread past the timeout ends alone: the completion
/// thread once the GPU completed what was submitted and it retired that, running its
/// completed handlers, so what the work held, the device among it, goes once the device's
/// last handle has dropped. Such a thread is not joined here; the device's last handle joins
/// it, with no deadline, before it destroys anything the thread can reach.
///
/// It frees nothing: every allocation's memory and mapping stays valid until the process ends,
/// or until the device's last handle drops, which then frees it without the hook. Later calls
@@ -746,19 +747,17 @@ impl Device {
/// an enqueue or commit, a zeroed Private buffer, and a listener.
///
/// The consumer calls it before `exit()`. It can also run in an `atexit` handler on whichever
/// thread calls `exit()`: it waits for each thread to end and joins it, reads no
/// thread calls `exit()`: it joins a thread only once that thread has ended, reads no
/// thread-local that `exit()` tears down, and takes no lock a consumer's thread can hold. Such
/// a handler runs before the driver's own exit teardown only where it was registered after the
/// driver loaded, after `Device::new`. A second call returns at once, with the first call's
/// answer, or false while the first is still running.
pub fn quiesce(&self, timeout: Duration) -> bool {
let threads = self.shared.take_threads();
halt(
&self.shared.core,
threads,
Instant::now().checked_add(timeout),
true,
)
let deadline = Instant::now().checked_add(timeout);
let (idle, left) = halt(&self.shared.core, threads, deadline, true);
self.shared.keep_threads(left);
idle
}
/// No Metal counterpart: gives a block back where `block` is its last handle: the drop of the
@@ -907,22 +906,47 @@ impl Shared {
reaper: threads.reaper.take(),
}
}
/// The threads a stop left running, kept for the teardown to join.
fn keep_threads(&self, left: Threads) {
let mut threads = lock(&self.threads);
let Threads {
blocks,
submit,
complete,
reaper,
} = left;
for (slot, runner) in [
(&mut threads.blocks, blocks),
(&mut threads.submit, submit),
(&mut threads.complete, complete),
(&mut threads.reaper, reaper),
] {
if runner.is_some() {
*slot = runner;
}
}
}
}
/// Stops the runtime's threads and its GPU work, and runs the consumer's unmap hook for every
/// allocation still mapped, on this thread: for [`Device::quiesce`] (`quiesce`, with its deadline)
/// and for teardown. Only the first call stops anything; a later one answers at once. Every
/// thread but this one is joined before it returns, past `deadline` too: nothing a live thread
/// can reach (the device, the instance, a queue) is destroyed before that thread is joined.
/// `deadline` bounds only how long the queued work may take before it counts late. True once the
/// GPU went idle and every thread ended by `deadline`.
fn halt(core: &Arc<Core>, threads: Threads, deadline: Option<Instant>, quiesce: bool) -> bool {
/// and for teardown, with none. Only the first call stops anything; a later one answers at once
/// and hands `threads` back. Each wait is bounded by `deadline`: a thread that has not ended by
/// then is left running, not joined, and handed back, with this thread's own, for the teardown to
/// join ([`join`]). True once the GPU went idle and every thread ended by `deadline`.
fn halt(
core: &Arc<Core>,
threads: Threads,
deadline: Option<Instant>,
quiesce: bool,
) -> (bool, Threads) {
match core
.halt
.compare_exchange(RUNNING, HALTING, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {}
Err(halt) => return halt == HALTED_IDLE,
Err(halt) => return (halt == HALTED_IDLE, threads),
}
core.closed.store(true, Ordering::Release);
let Threads {
@@ -931,72 +955,75 @@ fn halt(core: &Arc<Core>, threads: Threads, deadline: Option<Instant>, quiesce:
complete,
reaper,
} = threads;
let mut left = Threads::default();
// Where a scheduled handler quiesces, on the submit thread, the thread's own submission and
// the completion thread wait for the handler to return: neither is waited for.
let on_submit = role(core) == Role::Submit;
// Submission stops: what is ready goes, and what is held ends.
core.work.stop();
let submitted = finish(submit, core, deadline);
let mut idle = submitted.in_time;
let submitted = finish(submit, core, deadline, &mut left.submit);
let mut idle = submitted;
core.pool.stop();
idle &= finish(blocks, core, deadline).in_time;
idle &= finish(blocks, core, deadline, &mut left.blocks);
if quiesce && !on_submit {
idle &= core.wait_progress(core.work.progress(), deadline);
}
// The submit thread stops the completion thread as it ends; here only where it has ended, or
// never ran.
if submitted.joined {
// never ran. One past the deadline stops it when it ends alone.
if submitted {
core.done.stop(core);
}
if !on_submit {
idle &= finish(complete, core, deadline).in_time;
match on_submit {
false => idle &= finish(complete, core, deadline, &mut left.complete),
true => left.complete = complete,
}
core.reaper.stop();
idle &= finish(reaper, core, deadline).in_time;
idle &= finish(reaper, core, deadline, &mut left.reaper);
// The consumer's mappings go here, on the thread that stops the device, whichever thread
// later drops the core's last reference and frees the memory.
core.pool.unmap_all();
let answer = if idle { HALTED_IDLE } else { HALTED_LATE };
core.halt.store(answer, Ordering::Release);
idle
(idle, left)
}
/// How a stop waited for one thread.
struct Finished {
/// It ended by the deadline.
in_time: bool,
/// It was joined, or never ran.
joined: bool,
}
/// Joins a thread: it ended by `deadline` or later, and a thread past the deadline is waited for
/// all the same, never left behind. A thread is never waited for by itself: the completion
/// thread where a completed handler or a listener quiesces, the submit thread where a scheduled
/// handler does, the reaper where it runs a teardown; it ends once the call returns.
fn finish(runner: Option<Runner>, core: &Arc<Core>, deadline: Option<Instant>) -> Finished {
let Some(Runner {
handle,
ended,
role: of,
}) = runner
else {
return Finished {
in_time: true,
joined: true,
};
/// Waits for a thread to end, up to `deadline`, and joins it once it has: true. A thread past the
/// deadline is left running, not joined, its handle put in `left` for the teardown to join; so is
/// this thread's own, which is never waited for by itself (the completion thread where a
/// completed handler or a listener quiesces, the submit thread where a scheduled handler does,
/// the reaper where it runs a teardown) and ends once the call returns.
fn finish(
runner: Option<Runner>,
core: &Arc<Core>,
deadline: Option<Instant>,
left: &mut Option<Runner>,
) -> bool {
let Some(runner) = runner else {
return true;
};
if role(core) == of {
return Finished {
in_time: false,
joined: false,
};
if role(core) == runner.role || !runner.ended.wait(deadline) {
*left = Some(runner);
return false;
}
let in_time = ended.wait(deadline);
// A thread that panicked has ended all the same.
let _ = handle.join();
Finished {
in_time,
joined: true,
let _ = runner.handle.join();
true
}
/// Joins each thread a stop left running ([`halt`]), with no deadline, before the teardown
/// destroys anything such a thread can reach (the device, the instance, a queue): after a late
/// quiesce, the threads still in the driver or ending alone. This thread's own handle is let go:
/// it ends once the call returns.
fn join(core: &Arc<Core>, threads: Threads) {
let Threads {
blocks,
submit,
complete,
reaper,
} = threads;
for runner in [submit, blocks, complete, reaper] {
let mut own = None;
finish(runner, core, None, &mut own);
}
}
@@ -1271,7 +1298,10 @@ impl Drop for Shared {
fn drop(&mut self) {
let threads = self.take_threads();
let teardown = move |core: &Arc<Core>| {
halt(core, threads, None, false);
// Every thread is joined before anything it can reach goes: those this stop waits
// for, and those a late quiesce left running.
let (_, left) = halt(core, threads, None, false);
join(core, left);
// The blocks the consumer still holds handles of go back to the pool once the threads
// have stopped and the consumer's unmap hook has returned for each allocation
// (`halt`), for the core to free; a handle dropped later finds its claim empty. No buffer of them is
+37 -23
View File
@@ -2582,15 +2582,18 @@ pub(crate) mod on_device {
});
}
/// A quiesce past its deadline joins every runtime thread before it returns, so nothing a
/// live thread can reach (the device, the instance, a queue) is destroyed before that thread
/// is joined: with the submit thread held in a scheduled handler past a zero deadline, the
/// call returns only after the handler let it go, answers false, and by then none of the
/// device's four threads holds a slot of `Gauges::threads` (its thread ids, where the OS
/// gives them). The command buffer ends, and the device then tears down.
/// A drop after a late quiesce joins the thread the quiesce left running before anything that
/// thread can reach goes (the device, the instance, a queue): the shape of a process that ends
/// with a runtime thread still running. With the submit thread held in a scheduled handler, a
/// quiesce with no time to wait answers false at once and leaves that thread running, its
/// slot of `Gauges::threads` held (its thread id, where the OS gives one). The device's last
/// handle, dropped on another thread, has not returned half a second later, the blocks live,
/// and the thread holds its slot; once the handler lets it go, the drop returns, every gauge
/// reads zero and no thread of the device's holds a slot. Under the validation layer, as
/// every device test.
#[test]
fn every_device_joins_each_thread_past_a_quiesce_deadline_before_destroying_what_it_reaches() {
each_device("quiesce_joins", |name, _, device| {
fn every_device_dropped_after_a_late_quiesce_joins_the_late_thread_first() {
each_device("late_quiesce_drop", |name, _, device| {
let counters = device.counters();
let four: Vec<u64> = (counters.gauges().threads.iter())
.copied()
@@ -2617,24 +2620,35 @@ pub(crate) mod on_device {
inside
.recv_timeout(PATIENCE)
.expect("the handler holds the submit thread");
let quiescing = device.clone();
let quiesced = thread::spawn(move || quiescing.quiesce(Duration::ZERO));
// The stop began, past its zero deadline, while the handler holds the submit thread.
within("the quiesce's stop", || {
matches!(queue.command_buffer(), Err(Error::Quiesced))
});
release.send(()).expect("the handler waits");
let idle = quiesced.join().expect("the quiescing thread");
assert!(!idle, "{name}: the submit thread ended past the deadline");
assert_eq!(
alive(),
0,
"{name}: every thread joined before quiesce returned: {:?}",
counters.gauges().threads
assert!(
!device.quiesce(Duration::ZERO),
"{name}: no time to wait, an answer at once"
);
assert!(
alive() >= four.len().min(1),
"{name}: the held thread is left running"
);
let (dropped, gone) = mpsc::channel::<()>();
let dropping = thread::spawn(move || {
drop((a, arena, queue, device));
let _ = dropped.send(());
});
assert!(
gone.recv_timeout(Duration::from_millis(500)).is_err(),
"{name}: the drop waits for the held thread"
);
assert!(
counters.gauges().blocks > 0,
"{name}: the blocks live while the held thread runs"
);
assert!(alive() >= four.len().min(1), "{name}: the held thread runs");
release.send(()).expect("the handler waits");
(gone.recv_timeout(PATIENCE)).expect("the drop returns once the held thread ended");
dropping.join().expect("the dropping thread");
finished(name, &command_buffer);
drop((a, arena, queue, command_buffer, device));
drop(command_buffer);
within("the teardown", || counters.gauges() == Gauges::default());
assert_eq!(alive(), 0, "{name}: every thread ended");
});
}
+7 -12
View File
@@ -431,12 +431,11 @@ mod on_device {
}
}
/// A quiesce past its deadline while busy work the host holds ([`Busy`]) keeps the GPU, with a
/// `get_bytes` copy submitted behind it, waits for the completion thread all the same: once
/// the busy work opens, the thread retires the copy, which held what it used (the core among
/// it), and ends, and only then does the quiesce answer, late. The device's last handle then
/// frees everything: every gauge reads zero, and the instance goes within the validation
/// guard's patience.
/// A quiesce that answers past its deadline while busy work the host holds ([`Busy`]) keeps
/// the GPU, with a `get_bytes` copy submitted behind it, leaves the completion thread to end
/// alone: once the busy work opens, it retires the copy, which held what it used (the core
/// among it), and ends. The device's last handle then frees everything: every gauge reads
/// zero, and the instance goes within the validation guard's patience.
#[test]
fn every_device_frees_itself_after_a_quiesce_past_its_deadline() {
let instance = crate::tests::validation::instance(&[]);
@@ -467,15 +466,11 @@ mod on_device {
wait_until("the read's submission", || {
counters.metrics().submissions > submitted
});
let quiescing = device.clone();
let quiesced = thread::spawn(move || quiescing.quiesce(Duration::ZERO));
// The stop began, past its zero deadline, while the busy work holds the GPU.
wait_until("the quiesce's stop", || core.closed());
busy.open();
assert!(
!quiesced.join().expect("the quiescing thread"),
!device.quiesce(Duration::from_millis(100)),
"{name}: the quiesce answers past its deadline while the busy work holds the GPU"
);
busy.open();
let _ = reader.join().expect("the reader");
drop(busy);
drop(device);