metal2vulkan-rt: a reaper thread frees what the other threads give up

The planner's decision on (c): no driver free runs on the completion thread, since NVIDIA's frees
take 1-11 ms and would delay every later completion, and a submission on another thread waits
behind at most one free.

- A fourth runtime thread, the reaper, destroys event semaphores (the events gauge falls with
  each) and command pools past the idle ones kept, one at a time, in the order given. Every
  EventInner drop and every surplus recorder goes to it, whichever thread gives it up.
- A last handle dropped on the completion thread (a handler or listener) hands the whole teardown
  to the reaper: it stops and joins the other threads, gives the consumer's blocks back, and the
  core drops there. Every gauge still reads zero only once vkDestroyDevice has returned.
- Stops wait for a thread only where it is not the calling thread, by a per-thread role in a
  constant thread-local without a destructor. The reaper stops last, after its queue is empty;
  frees given after that are made at the core's drop.
- The handler teardown test now takes a block and checks it is unmapped once, on the reaper.

Verified: cargo fmt; the compile and device jobs follow.
This commit is contained in:
Anees Iqbal committed 2026-11-17 08:12:44 -08:00
1 parent 6769c2eaaf
commit 56fc28e12d
9 files changed
+307 -101

No files matched your search

+5 -3
View File
@@ -30,15 +30,17 @@ device against the floor below.
### Teardown
The runtime runs three threads per device: the block-maker, the submit thread and the completion
thread. A device is torn down when its last handle, and the last handle of every object made from
The runtime runs four threads per device: the block-maker, the submit thread, the completion
thread, and the reaper, which frees the semaphores and command pools the others give up, one at a
time, so no driver free runs on the completion thread and a submission waits behind at most one.
A device is torn down when its last handle, and the last handle of every object made from
it, is dropped; a committed command buffer and the blocks the consumer holds do not keep it alive.
Teardown stops the submit thread, which submits what is ready and ends what it holds with
`CommandBufferError::NotRun`; the completion thread retires the rest as the GPU completes it and
runs the handlers; the threads are joined and the GPU goes idle. Then every block is freed,
`BlockMappings::unmap` first for each block the consumer was handed, and the `VkDevice` is
destroyed. Teardown runs on the thread that drops the last handle, or, where that is a handler or
a listener, on the completion thread once the handler returns; every gauge reads zero only once
a listener, on the reaper once the handler returns; every gauge reads zero only once
the `VkDevice` is destroyed, so such a consumer waits for that before it drops its instance or
exits. A physical device and a device each hold their instance. No thread of the runtime outlives its device, and nothing relies on a
static destructor or an `atexit` handler: the consumer drops every handle, or calls
+2 -2
View File
@@ -494,7 +494,7 @@ pub(crate) fn retire(
blocks,
} = gpu;
if let Some(recorder) = recorder {
core.recorders.give_back(&core.device, recorder);
core.recorders.give_back(core, recorder);
}
drop((segments, blocks));
inner.queue.release();
@@ -515,7 +515,7 @@ impl Drop for CbInner {
if let Some(Building { device, gpu, .. }) = state.building.take() {
if let Some(recorder) = gpu.recorder {
let core = device.core();
core.recorders.give_back(&core.device, recorder);
core.recorders.give_back(core, recorder);
}
self.queue.release();
}
+141 -71
View File
@@ -9,6 +9,7 @@ use crate::fill::Filler;
use crate::floor;
use crate::instance::{Instance, PhysicalDevice};
use crate::memory::{self, Block, BlockId, BlockInfo, BlockMappings, MemoryClass, Pool, BLOCK_LEN};
use crate::reaper::{self, Job, Reaper};
use crate::record::Recorders;
use crate::submit::{self, Work};
use ash::vk;
@@ -26,15 +27,16 @@ use std::time::{Duration, Instant};
/// A cheap handle: clones share one device, and every object made from it holds a clone, except
/// a committed command buffer. Blocks the consumer holds do not.
///
/// The runtime runs three threads: the block-maker, the submit thread and the completion thread,
/// which runs every handler and listener. The device is torn down when the last handle is
/// dropped: the submit thread submits what is ready and ends what it holds with
/// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun); the completion thread
/// retires the rest as the GPU completes it; the threads are joined; then every block is freed,
/// after [`BlockMappings::unmap`] for each the consumer was handed, and the `VkDevice` is
/// destroyed; every gauge reads zero only then. Where the last handle drops in a handler or a
/// listener, the completion thread finishes the teardown itself once the handler returns, and the
/// consumer waits for the gauges to read zero before it drops its instance or exits. No thread of the
/// The runtime runs four threads: the block-maker, the submit thread, the completion thread,
/// which runs every handler and listener, and the reaper, which frees the semaphores and command
/// pools the others give up, one at a time, so no driver free runs on the completion thread. The
/// device is torn down when the last handle is dropped: the submit thread submits what is ready
/// and ends what it holds with [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun);
/// the completion thread retires the rest as the GPU completes it; the threads are joined; then
/// every block is freed, after [`BlockMappings::unmap`] for each the consumer was handed, and the
/// `VkDevice` is destroyed; every gauge reads zero only then. Where the last handle drops in a
/// handler or a listener, the reaper runs the teardown once the handler returns, and the consumer
/// waits for the gauges to read zero before it drops its instance or exits. No thread of the
/// runtime outlives the teardown, and nothing relies on a static destructor or an `atexit`
/// handler: the consumer drops every handle, or calls [`quiesce`](Device::quiesce), before the
/// process exits (a driver may unmap device memory inside `exit()`).
@@ -57,11 +59,25 @@ struct Threads {
blocks: Option<Runner>,
submit: Option<Runner>,
complete: Option<Runner>,
reaper: Option<Runner>,
}
struct Runner {
handle: JoinHandle<()>,
ended: Arc<Ended>,
role: Role,
}
/// What a runtime thread does.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
/// Not a runtime thread.
None,
Blocks,
Submit,
/// The completion thread: the only one that runs the consumer's code.
Complete,
Reaper,
}
/// Set as a runtime thread ends, so a stop can wait for it with a deadline.
@@ -82,10 +98,20 @@ impl Drop for Ending {
}
thread_local! {
/// The core a runtime thread serves, by address; 0 on every other thread. Constant and without
/// a destructor, so it reads the same while the thread's other thread-locals are torn down
/// (in `exit()`).
static SERVES: Cell<usize> = const { Cell::new(0) };
/// The core a runtime thread serves, by address, and its role; 0 and `Role::None` on every
/// other thread. Constant and without a destructor, so it reads the same while the thread's
/// other thread-locals are torn down (in `exit()`).
static SERVES: Cell<(usize, Role)> = const { Cell::new((0, Role::None)) };
}
/// The role of this thread for `core`.
fn role(core: &Arc<Core>) -> Role {
let (serves, role) = SERVES.get();
if serves == Arc::as_ptr(core) as usize {
role
} else {
Role::None
}
}
/// The device itself: what the runtime's threads and every block hold.
@@ -107,6 +133,7 @@ pub(crate) struct Core {
pub(crate) recorders: Recorders,
pub(crate) work: Work,
pub(crate) done: Done,
pub(crate) reaper: Reaper,
/// Quiesced or torn down: calls that need a thread are refused.
closed: AtomicBool,
/// [`RUNNING`], [`HALTING`], or the answer of the stop that ran.
@@ -272,6 +299,7 @@ impl Device {
recorders: Recorders::new(family),
work: Work::new(),
done,
reaper: Reaper::new(),
closed: AtomicBool::new(false),
halt: AtomicU8::new(RUNNING),
});
@@ -284,11 +312,13 @@ impl Device {
};
// A thread that does not start drops the device, which stops those that did.
let core = &device.shared.core;
let blocks = spawn("m2v-blocks", core, memory::run)?;
let reaper = spawn("m2v-reaper", core, Role::Reaper, reaper::run)?;
lock(&device.shared.threads).reaper = Some(reaper);
let blocks = spawn("m2v-blocks", core, Role::Blocks, memory::run)?;
lock(&device.shared.threads).blocks = Some(blocks);
let submit = spawn("m2v-submit", core, submit::run)?;
let submit = spawn("m2v-submit", core, Role::Submit, submit::run)?;
lock(&device.shared.threads).submit = Some(submit);
let complete = spawn("m2v-complete", core, complete::run)?;
let complete = spawn("m2v-complete", core, Role::Complete, complete::run)?;
lock(&device.shared.threads).complete = Some(complete);
Ok(device)
}
@@ -401,7 +431,13 @@ impl Device {
/// 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 {
self.shared.halt(Instant::now().checked_add(timeout), true)
let threads = self.shared.take_threads();
halt(
&self.shared.core,
threads,
Instant::now().checked_add(timeout),
true,
)
}
/// No Metal counterpart: gives a block back.
@@ -446,8 +482,8 @@ impl Device {
}
}
/// Starts a runtime thread that serves `core`.
fn spawn(name: &str, core: &Arc<Core>, body: fn(Arc<Core>)) -> Result<Runner, Error> {
/// Starts a runtime thread that serves `core` in `role`.
fn spawn(name: &str, core: &Arc<Core>, role: Role, body: fn(Arc<Core>)) -> Result<Runner, Error> {
let ended = Arc::new(Ended::default());
let ending = Ending(Arc::clone(&ended));
let core = Arc::clone(core);
@@ -455,11 +491,15 @@ fn spawn(name: &str, core: &Arc<Core>, body: fn(Arc<Core>)) -> Result<Runner, Er
.name(name.to_string())
.spawn(move || {
let _ending = ending;
SERVES.set(Arc::as_ptr(&core) as usize);
SERVES.set((Arc::as_ptr(&core) as usize, role));
body(core);
})
.map_err(Error::Thread)?;
Ok(Runner { handle, ended })
Ok(Runner {
handle,
ended,
role,
})
}
impl Ended {
@@ -488,56 +528,72 @@ impl Ended {
}
impl Shared {
/// Stops the runtime's threads and its GPU work: for [`Device::quiesce`] (`quiesce`, with its
/// deadline) and for teardown. Only the first call stops anything; a later one answers at
/// once. True once the GPU went idle and every thread ended by `deadline`.
fn halt(&self, deadline: Option<Instant>, quiesce: bool) -> bool {
let core = &self.core;
match core
.halt
.compare_exchange(RUNNING, HALTING, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {}
Err(halt) => return halt == HALTED_IDLE,
/// The runtime's threads, for the stop that waits for them.
fn take_threads(&self) -> Threads {
let mut threads = lock(&self.threads);
Threads {
blocks: threads.blocks.take(),
submit: threads.submit.take(),
complete: threads.complete.take(),
reaper: threads.reaper.take(),
}
core.closed.store(true, Ordering::Release);
let (blocks, submit, complete) = {
let mut threads = lock(&self.threads);
(
threads.blocks.take(),
threads.submit.take(),
threads.complete.take(),
)
};
// Submission stops: what is ready goes, and what is held ends.
core.work.stop();
let mut idle = finish(submit, deadline);
core.pool.stop();
idle &= finish(blocks, deadline);
if quiesce {
idle &= core.wait_progress(core.work.progress(), deadline);
}
core.done.stop(core, deadline);
// Only the completion thread runs the consumer's code among the runtime's threads. Where
// this call runs on it (a handler or listener dropped the last handle, or quiesced), it
// ends itself once the call returns, and is not waited for.
let on_completion = SERVES.get() == Arc::as_ptr(core) as usize;
idle &= !on_completion && finish(complete, deadline) && core.done.drained();
if quiesce {
core.pool.unmap_all();
}
let answer = if idle { HALTED_IDLE } else { HALTED_LATE };
core.halt.store(answer, Ordering::Release);
idle
}
}
/// Stops the runtime's threads and its GPU work: for [`Device::quiesce`] (`quiesce`, with its
/// deadline) and for teardown. Only the first call stops anything; a later one answers at once.
/// 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 {
match core
.halt
.compare_exchange(RUNNING, HALTING, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {}
Err(halt) => return halt == HALTED_IDLE,
}
core.closed.store(true, Ordering::Release);
let Threads {
blocks,
submit,
complete,
reaper,
} = threads;
// Submission stops: what is ready goes, and what is held ends.
core.work.stop();
let mut idle = finish(submit, core, deadline);
core.pool.stop();
idle &= finish(blocks, core, deadline);
if quiesce {
idle &= core.wait_progress(core.work.progress(), deadline);
}
core.done.stop(core, deadline);
idle &= finish(complete, core, deadline) && core.done.drained();
core.reaper.stop();
idle &= finish(reaper, core, deadline);
if quiesce {
core.pool.unmap_all();
}
let answer = if idle { HALTED_IDLE } else { HALTED_LATE };
core.halt.store(answer, Ordering::Release);
idle
}
/// Waits for a thread to end, up to `deadline`, and joins it once it has; a thread past the
/// deadline is left to end alone. True once it ended.
fn finish(runner: Option<Runner>, deadline: Option<Instant>) -> bool {
let Some(Runner { handle, ended }) = runner else {
/// deadline is left to end alone. True once it ended. A thread is never waited for by itself: the
/// completion thread where a handler or listener quiesces, the reaper where it runs a teardown;
/// it ends once the call returns.
fn finish(runner: Option<Runner>, core: &Arc<Core>, deadline: Option<Instant>) -> bool {
let Some(Runner {
handle,
ended,
role: of,
}) = runner
else {
return true;
};
if role(core) == of {
return false;
}
let done = ended.wait(deadline);
if done {
// A thread that panicked has ended all the same.
@@ -617,13 +673,25 @@ pub struct RawDevice<'a> {
impl Drop for Shared {
fn drop(&mut self) {
self.halt(None, false);
// The blocks the consumer still holds go back to the pool, for the core to free. No
// buffer of them is left: each holds a handle of the device.
self.claims
.get_mut()
.unwrap_or_else(PoisonError::into_inner)
.clear();
let threads = self.take_threads();
// The blocks the consumer still holds go back to the pool once the threads have stopped,
// for the core to free. No buffer of them is left: each holds a handle of the device.
let claims = std::mem::take(
self.claims
.get_mut()
.unwrap_or_else(PoisonError::into_inner),
);
let teardown = move |core: &Arc<Core>| {
halt(core, threads, None, false);
drop(claims);
};
if role(&self.core) == Role::Complete {
// A handler or listener dropped the last handle: the reaper tears down, once the
// handler returns and the completion thread can end.
self.core.reaper.give(Job::Teardown(Box::new(teardown)));
} else {
teardown(&self.core);
}
}
}
@@ -636,6 +704,8 @@ impl Drop for Core {
memory::free(self, memory);
}
self.recorders.destroy_all(&self.device);
// The reaper has ended; what it was given since is freed here.
self.reaper.drain(self);
// SAFETY: the device is idle, and nothing made from it is left but these objects.
let zero_source = unsafe {
self.done.destroy(&self.device);
+7 -5
View File
@@ -4,6 +4,7 @@
use crate::counters::Gauge;
use crate::device::{lock, Core, Device};
use crate::error::Error;
use crate::reaper::{Free, Job};
use ash::vk;
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
@@ -282,10 +283,11 @@ impl EventInner {
impl Drop for EventInner {
fn drop(&mut self) {
// SAFETY: no pending GPU work names the semaphore: every command buffer that waits on it
// or signals it holds the event until it retires, and the completion thread holds it
// while its signals are pending.
unsafe { self.core.device.destroy_semaphore(self.semaphore, None) };
self.core.counters.fall(Gauge::Events);
// No pending GPU work names the semaphore: every command buffer that waits on it or
// signals it holds the event until it retires, and the completion thread holds it while
// its signals are pending. The reaper destroys it, off the completion thread.
self.core
.reaper
.give(Job::Free(Free::Semaphore(self.semaphore)));
}
}
+1
View File
@@ -21,6 +21,7 @@ pub mod floor;
mod instance;
mod memory;
mod queue;
mod reaper;
mod record;
mod submit;
#[cfg(test)]
+112
View File
@@ -0,0 +1,112 @@
//! The reaper thread: it frees what the runtime's other threads give up, one object at a time, and
//! runs a teardown that starts on the completion thread. No driver free runs on the completion
//! thread, so no completion waits behind one, and a submission on another thread waits behind at
//! most one free.
use crate::counters::Gauge;
use crate::device::{lock, Core};
use ash::vk;
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
/// The reaper's queue.
pub(crate) struct Reaper {
state: Mutex<State>,
changed: Condvar,
}
struct State {
jobs: VecDeque<Job>,
/// The reaper ends once the queue is empty.
stop: bool,
}
pub(crate) enum Job {
Free(Free),
/// The device's teardown, after its last handle dropped on the completion thread.
Teardown(Box<dyn FnOnce(&Arc<Core>) + Send>),
}
/// An object whose last user is gone.
pub(crate) enum Free {
/// An event's timeline semaphore; the events gauge falls with it.
Semaphore(vk::Semaphore),
/// A command pool past the idle ones the device keeps, or one whose reset failed.
CommandPool(vk::CommandPool),
}
impl Reaper {
pub(crate) fn new() -> Reaper {
Reaper {
state: Mutex::new(State {
jobs: VecDeque::new(),
stop: false,
}),
changed: Condvar::new(),
}
}
/// Queues a job. Once the reaper has ended, a free waits for the core's drop.
pub(crate) fn give(&self, job: Job) {
lock(&self.state).jobs.push_back(job);
self.changed.notify_one();
}
/// Tells the reaper to end once its queue is empty.
pub(crate) fn stop(&self) {
lock(&self.state).stop = true;
self.changed.notify_one();
}
/// At the core's drop, the reaper having ended: frees what is left. No teardown is left: one
/// holds blocks, and so the core.
pub(crate) fn drain(&self, core: &Core) {
let jobs = std::mem::take(&mut lock(&self.state).jobs);
for job in jobs {
if let Job::Free(object) = job {
free(core, object);
}
}
}
}
/// Frees one object.
fn free(core: &Core, object: Free) {
let device = &core.device;
match object {
Free::Semaphore(semaphore) => {
// SAFETY: no pending work names it: its event's last user, which held it until its
// work retired, is gone.
unsafe { device.destroy_semaphore(semaphore, None) };
core.counters.fall(Gauge::Events);
}
// SAFETY: no command buffer of the pool is pending: its work retired, or never ran.
Free::CommandPool(pool) => unsafe { device.destroy_command_pool(pool, None) },
}
}
/// The reaper thread, until it is stopped and its queue is empty.
pub(crate) fn run(core: Arc<Core>) {
let reaper = &core.reaper;
loop {
let job = {
let mut state = lock(&reaper.state);
loop {
if let Some(job) = state.jobs.pop_front() {
break job;
}
if state.stop {
return;
}
state = reaper
.changed
.wait(state)
.unwrap_or_else(PoisonError::into_inner);
}
};
match job {
Job::Free(object) => free(&core, object),
Job::Teardown(teardown) => teardown(&core),
}
}
}
+12 -14
View File
@@ -2,8 +2,9 @@
//! command buffer (or upload) to the next once its work has completed.
use crate::counters::{Counters, Metric};
use crate::device::lock;
use crate::device::{lock, Core};
use crate::error::Error;
use crate::reaper::{Free, Job};
use ash::vk;
use std::sync::Mutex;
@@ -112,19 +113,22 @@ impl Recorders {
}
/// Takes back a recorder whose work has completed, or that never submitted: its pool is reset
/// for the next one, or destroyed past [`IDLE_MAX`].
pub(crate) fn give_back(&self, device: &ash::Device, mut recorder: Recorder) {
/// for the next one, or, past [`IDLE_MAX`], given to the reaper to destroy.
pub(crate) fn give_back(&self, core: &Core, mut recorder: Recorder) {
// SAFETY: no command buffer of the pool is pending. A failed reset (a lost device) leaves
// the pool to be destroyed.
let reset =
unsafe { device.reset_command_pool(recorder.pool, vk::CommandPoolResetFlags::empty()) };
let reset = unsafe {
core.device
.reset_command_pool(recorder.pool, vk::CommandPoolResetFlags::empty())
};
let mut idle = lock(&self.idle);
if reset.is_ok() && idle.len() < IDLE_MAX {
recorder.used = 0;
idle.push(recorder);
} else {
drop(idle);
destroy(device, recorder);
core.reaper
.give(Job::Free(Free::CommandPool(recorder.pool)));
}
}
@@ -135,14 +139,8 @@ impl Recorders {
.get_mut()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for recorder in idle.drain(..) {
destroy(device, recorder);
// SAFETY: the device is idle; destroying the pool frees its command buffers.
unsafe { device.destroy_command_pool(recorder.pool, None) };
}
}
}
/// Destroys a recorder's pool, which frees its command buffers.
pub(crate) fn destroy(device: &ash::Device, recorder: Recorder) {
// SAFETY: no command buffer of the pool is pending: the device is idle, or the recorder's work
// completed.
unsafe { device.destroy_command_pool(recorder.pool, None) };
}
+2 -2
View File
@@ -139,7 +139,7 @@ impl Work {
blocks: Vec::new(),
},
Err(error) => {
core.recorders.give_back(device, recorder);
core.recorders.give_back(core, recorder);
return Err(error);
}
}
@@ -519,6 +519,6 @@ impl Upload {
/// Recycles the upload's recorder and gives up its blocks: once its submission completed, or
/// where it never went.
pub(crate) fn retire(self, core: &Core) {
core.recorders.give_back(&core.device, self.recorder);
core.recorders.give_back(core, self.recorder);
}
}
+25 -4
View File
@@ -601,11 +601,25 @@ mod on_device {
}
}
/// The last handle dropped in a completed handler: the completion thread finishes the
/// teardown itself once the handler returns.
/// The last handle dropped in a completed handler: the reaper runs the teardown once the
/// handler returns, so the block still held is unmapped and freed there, and every gauge
/// reads zero once the device is destroyed.
#[test]
fn every_device_tears_down_from_a_completed_handler() {
each_device("handler_teardown", |name, _, device| {
let instance = Instance::new(&[]).expect("an instance at the floor");
let devices = devices_of_the_cfgs_kind(&instance);
assert!(!devices.is_empty(), "no device of this cfg's kind");
for (name, physical) in &devices {
let hook = Arc::new(Hook::default());
let options = DeviceOptions {
block_mappings: Some(hook.clone() as Arc<dyn BlockMappings>),
..DeviceOptions::default()
};
let device = Device::new(physical, options).expect("a device");
let counters = device.counters();
let block = device
.take_block(MemoryClass::Shared, 1)
.expect("a Shared block");
let queue = queue(&device);
let command_buffer = queue.command_buffer().expect("a command buffer");
drop(queue);
@@ -614,7 +628,14 @@ mod on_device {
.expect("a handler");
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
});
within("the teardown", || counters.gauges() == Gauges::default());
print_gauges_at_drop("handler_teardown", counters.gauges());
assert_eq!(
*lock(&hook.0),
[(block.id, Some("m2v-reaper".to_string()))],
"{name}: unmapped once, by the reaper"
);
}
}
/// At a loss: a host wait for a pending signal ends false; the command buffer in flight ends