From 6898b52edf044bf734ed93b91a2866c3b70b8a14 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:16:00 +0300 Subject: [PATCH] Hold freed memory for the program's own with_vk_queue submissions, and tear the device down on its own thread On drivers that park freed memory (MoltenVK among them), memory freed while the program's own with_vk_queue submissions may still use it now waits for them, by a mark each use signals. The watch of those marks and the release of freed memory hold only the device parts they use, never the device, and teardown closes the parking first and waits for the handler threads: the program's last drop tears the device down on its own thread before it returns, as Metal's last release does (vkDestroyDevice needs external synchronization and every child object destroyed first). freed_memory.rs is listed among the modules that may keep the device's functions, with that reason. Verified: the freed-memory and teardown tests on ANV, lavapipe and the M3 through MoltenVK (14 of 14 each), the two teardown tests fail without the fix, and the presenting test that crashed in the batch passed 20 of 20 on the M3. Folds in: - Hold MoltenVK's freed memory for the program's own with_vk_queue submissions, by a mark each use signals - Hold nothing of the device in the watch of the program's marks and the releases of freed memory - List freed_memory.rs among the modules that keep the device's functions --- .../metal2vulkan-runtime/src/contexts/mod.rs | 9 + crates/metal2vulkan-runtime/src/device/mod.rs | 42 +- .../metal2vulkan-runtime/src/device/relay.rs | 100 +++-- .../src/driver_defects.rs | 3 + .../metal2vulkan-runtime/src/freed_memory.rs | 373 ++++++++++++++++-- crates/metal2vulkan-runtime/src/interop.rs | 17 +- .../src/tests/exit_guard.rs | 7 + .../src/tests/freed_memory.rs | 124 +++++- .../src/tests/teardown_threads.rs | 100 +++++ docs/API.md | 5 +- docs/FAST-PATHS.md | 3 +- 11 files changed, 702 insertions(+), 81 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/contexts/mod.rs b/crates/metal2vulkan-runtime/src/contexts/mod.rs index 751e231b2..a26b2196a 100644 --- a/crates/metal2vulkan-runtime/src/contexts/mod.rs +++ b/crates/metal2vulkan-runtime/src/contexts/mod.rs @@ -95,6 +95,8 @@ struct Shared { /// The notifies made, and those spared as no thread slept or no line was ready. woke: AtomicU64, spared: AtomicU64, + /// The identity the next context takes ([`Contexts::fresh`]). + next: AtomicU64, } struct State { @@ -144,6 +146,7 @@ impl Contexts { wake: Condvar::new(), woke: AtomicU64::new(0), spared: AtomicU64::new(0), + next: AtomicU64::new(0), census: Arc::new(Census { count: Mutex::new(Count { threads: 1, @@ -157,6 +160,12 @@ impl Contexts { Ok(Contexts { shared }) } + /// A context's identity, each call a new one: a logical queue's, or a release's of its own + /// (`Device::let_go_elsewhere`). + pub(crate) fn fresh(&self) -> u64 { + self.shared.next.fetch_add(1, Ordering::Relaxed) + } + /// Append `item` to the context of logical queue `queue`; start a thread when a context is /// ready that no free thread will take, below the cap. pub(crate) fn post(&self, queue: u64, item: I) { diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 210651284..6913bed54 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -164,8 +164,9 @@ pub(super) struct DeviceShared { /// The instance outlives the device. pub(super) instance: Arc, pub(super) physical: vk::PhysicalDevice, - /// The device's functions: through [`DeviceShared::vk`] only. - functions: Functions, + /// The device's functions: through [`DeviceShared::vk`] only, or a share that holds nothing + /// of the device ([`DeviceShared::functions`]). + functions: Arc, /// The primary queue family: its first queue's, where internal submissions go. pub(super) queue_family: u32, /// The `VkQueue`s the runtime submits to, the primary family's first queue first: at least @@ -174,9 +175,6 @@ pub(super) struct DeviceShared { /// The families of those queues, the primary first, each once: what the device's buffers and /// images are shared among (`sharing.rs`). pub(super) queue_families: Vec, - /// The identity the next logical queue takes, or the next release's context of its own - /// ([`Device::let_go_elsewhere`]). - next_queue: AtomicU64, /// How many of `queues`, the first, logical queues share round robin; the rest are reserved /// for presenting queues. round_robin: usize, @@ -201,7 +199,9 @@ pub(super) struct DeviceShared { /// The alignment of every upload (`upload.rs`): 16 bytes, and the device's storage and /// uniform buffer offset alignments. pub(super) upload_alignment: u64, - pub(super) memory: Mutex, + /// Shared with the releases of freed memory posted to the handler threads, which hold + /// nothing of the device (`freed_memory.rs`). + pub(super) memory: Arc>, pub(super) addresses: Mutex, /// The resource IDs of textures and sampler states (`resource_ids.rs`). pub(super) resource_ids: Arc>, @@ -470,6 +470,13 @@ impl DeviceShared { self.functions.get() } + /// A share of the device's functions, which holds nothing of the device: for the releases + /// posted to its handler threads, which its teardown waits for (`freed_memory.rs`). Reached + /// through [`Functions::get`] alone, as [`vk`](Self::vk) reaches them. + pub(crate) fn functions(&self) -> Arc { + Arc::clone(&self.functions) + } + /// What its encoders' deferred command buffers' replays share, where it records them so /// (`recorder`). pub(crate) fn recorder(&self) -> Option<&Arc> { @@ -566,6 +573,12 @@ impl Drop for DeviceShared { let Some(_busy) = exit_guard::enter() else { return; }; + // The watch of the program's marks and the releases of freed memory, posted to the + // handler threads, hold nothing of the device: those that begin from here on call + // nothing, and the threads' stop below waits for those running (`freed_memory.rs`). + if let Some(parking) = self.parking.get() { + parking.close(); + } // The draws the snapshot's area rule weighed since the last line (`reader_sizes.rs`). if let Some(text) = lock(&self.reader_sizes).last_line() { let sink = self.instance.sink(); @@ -603,6 +616,10 @@ impl Drop for DeviceShared { release::object(self.vk(), fence); } } + // Nor the marks of the program's uses of the queues (`freed_memory.rs`). + if let Some(parking) = self.parking.get() { + parking.release(self.vk()); + } // No fence is pending either: each command buffer's was given back as it finished. self.fences.release(self.vk()); // Nor a timestamp slot: each command buffer gave its slot back as it finished, or @@ -864,14 +881,13 @@ impl Device { /// and a context of its own. The handle of the pool holds nothing of the device, so what holds /// the device can be posted with no handle of it taken here. pub(crate) fn elsewhere(&self) -> (Contexts, u64) { - let context = self.0.next_queue.fetch_add(1, Ordering::Relaxed); - (self.0.contexts.clone(), context) + (self.0.contexts.clone(), self.0.contexts.fresh()) } /// A new logical queue's identity, and the index of the `VkQueue` it submits to: round /// robin over the device's queues that are not reserved for presenting. pub(super) fn next_queue(&self) -> (u64, usize) { - let id = self.0.next_queue.fetch_add(1, Ordering::Relaxed); + let id = self.0.contexts.fresh(); let made = self.0.round_robin_made.fetch_add(1, Ordering::Relaxed); (id, (made % self.0.round_robin as u64) as usize) } @@ -883,7 +899,7 @@ impl Device { if reserved == 0 { return None; } - let id = self.0.next_queue.fetch_add(1, Ordering::Relaxed); + let id = self.0.contexts.fresh(); let made = self.0.presenting_made.fetch_add(1, Ordering::Relaxed); Some((id, self.0.round_robin + (made % reserved as u64) as usize)) } @@ -1513,12 +1529,11 @@ impl Device { let shared = Arc::new(DeviceShared { instance, physical, - functions, + functions: Arc::new(functions), queue_family, round_robin: queues.len() - present_queues, queues, queue_families, - next_queue: AtomicU64::new(0), round_robin_made: AtomicU64::new(0), presenting_made: AtomicU64::new(0), compile, @@ -1530,7 +1545,7 @@ impl Device { views_epoch: AtomicU64::new(0), device_address, upload_alignment, - memory: Mutex::new(memory), + memory: Arc::new(Mutex::new(memory)), addresses: Mutex::new(AddressSpace::new()), resource_ids, identifiers: Arc::default(), @@ -1634,6 +1649,7 @@ impl Device { // but on MoltenVK, whose wait for any of several semaphores loses a signal that lands // while it registers a later one (`command_buffer/completion.rs`). if !moltenvk { + (shared.scheduler).wait_on_gpu(Functions::clone(&shared.functions), shared.nudge); } let device = Device(shared); // The pages its replays held last go on its handler threads (`recorder`). diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs index 7e6550732..5efebf73e 100644 --- a/crates/metal2vulkan-runtime/src/device/relay.rs +++ b/crates/metal2vulkan-runtime/src/device/relay.rs @@ -415,47 +415,91 @@ impl super::DeviceShared { /// `f` with `VkQueue` `queue` under its lock: a use outside a batch, `by`'s. Where the /// queue's failures are relayed, a submission of no work after `f`'s, under the same lock, /// signals a fence logged as `by`'s, which ends where `f`'s submissions end (the module - /// docs); the marks before it whose fences are signaled go back first. Each reach of the + /// docs); the marks before it whose fences are signaled go back first. Where freed memory + /// waits for the work in flight, the program's use takes a value of the queue's timeline of + /// such marks before `f` runs, which that submission signals too (`freed_memory.rs`); should + /// the submission fail, the value counts as reached once the queue is idle. Each reach of the /// device is a section of the exit guard of its own (`f` runs outside one: it may be the /// program's); once the process is exiting no mark is made. pub(crate) fn use_queue(&self, queue: usize, by: By, f: impl FnOnce(vk::Queue) -> R) -> R { let slot = &self.queues[queue]; - let Some(flights) = slot.flights.get() else { + let flights = slot.flights.get(); + let parking = (self.parking.get()).filter(|_| matches!(by, By::Program)); + if flights.is_none() && parking.is_none() { return slot.with(f); - }; - let fence = exit_guard::enter().and_then(|_busy| { - let raw = self.vk(); - let mut done = flights.done_marks(); - if !done.is_empty() { - // SAFETY: each is signaled, its submission completed, and out of the log. - let reset = unsafe { raw.reset_fences(&done) }; - exit_guard::called(Call::ResetFences); - // Kept idle where reset; the rest, and all where the reset failed, released. - if reset.is_ok() { - self.fences.keep(&mut done); + } + let fence = flights.and_then(|flights| { + exit_guard::enter().and_then(|_busy| { + let raw = self.vk(); + let mut done = flights.done_marks(); + if !done.is_empty() { + // SAFETY: each is signaled, its submission completed, and out of the log. + let reset = unsafe { raw.reset_fences(&done) }; + exit_guard::called(Call::ResetFences); + // Kept idle where reset; the rest, and all where the reset failed, released. + if reset.is_ok() { + self.fences.keep(&mut done); + } + for fence in done { + // SAFETY: as above. + unsafe { crate::release::object(raw, fence) }; + } } - for fence in done { - // SAFETY: as above. - unsafe { crate::release::object(raw, fence) }; - } - } - // SAFETY: the device's fences, inside a section. - unsafe { self.fences.take(raw) }.ok() + // SAFETY: the device's fences, inside a section. + unsafe { self.fences.take(raw) }.ok() + }) }); slot.with(|vk_queue| { + // Taken before `f` submits: a block that goes meanwhile waits for the mark. + let mark = parking.and_then(|parking| { + let _busy = exit_guard::enter()?; + parking.program_use(queue, self.vk()) + }); let used = f(vk_queue); - if let (Some(fence), Some(_busy)) = (fence, exit_guard::enter()) { - let raw = self.vk(); + let Some(_busy) = exit_guard::enter() else { + return used; + }; + let raw = self.vk(); + let logged = fence.zip(flights); + if let Some((fence, flights)) = logged { flights.push(fence, by); + } + if fence.is_some() || mark.is_some() { + let signal = mark.map(|(timeline, value)| ([timeline], [value])); + let mut values = vk::TimelineSemaphoreSubmitInfo::default(); + let mut submit = vk::SubmitInfo::default(); + if let Some((timelines, signalled)) = &signal { + values = values.signal_semaphore_values(signalled); + submit = submit.signal_semaphores(timelines).push_next(&mut values); + } + // A mark alone needs a submission of its own; a fence alone none. + let submits = match signal.is_some() { + true => std::slice::from_ref(&submit), + false => &[], + }; self.counts.queue_submitted(0); - // SAFETY: a submission of no work with an unsignaled fence in no pending - // submission; the queue is used under its lock. - let submitted = unsafe { raw.queue_submit(vk_queue, &[], fence) }; + // SAFETY: a submission of no work, with an unsignaled fence in no pending + // submission where it has one, signalling the timeline of marks above every + // value signalled there before where it has one; the queue is used under its + // lock. + let submitted = + unsafe { raw.queue_submit(vk_queue, submits, fence.unwrap_or_default()) }; exit_guard::called(Call::QueueSubmit); if submitted.is_err() { - flights.unpush(fence); - // SAFETY: the failed submission is not pending (as a failed batch's fence). - unsafe { crate::release::object(raw, fence) }; + if let Some((fence, flights)) = logged { + flights.unpush(fence); + // SAFETY: the failed submission is not pending (as a failed batch's + // fence). + unsafe { crate::release::object(raw, fence) }; + } + if let (Some(parking), Some((_, value))) = (parking, mark) { + // The use's submissions completed once the queue is idle (or the device + // is lost); the answer changes nothing. + // SAFETY: the queue is used under its lock. + let _ = unsafe { raw.queue_wait_idle(vk_queue) }; + exit_guard::called(Call::QueueWaitIdle); + parking.program_completed(queue, value); + } } } used diff --git a/crates/metal2vulkan-runtime/src/driver_defects.rs b/crates/metal2vulkan-runtime/src/driver_defects.rs index 51edd8387..2625a02b8 100644 --- a/crates/metal2vulkan-runtime/src/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/driver_defects.rs @@ -234,6 +234,9 @@ pub(super) struct Affected { /// 27.0.1: a bare-Vulkan program freeing an unused buffer's memory while a dispatch through a /// device address waits behind fills fails at once, and `runtime_lane::freed_memory`: known /// broken through 1.4.1. Nothing is refused: the runtime frees such memory once the batches +/// submitted before it completed (`freed_memory.rs`), the program's own submissions through +/// `CommandQueue::with_vk_queue` among them (a mark after each use signals a timeline of its +/// own). /// /// `PushedBufferSizesUnset`: /// - MoltenVK (`MOLTENVK`): a shader's runtime array length of a buffer (`OpArrayLength`) reads diff --git a/crates/metal2vulkan-runtime/src/freed_memory.rs b/crates/metal2vulkan-runtime/src/freed_memory.rs index d1cc26446..699100081 100644 --- a/crates/metal2vulkan-runtime/src/freed_memory.rs +++ b/crates/metal2vulkan-runtime/src/freed_memory.rs @@ -27,21 +27,48 @@ //! (`device/submit.rs`) signal no queue's timeline: each takes a number before its //! `vkQueueSubmit` and gives it back once its submitter saw it complete ([`OwnSubmission`]), //! and a block waits too for every one numbered before it went. Its sparse binds and the -//! staging queue's copies run no pipeline, so no encoder of theirs lists a buffer. The -//! program's own submissions (`CommandQueue::with_vk_queue`) are not waited for: the runtime -//! sees neither what they list nor when they complete. +//! staging queue's copies run no pipeline, so no encoder of theirs lists a buffer. +//! - **And the program's.** The runtime sees neither what the program's own submissions list +//! (`CommandQueue::with_vk_queue`) nor when they complete, so each use of a queue is marked +//! ([`ProgramUses`]): under the queue's lock, before the program's code runs, the use takes the +//! next value of a timeline of the queue's own for such marks, and after it a submission of no +//! work signals that value, which Vulkan's signal order completes after every submission the +//! use made. A block waits too for each queue's value taken before it went: a submission the +//! program made before the block's buffers were destroyed lies in a use that took its value +//! before. While marks are pending a handler thread waits for them ([`Watch`]), and posts the +//! release of the blocks whose values were reached as each completes. A mark whose submission +//! fails is reached once the queue is idle. //! - **Freed off the runtime's completion threads.** A queue's waiter that publishes a value while -//! blocks wait posts their release to a handler thread (`Device::let_go_elsewhere`), which frees -//! the blocks it reached and then lets go of what waited for them; a block whose values were -//! reached as it went is freed at once, where it went. At the device's teardown, its queues -//! idle, every block left is freed (`Memory::destroy`). +//! blocks wait posts their release to a handler thread ([`Unpark`]), which frees the blocks it +//! reached and then lets go of what waited for them; a block whose values were reached as it +//! went is freed at once, where it went. At the device's teardown, its queues idle, every block +//! left is freed (`Memory::destroy`). +//! - **Holding nothing of the device.** The watch and the releases hold only the parts of the +//! device they work with ([`Parts`]), never a handle: posted as the program's wait returns, or +//! after its last use of a queue, one holding a handle would hold the device's last once the +//! program dropped its own, and the device would go on a handler thread after the program's +//! last drop returned, where a consumer that adopted its `VkDevice` destroys it then +//! ("Host access to `device` must be externally synchronized", and every object made from it +//! is destroyed before it: VUID-vkDestroyDevice-device-05137). So the program's last drop tears +//! the device down before it returns, as Metal's last release of a device ends it. The teardown +//! closes the parking first ([`Parking::close`]) and then waits for the handler threads to end +//! (`Contexts::stop`); one that runs after it, on the thread the teardown ran on, finds the +//! parking closed and calls nothing. +use crate::command_buffer::Item; +use crate::contexts::Contexts; +use crate::device::functions::Functions; use crate::device::{lock, Device}; -use crate::exit_guard; +use crate::exit_guard::{self, Call}; +use crate::memory::Memory; use ash::vk; use std::collections::BTreeSet; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Mutex, RwLock, RwLockReadGuard}; +use std::sync::{Arc, Mutex, OnceLock, RwLock, RwLockReadGuard}; +use std::time::Duration; + +/// How long the watch of the program's marks waits at a time, between its checks of the exit. +const WAIT_SLICE: Duration = Duration::from_millis(100); /// A device's record of its batches for the blocks that wait (the module docs). pub(crate) struct Parking { @@ -59,6 +86,29 @@ pub(crate) struct Parking { posted: AtomicBool, /// The device's own submissions: the next one's number, and those in flight. own: Mutex, + /// Per `VkQueue`: the program's uses of it, marked. + program: Box<[ProgramUses]>, + /// A [`Watch`] of the program's marks is posted or running: no other is posted. + watching: AtomicBool, + /// The device's teardown began ([`close`](Self::close)): a watch or release that runs from + /// here on calls nothing. + closed: AtomicBool, + /// The crate's device tests' hold of the watch and the releases as they begin + /// (`tests/teardown_threads.rs`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) held: held::Held, +} + +/// The program's uses of one `VkQueue` (`CommandQueue::with_vk_queue`), each marked by a value +/// of a timeline of their own (the module docs). +#[derive(Default)] +struct ProgramUses { + /// The timeline the marks signal, made at the queue's first marked use. + timeline: OnceLock, + /// The value the last use took, under the queue's lock, before the program's code ran. + taken: AtomicU64, + /// The value through which the marks completed, as the host saw. + completed: AtomicU64, } /// The device's own submissions ([`OwnSubmission`]). @@ -70,11 +120,13 @@ struct Own { in_flight: BTreeSet, } -/// What a block noted as it went: the value of each `VkQueue`'s last batch submitted, and the -/// number the device's next own submission takes. +/// What a block noted as it went: the value of each `VkQueue`'s last batch submitted, the number +/// the device's next own submission takes, and the value each queue's last use by the program +/// took. pub(crate) struct Noted { values: Box<[u64]>, own: u64, + program: Box<[u64]>, } impl Parking { @@ -87,9 +139,26 @@ impl Parking { waiting: AtomicUsize::new(0), posted: AtomicBool::new(false), own: Mutex::new(Own::default()), + program: (0..queues).map(|_| ProgramUses::default()).collect(), + watching: AtomicBool::new(false), + closed: AtomicBool::new(false), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + held: held::Held::default(), } } + /// The device's teardown begins: a watch or release that runs from here on calls nothing + /// (the module docs). + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::SeqCst); + } + + /// Let the tests' hold go once the device's teardown began, or once it was let go already. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn release_once_closed(&self) { + self.held.release_once(&self.closed); + } + /// The gate's read lock, held around a batch's `vkQueueSubmit` and the store of its value /// ([`submitted`](Self::submitted)), inside the queue's lock. pub(crate) fn submitting(&self) -> RwLockReadGuard<'_, ()> { @@ -122,22 +191,104 @@ impl Parking { Noted { values, own: lock(&self.own).next, + program: (self.program.iter()) + .map(|uses| uses.taken.load(Ordering::SeqCst)) + .collect(), } } - /// Whether every `VkQueue`'s timeline reached the value `noted` holds for it, and every own - /// submission numbered before `noted`'s completed. + /// Whether every `VkQueue`'s timeline reached the value `noted` holds for it, every own + /// submission numbered before `noted`'s completed, and every queue's marks of the program's + /// uses reached the value `noted` holds for them. pub(crate) fn reached(&self, noted: &Noted) -> bool { let batches = (self.completed.iter()) .zip(¬ed.values) .all(|(completed, noted)| completed.load(Ordering::SeqCst) >= *noted); + let program = (self.program.iter()) + .zip(¬ed.program) + .all(|(uses, noted)| uses.completed.load(Ordering::SeqCst) >= *noted); batches + && program && lock(&self.own) .in_flight .first() .is_none_or(|first| *first >= noted.own) } + /// A use of `VkQueue` `queue` by the program begins, under the queue's lock, before the + /// program's code runs: the timeline its mark signals and the value it takes; `None` where the + /// timeline cannot be made (the use is then not waited for). Inside a section of the exit + /// guard. + pub(crate) fn program_use( + &self, + queue: usize, + device: &ash::Device, + ) -> Option<(vk::Semaphore, u64)> { + let uses = &self.program[queue]; + let timeline = match uses.timeline.get() { + Some(&timeline) => timeline, + None => { + let mut kind = vk::SemaphoreTypeCreateInfo::default() + .semaphore_type(vk::SemaphoreType::TIMELINE) + .initial_value(0); + let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); + // SAFETY: the device is live and enables `timelineSemaphore`. + let made = unsafe { device.create_semaphore(&info, None) }; + exit_guard::called(Call::CreateSemaphore); + let timeline = made.ok()?; + // Set under the queue's lock, which every use takes: never set before. + let _ = uses.timeline.set(timeline); + timeline + } + }; + Some((timeline, uses.taken.fetch_add(1, Ordering::SeqCst) + 1)) + } + + /// The marks of `VkQueue` `queue`'s uses by the program completed through `value`, as the + /// host saw. + pub(crate) fn program_completed(&self, queue: usize, value: u64) { + self.program[queue] + .completed + .fetch_max(value, Ordering::SeqCst); + } + + /// Each queue's timeline of marks whose last value taken is not yet seen complete, with that + /// value. + fn program_pending(&self) -> Vec<(usize, vk::Semaphore, u64)> { + (self.program.iter().enumerate()) + .filter_map(|(queue, uses)| { + let taken = uses.taken.load(Ordering::SeqCst); + let timeline = *uses.timeline.get()?; + (uses.completed.load(Ordering::SeqCst) < taken).then_some((queue, timeline, taken)) + }) + .collect() + } + + /// After a use of a queue by the program: where its mark, or another, is pending and no watch + /// is posted, post one to a handler thread of `device`'s. + pub(crate) fn watch(&self, device: &Device) { + if self.program_pending().is_empty() || self.watching.swap(true, Ordering::SeqCst) { + return; + } + if let Some(parts) = Parts::of(device) { + parts.post(Box::new(Watch(parts.clone()))); + } + } + + /// Destroy the timelines of the program's marks: the device is torn down, idle. + /// + /// # Safety + /// + /// The timelines are `device`'s, and no submission or wait uses them. + pub(crate) unsafe fn release(&self, device: &ash::Device) { + for uses in &self.program { + if let Some(&timeline) = uses.timeline.get() { + // SAFETY: the caller's. + unsafe { crate::release::object(device, timeline) }; + } + } + } + /// An own submission of `device`'s, from before its `vkQueueSubmit` until the guard drops, /// once its submitter saw it complete (or gave up on it). pub(crate) fn own_submission<'a>(&'a self, device: &'a Device) -> OwnSubmission<'a> { @@ -165,10 +316,47 @@ impl Parking { /// After the host saw a value of a queue's: where blocks wait and no release is posted, post /// one to a handler thread of `device`'s, which frees those whose values were reached. pub(crate) fn after_completion(&self, device: &Device) { - if self.waiting.load(Ordering::SeqCst) == 0 || self.posted.swap(true, Ordering::SeqCst) { - return; + if self.unpark_due() { + if let Some(parts) = Parts::of(device) { + parts.post(Box::new(Unpark(parts.clone()))); + } } - device.let_go_elsewhere(Box::new(Unpark(device.clone()))); + } + + /// Whether a release is to be posted: blocks wait, and none is posted (it is then). + fn unpark_due(&self) -> bool { + self.waiting.load(Ordering::SeqCst) != 0 && !self.posted.swap(true, Ordering::SeqCst) + } +} + +/// The parts of a device that its watch of the program's marks and its releases of freed memory +/// work with ([`Watch`], [`Unpark`]), none of which holds the device (the module docs): its +/// parking, its memory, a share of its functions (reached through [`Functions::get`] alone, as +/// the device's own are), and its handler threads. +#[derive(Clone)] +struct Parts { + parking: Arc, + memory: Arc>, + functions: Arc, + contexts: Contexts, +} + +impl Parts { + /// `device`'s, where it parks freed memory. + fn of(device: &Device) -> Option { + let shared = device.shared(); + Some(Parts { + parking: Arc::clone(shared.parking.get()?), + memory: Arc::clone(&shared.memory), + functions: shared.functions(), + contexts: device.elsewhere().0, + }) + } + + /// Run `held`'s drop on one of the handler threads, in a context of its own. + fn post(&self, held: Box) { + self.contexts + .post(self.contexts.fresh(), Item::Release(held)); } } @@ -187,6 +375,68 @@ impl Drop for OwnSubmission<'_> { } } +/// The watch of the program's marks ([`Parking::watch`]): on a handler thread, it waits for the +/// marks pending, a slice at a time, publishes each queue's value reached, and posts the release +/// of the blocks that waited for them, until none is pending. It ends where the device is lost +/// (the blocks then wait for the device's teardown), once its teardown began, and once the +/// process is exiting. +struct Watch(Parts); + +impl Drop for Watch { + fn drop(&mut self) { + let parking = &*self.0.parking; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + parking.held.pass(); + loop { + if parking.closed.load(Ordering::SeqCst) { + return; + } + let pending = parking.program_pending(); + if pending.is_empty() { + parking.watching.store(false, Ordering::SeqCst); + // A use that found the watch on before the store is seen here. + if parking.program_pending().is_empty() + || parking.watching.swap(true, Ordering::SeqCst) + { + return; + } + continue; + } + let Some(busy) = exit_guard::enter() else { + return; + }; + let raw = self.0.functions.get(); + let (timelines, values): (Vec, Vec) = pending + .iter() + .map(|&(_, timeline, value)| (timeline, value)) + .unzip(); + let info = vk::SemaphoreWaitInfo::default() + .flags(vk::SemaphoreWaitFlags::ANY) + .semaphores(&timelines) + .values(&values); + // SAFETY: the timelines are the device's, live until its teardown, which closed the + // parking before and waits for this watch to end (the module docs). + let waited = unsafe { raw.wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) }; + exit_guard::called(Call::WaitSemaphores); + if !matches!(waited, Ok(()) | Err(vk::Result::TIMEOUT)) { + parking.watching.store(false, Ordering::SeqCst); + return; + } + for &(queue, timeline, _) in &pending { + // SAFETY: as above. + if let Ok(value) = unsafe { raw.get_semaphore_counter_value(timeline) } { + parking.program_completed(queue, value); + } + exit_guard::called(Call::GetSemaphoreCounterValue); + } + drop(busy); + if parking.unpark_due() { + self.0.post(Box::new(Unpark(self.0.clone()))); + } + } + } +} + /// A block's memory waiting for the batches in flight as it went, and what goes after it. pub(crate) struct Parked { pub(crate) noted: Noted, @@ -212,26 +462,35 @@ impl Parked { } /// The release a queue's waiter posts ([`Parking::after_completion`]): on a handler thread, the -/// blocks whose values were reached are freed, and what waited for them goes. -struct Unpark(Device); +/// blocks whose values were reached are freed, and what waited for them goes. Once the device's +/// teardown began it frees nothing: the teardown frees every block left. +struct Unpark(Parts); impl Drop for Unpark { fn drop(&mut self) { - let shared = self.0.shared(); - let Some(parking) = shared.parking.get() else { - return; - }; + let Parts { + parking, + memory, + functions, + .. + } = &self.0; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + parking.held.pass(); // Cleared first: a value published from here on posts another release. parking.posted.store(false, Ordering::SeqCst); + if parking.closed.load(Ordering::SeqCst) { + return; + } // The frees are a section of the exit guard: while the process exits, the blocks stay // to its end (`exit_guard`). let Some(busy) = exit_guard::enter() else { return; }; - let reached = lock(&shared.memory).reached(); + let reached = lock(memory).reached(); let after: Vec> = (reached.into_iter()) - // SAFETY: its values were reached, so every batch that may list it completed. - .filter_map(|parked| unsafe { parked.release(shared.vk()) }) + // SAFETY: its values were reached, so every batch that may list it completed; the + // device lives, its teardown waiting for this release to end (the module docs). + .filter_map(|parked| unsafe { parked.release(functions.get()) }) .collect(); drop(busy); drop(after); @@ -251,3 +510,67 @@ impl Device { lock(&shared.memory).park_by(std::sync::Arc::clone(parking)); } } + +/// The crate's device tests' hold of a device's watch and releases (`tests/teardown_threads.rs`, +/// compiled under the validation crate's GPU safety cfgs alone): while held, each waits as it +/// begins, counted, until the hold is let go. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) mod held { + use crate::device::lock; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Condvar, Mutex}; + use std::time::{Duration, Instant}; + + /// The hold: whether held, and how many wait at it. + #[derive(Default)] + pub(crate) struct Held { + state: Mutex<(bool, usize)>, + changed: Condvar, + } + + impl Held { + /// Hold the watch and the releases that begin from now on. + pub(crate) fn hold(&self) { + lock(&self.state).0 = true; + } + + /// Let them go. + pub(crate) fn release(&self) { + lock(&self.state).0 = false; + self.changed.notify_all(); + } + + /// Let them go once `closed` is set, or once they were let go already. + pub(super) fn release_once(&self, closed: &AtomicBool) { + while !closed.load(Ordering::SeqCst) && lock(&self.state).0 { + std::thread::sleep(Duration::from_millis(1)); + } + self.release(); + } + + /// Wait until `count` wait at the hold, failing past `within`. + pub(crate) fn until_waiting(&self, count: usize, within: Duration) { + let deadline = Instant::now() + within; + let mut state = lock(&self.state); + while state.1 < count { + let left = deadline.saturating_duration_since(Instant::now()); + assert!(!left.is_zero(), "{count} never waited at the hold"); + state = (self.changed.wait_timeout(state, left)) + .unwrap_or_else(std::sync::PoisonError::into_inner) + .0; + } + } + + /// As a watch or release begins: wait while held, counted. + pub(super) fn pass(&self) { + let mut state = lock(&self.state); + state.1 += 1; + self.changed.notify_all(); + while state.0 { + state = + (self.changed.wait(state)).unwrap_or_else(std::sync::PoisonError::into_inner); + } + state.1 -= 1; + } + } +} diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index a00042355..d130dcb64 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -169,10 +169,10 @@ impl CommandQueue { /// and presents (`vkQueuePresentKHR`) go there, externally synchronized as Vulkan requires. /// On MoltenVK, where the runtime relays the driver's command-buffer failures, it submits no /// work with a fence of its own after `f` under the same lock, so a failure of the caller's - /// submissions stays the caller's. There the runtime's frees of its memory wait for its own - /// work in flight, not for the caller's - /// (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`): a submission of the caller's - /// still pending whose pipelines read device addresses may fail. + /// submissions stays the caller's. There the runtime's frees of its memory wait for the work + /// in flight (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), the caller's + /// submissions in `f` among it: that submission of no work also signals a value the use took + /// before `f` ran, and memory that goes while it is pending is freed once it completed. /// /// # Safety /// @@ -183,7 +183,12 @@ impl CommandQueue { let shared = self.device().shared(); let family = shared.queue_family_of(self.vk_queue()); // Where the queue's failures are relayed, a mark after `f`'s submissions keeps a failure - // of theirs the caller's (`device/relay.rs`). - shared.use_queue(self.vk_queue(), By::Program, |queue| f(queue, family)) + // of theirs the caller's (`device/relay.rs`); where freed memory waits for the work in + // flight, it waits for that mark (`freed_memory.rs`). + let used = shared.use_queue(self.vk_queue(), By::Program, |queue| f(queue, family)); + if let Some(parking) = shared.parking.get() { + parking.watch(self.device()); + } + used } } diff --git a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs index 87d936e47..bcc9e6839 100644 --- a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs @@ -1622,6 +1622,7 @@ fn the_device_s_functions_are_reached_through_checked_accessors() { /// tuple field, a type argument or a by-value parameter) fails /// `only_the_listed_modules_keep_the_device_s_functions`; so does a listed module that keeps none /// any more. +const KEEPERS: [(&str, &str); 24] = [ ( "binding.rs", "the push command (vkCmdPushDescriptorSet), a call's parameter (`push_set`) and the \ @@ -1658,6 +1659,12 @@ fn the_device_s_functions_are_reached_through_checked_accessors() { "dynamic_state.rs", "the device's extended dynamic state commands (DeviceShared)", ), + ( + "freed_memory.rs", + "the watch of the program's marks and the release of freed memory, posted to the handler \ + threads; the teardown closes the parking first and waits for those threads, and one that \ + starts after finds the parking closed and calls nothing", + ), ( "generated_commands.rs", "the device's generated-commands loader (DeviceShared)", diff --git a/crates/metal2vulkan-runtime/src/tests/freed_memory.rs b/crates/metal2vulkan-runtime/src/tests/freed_memory.rs index 8c4eed267..aa4be255a 100644 --- a/crates/metal2vulkan-runtime/src/tests/freed_memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/freed_memory.rs @@ -4,6 +4,12 @@ //! released while a batch submitted before it runs keeps its memory, and its deallocator waits, //! until that batch completed, then goes on a handler thread; elsewhere it goes at once, as //! before. The counts show which path ran (`WorkCounts::freed_memory_parked`, +//! `freed_memory_waiting`, `host_deallocators_delayed`). The same release waits too for the +//! program's own submission through `CommandQueue::with_vk_queue` pending as it goes, held back +//! by a timeline semaphore of the program's that the program signals once the release returned. +//! And what a block notes as it goes holds it for the batches, the device's own submissions and +//! the program's uses of a queue made before, and for none after. +//! //! Where a host import goes as its release frees it: its free, then its deallocator, before the //! release returns, on the releasing thread, as Metal runs the deallocator (an M3 Max under macOS //! 27.0.1 ran an unused buffer's deallocator inside its final release, on the releasing thread, @@ -19,6 +25,7 @@ use crate::{ BufferContents, BufferDescriptor, CommandBuffer, CommandBufferStatus, CommandQueue, Device, DeviceKind, DeviceOptions, Error, HostMemory, KeepAlive, ResourceOptions, ShaderCacheOptions, }; +use ash::vk; use std::alloc::Layout; use std::path::{Path, PathBuf}; use std::ptr::NonNull; @@ -58,14 +65,14 @@ impl Drop for Scratch { /// Page-aligned host memory of [`BYTES`], freed when dropped: declared first, after the device /// that used it. -struct Host(NonNull); +pub(super) struct Host(NonNull); impl Host { fn layout() -> Layout { Layout::from_size_align(BYTES, BYTES).unwrap() } - fn new() -> Host { + pub(super) fn new() -> Host { // SAFETY: the layout's size is not zero. let pointer = unsafe { std::alloc::alloc_zeroed(Host::layout()) }; Host(NonNull::new(pointer).unwrap()) @@ -102,14 +109,14 @@ fn device(cache: &Path) -> Device { /// The runs of a deallocator: how many, and the thread of the last. #[derive(Default)] -struct Runs { - count: AtomicUsize, +pub(super) struct Runs { + pub(super) count: AtomicUsize, thread: Mutex>, } /// A no-copy buffer over `host` that no command uses, its deallocator's runs in `runs`; `None`, /// printed, where the device imports no host memory. -fn unused(device: &Device, host: &Host, runs: &Arc) -> Option { +pub(super) fn unused(device: &Device, host: &Host, runs: &Arc) -> Option { let runs = Arc::clone(runs); // SAFETY: the memory outlives the buffer (dropped after the device), and nothing else uses it. let made = unsafe { @@ -325,6 +332,113 @@ fn a_note_holds_a_block_for_the_work_submitted_before_it_alone() { ); drop(later); assert!(parking.reached(&last), "every own submission completed"); + // The program's uses of a queue, marked on a timeline of their own. + let raw = device.shared().vk(); + let (_, first) = parking.program_use(1, raw).expect("the timeline of marks"); + let using = parking.note(); + assert!( + parking.reached(&last), + "a use of the program's after the note" + ); + assert!(!parking.reached(&using), "the program's use in flight"); + let (_, second) = parking.program_use(1, raw).unwrap(); + parking.program_completed(1, first); + assert!( + parking.reached(&using), + "the program's use completed; the later one is after" + ); + let after = parking.note(); + assert!(!parking.reached(&after), "the later use in flight"); + parking.program_completed(1, second); + assert!( + parking.reached(&after), + "every use of the program's completed" + ); + // SAFETY: the timeline is the device's, and no submission or wait uses it. + unsafe { parking.release(raw) }; +} + +/// Where the device parks freed memory, a host import released while the program's own +/// submission through `with_vk_queue` is pending keeps its memory, its deallocator waiting, until +/// that submission completed: the runtime sees neither what it lists nor when it completes, so +/// the use's mark holds the block. The submission waits on a timeline semaphore of the program's, +/// which the program signals once the release returned, so nothing else of the device's is in +/// flight meanwhile. It names none of the buffer's Vulkan objects: the block's buffer of addresses +/// is destroyed as it goes, which Vulkan forbids under a pending command that names it, and +/// MoltenVK fails a pending submission whose pipelines read device addresses whatever buffers it +/// names (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`). +#[test] +fn a_release_waits_for_the_program_s_own_submission_where_the_device_parks_freed_memory() { + let scratch = Scratch::new("program"); + let host = Host::new(); + let device = device(&scratch.0); + device.park_freed_memory(); + let queue = device.new_command_queue().unwrap(); + let runs = Arc::new(Runs::default()); + let Some(buffer) = unused(&device, &host, &runs) else { + return; + }; + // SAFETY: the handles are used only below, while the device lives; nothing here destroys one + // of the runtime's, and the test submits only through `with_vk_queue`. + let vk_device = unsafe { device.raw() }.device; + let mut kind = vk::SemaphoreTypeCreateInfo::default() + .semaphore_type(vk::SemaphoreType::TIMELINE) + .initial_value(0); + let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); + // SAFETY: the device is live and enables `timelineSemaphore`. + let gate = unsafe { vk_device.create_semaphore(&info, None) }.unwrap(); + let waits = [gate]; + let values = [1]; + let stages = [vk::PipelineStageFlags::ALL_COMMANDS]; + let mut timeline = vk::TimelineSemaphoreSubmitInfo::default().wait_semaphore_values(&values); + let submit = vk::SubmitInfo::default() + .wait_semaphores(&waits) + .wait_dst_stage_mask(&stages) + .push_next(&mut timeline); + // SAFETY: the queue is used only inside `f`, under the runtime's lock; the submission waits + // for a value of the program's semaphore that the program signals below. + unsafe { + queue.with_vk_queue(|vk_queue, _| { + vk_device + .queue_submit(vk_queue, &[submit], vk::Fence::null()) + .unwrap() + }) + }; + let before = device.work_counts(); + drop(buffer); + let after = device.work_counts(); + let ran = runs.count.load(Ordering::SeqCst); + eprintln!( + "FREED-MEMORY: at the release, the program's submission pending: parked {}, waiting {}, \ + deallocators delayed {}, run {ran}", + after.freed_memory_parked - before.freed_memory_parked, + after.freed_memory_waiting, + after.host_deallocators_delayed - before.host_deallocators_delayed, + ); + let signal = vk::SemaphoreSignalInfo::default().semaphore(gate).value(1); + // SAFETY: the program's semaphore, signalled above its value, with no signal pending. + unsafe { vk_device.signal_semaphore(&signal) }.unwrap(); + assert_eq!( + ran, 0, + "the deallocator ran while the program's submission before its release was pending" + ); + assert_eq!(after.freed_memory_parked - before.freed_memory_parked, 1); + assert_eq!(after.freed_memory_waiting, 1); + until("the deallocator never ran", || { + runs.count.load(Ordering::SeqCst) == 1 + }); + until("the memory never went", || { + device.work_counts().freed_memory_waiting == 0 + }); + assert_ne!( + *runs.thread.lock().unwrap(), + Some(std::thread::current().id()), + "the deallocator ran on the program's thread" + ); + // SAFETY: the program's semaphore; the submission that waited on it completed (its mark + // did, which the deallocator waited for). + unsafe { vk_device.destroy_semaphore(gate, None) }; +} /// A no-copy buffer over `host` that no command uses, whose deallocator records its run in /// `runs` with the device's live host imports as it ran, once `go` lets it (at most [`WAIT`]); diff --git a/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs b/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs index 86b347abf..9fb1d362f 100644 --- a/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs +++ b/crates/metal2vulkan-runtime/src/tests/teardown_threads.rs @@ -31,6 +31,16 @@ //! buffer of another queue committed after it finished, no thread but the handler's holds the //! device. The handler lets the module go, then the command buffer's release drops the last //! device handle on that thread, whose teardown destroys the module. +//! - **Not a handler thread after the program's use of a queue**: on a device that parks freed +//! memory (`Device::park_freed_memory`), a use of a queue through `with_vk_queue` leaves its +//! mark pending and posts the watch of the marks, held as it begins (`freed_memory::held`). The +//! watch holds nothing of the device, so the program's drops tear the device down on its own +//! thread before the last drop returns; the teardown waits for the watch, let go once the +//! teardown began. +//! - **Nor after a wait, beside a block that waits**: likewise, with a released host import's +//! block waiting for that mark and the release of freed memory that a later command buffer's +//! completion posted, held too, as the program's wait for that command buffer returns. The +//! teardown frees the block and runs its deallocator, before the last drop returns. //! //! The teardown's end is seen through the device's message sink, whose last share the instance //! drops after `vkDestroyInstance`, the teardown's last step: the sink owns a value that, dropped, @@ -41,6 +51,7 @@ //! fixture `validation/fixtures/public/examples/runtime_examples.ll` (`llvm-as`). use super::dispatch_pending as pending; +use super::freed_memory::{unused, Host, Runs}; use crate::device::lock; use crate::device::prime::SHADER; use crate::exit_guard; @@ -57,6 +68,7 @@ use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use std::ffi::CString; use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; use std::sync::mpsc::{self, TryRecvError}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -468,3 +480,91 @@ fn a_host_step_s_own_module_and_the_last_device_go_on_a_handler_thread() { drop(open); ending.on(&[HANDLERS]); } + +/// A thread that lets the hold of `device`'s watch and releases go once its teardown began, or +/// once the test let it go: the teardown waits for what the hold holds. +fn let_go_once_torn_down(device: &Device) -> std::thread::JoinHandle<()> { + let parking = Arc::clone(device.shared().parking.get().expect("the device parks")); + std::thread::spawn(move || parking.release_once_closed()) +} + +/// The program's use of a queue leaves its mark pending; the watch of the marks, held as it +/// begins, holds nothing of the device: the program's drops tear the device down on its own +/// thread before the last drop returns, the teardown waiting for the watch. +#[test] +fn the_watch_of_the_program_s_marks_leaves_the_device_to_the_program_s_thread() { + let scratch = Scratch::new("marks"); + let (device, ending) = watched(&scratch.0); + device.park_freed_memory(); + let parking = Arc::clone(device.shared().parking.get().expect("the device parks")); + let queue = device.new_command_queue().unwrap(); + parking.held.hold(); + // SAFETY: the closure uses the queue for nothing. + unsafe { queue.with_vk_queue(|_, _| ()) }; + parking.held.until_waiting(1, WAIT); + let releasing = let_go_once_torn_down(&device); + drop(queue); + drop(device); + let torn_down = ending.thread.try_recv(); + parking.held.release(); + releasing.join().unwrap(); + assert_eq!( + torn_down, + Ok(program_thread()), + "the device was not torn down on this thread before its last drop returned" + ); + let failures = lock(&ending.failures); + assert!(failures.is_empty(), "failing messages: {:#?}", *failures); +} + +/// A released host import's block waits for the program's mark, which only the held watch sees; +/// a later command buffer's completion posts the release of freed memory, held too, before the +/// program's wait for it returns. Neither holds the device: the program's drops tear it down on +/// its own thread before the last drop returns, freeing the block and running its deallocator. +#[test] +fn a_release_of_freed_memory_leaves_the_device_to_the_program_s_thread() { + let scratch = Scratch::new("unpark"); + let host = Host::new(); + let (device, ending) = watched(&scratch.0); + device.park_freed_memory(); + let parking = Arc::clone(device.shared().parking.get().expect("the device parks")); + let queue = device.new_command_queue().unwrap(); + let runs = Arc::new(Runs::default()); + let Some(import) = unused(&device, &host, &runs) else { + return; + }; + parking.held.hold(); + // SAFETY: the closure uses the queue for nothing. + unsafe { queue.with_vk_queue(|_, _| ()) }; + parking.held.until_waiting(1, WAIT); + drop(import); + assert_eq!( + device.work_counts().freed_memory_waiting, + 1, + "the import's block waits for the mark" + ); + let buffer = floats(&device, [0.0; 64]); + let command_buffer = filling(&queue, &buffer); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + parking.held.until_waiting(2, WAIT); + let releasing = let_go_once_torn_down(&device); + drop((command_buffer, buffer, queue)); + drop(device); + let torn_down = ending.thread.try_recv(); + parking.held.release(); + releasing.join().unwrap(); + assert_eq!( + torn_down, + Ok(program_thread()), + "the device was not torn down on this thread before its last drop returned" + ); + assert_eq!( + runs.count.load(Ordering::SeqCst), + 1, + "the teardown freed the block and ran its deallocator" + ); + let failures = lock(&ending.failures); + assert!(failures.is_empty(), "failing messages: {:#?}", *failures); + drop(host); +} diff --git a/docs/API.md b/docs/API.md index f293ea7d8..d42b33df0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1992,8 +1992,9 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. unnamed holds a table of the live buffers that lists it (its first submission's and its host steps', until it completes; one a rebind encoded again before its first submission, until then); with no keep-alive on MoltenVK (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), while - the batches submitted before the import's memory went are in flight, as MoltenVK fails pending work - that reads device addresses where such memory is freed. With a keep-alive the deallocator runs at + the batches submitted before the import's memory went, and the program's own submissions through + `CommandQueue::with_vk_queue` before it, are in flight, as MoltenVK fails pending work that reads + device addresses where such memory is freed. With a keep-alive the deallocator runs at the release, as Metal's, and the import keeps the keep-alive, which keeps the pages mapped, until it is freed: not announced. Cost: the deallocator runs once every such command buffer lets go of the pages, or those batches diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 0fe5e8cc7..387f41c8d 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -80,8 +80,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | Command buffers that share no resource run one after another, where Metal overlaps them while the GPU has room. | The runtime orders nothing between them and runs at each driver's floor for one completion signal per command buffer; a signal shared by several would hold an earlier one's completion for the later ones' work. | None (timing only) | | On MoltenVK a light queue's command buffer waits for the latest one another queue committed, where Metal waits for none: MoltenVK fences every encoder of every queue device-wide when argument buffers and a residency set are on. | The runtime needs argument buffers, and MoltenVK has no setting for its residency set; `runtime_lane::queue_storms` judges the runtime against Metal under those fences. | None (timing only) | | A `Counting` visibility result of a draw writing more than one color attachment, on ANV (Mesa 26.2.4): Metal's count multiplied by the colors written, not divided back. `Boolean` results stay exact. | The driver counts each sample once per color output (`RuntimeDriverDefect::OcclusionCountPerColorOutput`), no documented Vulkan form counts it once, and a refusal would withhold the Mac2 and Metal3 families. | `VisibilityCountPerColor` (`visibility-count-per-color`) | -| On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) | -| On ANV (Mesa 26.2.4) a render pipeline whose largest stage module, under the consumer's exact forms, passes 400,000 words is retranslated with those forms dropped until it fits: native sampling first, then every module-growing exact answer native. On a large enough module the driver's register allocator reads past its interference bitset and the process faults at pipeline creation. | ANV's `brw` register allocator faults on such modules (`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`), no documented Vulkan form bounds a module's register pressure, and a refusal would withhold the consumer's large fragments. | `ExactFormsOverCompilerLimit` (`exact-forms-over-compiler-limit`) | +| On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, and the program's own submissions through `CommandQueue::with_vk_queue` before it, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) | ## Accuracy switches whose default is Metal's