Files
metal2vulkan/crates/metal2vulkan-runtime/src/program_objects.rs
T
Anees Iqbal 964dc71828 Give a released resource's ranges back inside the passing hold that let go of it last
A texture over a buffer (or in a heap) that the program released while a
runtime thread held it for a moment (a batch writing deferred heap slots,
a new heap set, a storage-form switch: a passing hold, resource_ids.rs)
went only as that thread let go, and its going (and with it the buffer's
address range, a pool's slot, an automatic heap's range) ran after the
hold ended. Buffer, heap and pool makings did not wait at all. So a
buffer pinned where the released buffer lay was refused
PlacementConflict::Held, a buffer in the same pool slot likewise, and a
texture in an automatic heap the released texture filled
OutOfMemory(Heap), where Metal's release had freed them and its making
succeeds.

Now the handles a passing hold took go inside it, as plain drops: a
texture whose last handle one is goes there, with everything only it
held (its buffer, its heap, the texture a view was made of), each giving
back its ID, slot, address range, pool slot and heap range under their
own locks. Only the program's code in such a going waits for the
thread's outermost hold to end: exit_guard::program_release raised
inside a hold is queued and runs once the hold ended (on a handler
thread where the thread serves completion), as messages already did.
Every making that takes what such a going gives back now waits for the
device's passing holds first, as texture and sampler makings did: a
placement in the Metal address space (Device::address_space_for: picks,
pins, pool slots, pool reservations; not Outside, records or shared
ranges) and an automatic heap's range (Heap::allocate). The wait is one
SeqCst load where no hold is under way, and none on a thread inside one.

Texture::id_back_if_last, IdHold::give_back and PassingHold::let_go are
gone: the drop does what they did. Releases deferred off-thread need
Send + 'static closures (host_memory's Deallocation carries the pointer
to the deallocator). In builds with debug assertions a program object
(deallocator, keep-alive, range token, dma-buf source) dropped inside a
passing hold now ends the process, as program code run there already
did, so an implicit drop of one in a going cannot hide.

Tests (tests::passing_holds, device-gated), each forcing the batch's
pause while it holds the texture: a buffer pinned where the released
buffer lay, a pool slot, an automatic heap's range; the existing ID and
deallocator tests kept (the latter now drops the handle inside the hold).

Verified: homelab-ms01-1 lavapipe (job m3-max-6700): clippy -p
metal2vulkan-runtime --all-targets --all-features -D warnings clean;
80/80 of passing_holds, exit_guard, heap_sets, address and the in-place
check's ID-order test. M3 Max MoltenVK --cfg m2v_gpu (m3-max-6707):
78/78 of the same set. Negative control (makings do not wait; lavapipe,
m3-max-6737): the pin and slot tests fail PlacementConflict::Held, the
heap test OutOfMemory(Heap); the ID and deallocator tests pass.

(cherry picked from commit a784e57e52bfdea0db93511f51dba50717ac460b)
2026-11-07 20:29:28 -08:00

118 lines
4.7 KiB
Rust

//! The program's objects a release drops or runs on a runtime thread (a no-copy buffer's or
//! heap's deallocator and keep-alive, a range token, a dma-buf source:
//! `exit_guard::program_release`), counted while the runtime holds them, so that a queue waiter
//! runs a command buffer's transition to `Completed` itself only while it holds none
//! (`CommandBufferShared::finish_here`): that transition's release then reaches none of the
//! program's code, which no thread that sees command buffers complete may run.
//!
//! - **Counted while held.** The runtime holds each in a [`ProgramObject`], from where it takes it to where
//! it drops or runs it, and a `ProgramObject` counts while it lives.
//! - **None held meets such a run.** A waiter counts its run in ([`Unheld::enter`]) before it
//! reads the count, and a release the program gives for objects a pending command buffer may
//! already hold (a rebind's new pages, `rebind.rs`; every no-copy buffer's and heap's release
//! takes the same path) waits, once counted, until no such run is under way ([`settle`]). Both
//! counts are sequentially consistent: in their one order, either the waiter reads the new
//! object counted and leaves the transition to its queue's handler thread, or the release
//! waits for the waiter's run to end. A range token or a dma-buf source is held as its new
//! resource is made, which no pending command buffer holds yet.
use std::cell::Cell;
use std::sync::atomic::{AtomicUsize, Ordering};
/// The program's objects the runtime holds.
static HELD: AtomicUsize = AtomicUsize::new(0);
/// The runs under way that found none held ([`Unheld`]).
static UNHELD: AtomicUsize = AtomicUsize::new(0);
thread_local! {
/// The runs under way on this thread that found none held.
static HERE: Cell<usize> = const { Cell::new(0) };
}
/// One of the program's objects the runtime holds, counted while it lives.
pub(crate) struct ProgramObject<T> {
value: T,
_counted: Counted,
}
/// One count of [`HELD`], taken back when dropped.
struct Counted;
impl Drop for Counted {
/// In builds with debug assertions (every test run), end the process where the object goes
/// inside a passing hold of a device's resources (`resource_ids.rs`): its drop or run is the
/// program's code, which a making on another thread may wait for. A release runs it once the
/// thread's outermost hold ended (`exit_guard::program_release`).
fn drop(&mut self) {
if cfg!(debug_assertions) && crate::resource_ids::inside_passing_hold() {
let name = std::thread::current().name().map(str::to_owned);
eprintln!(
"metal2vulkan: thread {} let go of the program's object inside a passing hold of \
a device's resources, which a making on another thread may wait for",
name.as_deref().unwrap_or("(unnamed)")
);
std::process::abort();
}
HELD.fetch_sub(1, Ordering::SeqCst);
}
}
impl<T> ProgramObject<T> {
/// Hold `value`, counted from now on.
pub(crate) fn new(value: T) -> ProgramObject<T> {
HELD.fetch_add(1, Ordering::SeqCst);
ProgramObject {
value,
_counted: Counted,
}
}
/// The value, to call or clone where it stays held.
pub(crate) fn get(&self) -> &T {
&self.value
}
/// Give the value to `f`, which runs or drops it: counted until `f` returned.
pub(crate) fn run<R>(self, f: impl FnOnce(T) -> R) -> R {
let ProgramObject { value, _counted } = self;
f(value)
}
}
/// A run under way that found none of the program's objects held: none is held for an object a
/// pending command buffer holds until it ends ([`settle`]).
pub(crate) struct Unheld(());
impl Unheld {
/// Count a run in where none of the program's objects is held; `None` where one is.
pub(crate) fn enter() -> Option<Unheld> {
UNHELD.fetch_add(1, Ordering::SeqCst);
if HELD.load(Ordering::SeqCst) != 0 {
UNHELD.fetch_sub(1, Ordering::SeqCst);
return None;
}
HERE.with(|here| here.set(here.get() + 1));
Some(Unheld(()))
}
}
impl Drop for Unheld {
fn drop(&mut self) {
HERE.with(|here| here.set(here.get() - 1));
UNHELD.fetch_sub(1, Ordering::SeqCst);
}
}
/// Wait until no run counted in by [`Unheld::enter`] is under way, once the objects a release
/// gives are held ([`ProgramObject`]) and before anything holds them: a run that read none held ends first. A
/// run on this thread (the program's code it reached, a message sink) is not waited for.
pub(crate) fn settle() {
if HERE.with(Cell::get) != 0 {
return;
}
while UNHELD.load(Ordering::SeqCst) != 0 {
std::thread::yield_now();
}
}