diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index d3d791049..882c0fce7 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -1866,23 +1866,31 @@ impl Drop for HostImport { // memory's whole life (`VkImportMemoryHostPointerInfoEXT`), so the free is made here too. let posts = delayed.is_none() && (kept.is_some() || releases.iter().any(Release::keeps_alive)); + // A completed command buffer's release that lets go of the import last, while a + // deallocator or a keep-alive waits for its free, posts the free to the device's free + // thread, which paces it (`free_thread.rs`): NVIDIA's driver holds every other thread's + // `vkQueueSubmit` while it frees memory (docs/FAST-PATHS.md, known gaps), and the caller + // learns that the pages may go from what waits, which goes there after the free. + let waits = delayed.is_some() || posts; + let paced = waits && crate::free_thread::posts_imports(); let left = AfterImport { after: Box::new(AfterFree { kept, releases }), delayed, + waits, }; // SAFETY: taken once, here, as the import goes, and never read again. let objects = unsafe { ManuallyDrop::take(&mut self.objects) }; - let going: Box = match objects { + let (going, frees): (Box, bool) = match objects { // No pending command buffer uses the pages: one whose commands used them holds them // until it completed (`rebind.rs`), one that may read a texture's image over them // holds the image, which holds the import (`heap_sets.rs`), and every buffer over them // let go of them. Objects::Fixed(mut imported) => { imported.leave(left); - if posts { + if posts || paced { imported.hold_for_release(); } - Box::new(imported) + (Box::new(imported), true) } // Its objects go with their last holder, here or the last command buffer that read // them (a blit's, which holds them and not the buffer once a rebind or detach @@ -1895,17 +1903,24 @@ impl Drop for HostImport { held.leave(left); // Where a command buffer's blit holds them still, that command buffer holds // the device as the program's, and they go with it. - if posts { + if posts || paced { if let Some(imported) = Arc::get_mut(&mut held) { imported.hold_for_release(); } } - Box::new(held) + (Box::new(held), true) } // Released: nothing to free. - None => left.after, + None => (left.after, false), }, }; + let going = match paced && frees { + true => match post_free(shared, going) { + Ok(()) => return, + Err(going) => going, + }, + false => going, + }; if posts { shared.counts.host_import_release_posted(); // A tuple drops in order: the release, then its count. The release's own handles of @@ -1921,6 +1936,18 @@ impl Drop for HostImport { } } +/// Post `objects`, a host import's going at a completed command buffer's release while a +/// deallocator or a keep-alive waits for their free, each handle of the device they hold a +/// holder's, to the device of `shared`'s free thread (`free_thread.rs`, +/// `WorkCounts::host_import_frees_posted`); given back where it refused them. +fn post_free(shared: &DeviceShared, objects: Box) -> Result<(), Box> { + let posted = crate::free_thread::PostedImport { + objects, + holds: Arc::clone(&shared.holds), + }; + (shared.frees.post_import(posted)).map_err(|posted| posted.objects) +} + /// Counts a host import's release posted to a handler thread (a keep-alive alone waiting for its /// free) run as it drops, after the release. struct PostedDone(Device); @@ -1943,11 +1970,14 @@ pub(super) struct Imported { } /// What a going import leaves with its objects ([`Imported::leave`]): the caller's keep-alive and -/// deallocators, which go once the memory is freed, and the length of a deallocator's pages, -/// announced where the free waits for the batches in flight. +/// deallocators, which go once the memory is freed, the length of a deallocator's pages, +/// announced where the free waits for the batches in flight, and whether a deallocator or a +/// keep-alive waits for the free (a completed command buffer that lets go of the objects last +/// posts their free to the free thread then, `rebind::ImportHold`). pub(super) struct AfterImport { after: Box, delayed: Option, + waits: bool, } impl Imported { @@ -1965,10 +1995,32 @@ impl Imported { *lock(&self.after) = Some(left); } + /// Whether the import went, leaving what waits for the free ([`Imported::leave`]), and a + /// deallocator or a keep-alive among it: its free may go to the free thread then. + pub(super) fn waits_for_free(&mut self) -> bool { + let after = self.after.get_mut().unwrap_or_else(PoisonError::into_inner); + after.as_ref().is_some_and(|after| after.waits) + } + + /// Post the free of `imported`, a completed command buffer's release letting go of it last, + /// to its device's free thread where a deallocator or a keep-alive waits for it + /// (`rebind::ImportHold`); else, or where the thread refuses it, free it here. + pub(super) fn let_go_at_completion(mut imported: Imported) { + if !(crate::free_thread::posts_imports() && imported.waits_for_free()) { + drop(imported); + return; + } + imported.hold_for_release(); + let device = imported.device.clone(); + if let Err(objects) = post_free(device.shared(), Box::new(imported)) { + drop(objects); + } + } + /// Hold the device through a handle the program's last drop waits for, in place of its own /// ([`Device::held_for_release`]), and so the dma-buf imports its pages lie in where they /// alone hold them: the import going, these objects go in a release posted to a handler - /// thread. + /// thread or the free thread. fn hold_for_release(&mut self) { self.device = self.device.held_for_release(); #[cfg(unix)] @@ -1982,7 +2034,7 @@ impl Drop for Imported { .unwrap_or_else(PoisonError::into_inner) .take(); let (after, delayed) = match left { - Some(AfterImport { after, delayed }) => (Some(after), delayed), + Some(AfterImport { after, delayed, .. }) => (Some(after), delayed), None => (None, None), }; // SAFETY: no pending command buffer uses them: an import's own go as the import goes diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 2727a972e..0c48568a4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -6162,9 +6162,15 @@ impl CommandBufferShared { self.device.shared().counts.slot_returned(nanos); // What the commands used goes after the completed handlers, as Metal releases it (a // no-copy buffer's deallocator runs after them), and before the gate opens, so a waiter - // returns after it. Each leaves under the lock and drops without it. + // returns after it, but for the frees of host imports posted to the free thread (below), + // whose deallocators and keep-alives run after their frees there. Each leaves under the + // lock and drops without it. { let _running = Running::enter(self.marker(Step::Release)); + // A host import it lets go of last, a deallocator or a keep-alive waiting for its + // free, is freed on the device's free thread, paced (`free_thread.rs`): this thread + // runs the next command buffers' completed handlers. + let _frees = crate::free_thread::AtCompletion::enter(); // Its live buffers' tables first: a buffer whose last hold goes below then counts // only the tables of other command buffers, which may still reach its pages, as // holding them past its release (`HostPages::released_listed`); this one's wait ends diff --git a/crates/metal2vulkan-runtime/src/free_thread.rs b/crates/metal2vulkan-runtime/src/free_thread.rs index e82d9d563..a60c016d2 100644 --- a/crates/metal2vulkan-runtime/src/free_thread.rs +++ b/crates/metal2vulkan-runtime/src/free_thread.rs @@ -1,5 +1,7 @@ //! The device's free thread: the `vkFreeMemory` of a block of the runtime's own memory that a -//! release let go of runs here, off the releasing thread (`memory.rs`'s `Memory::let_go`). A +//! release let go of runs here, off the releasing thread (`memory.rs`'s `Memory::let_go`), and so +//! does a host import's that a completed command buffer let go of last while a deallocator or a +//! keep-alive waits for it (below), off the thread that runs the completed handlers. A //! driver that unmaps a block's pages as it frees it charges that to the free: on an Apple M3 Max //! an object's release that freed a block took up to 24 ms (a 2048x2048 `Shared` texture's, a //! 16 MiB buffer's, each the last placement in its block). @@ -7,11 +9,16 @@ //! - **What is posted.** A block of the runtime's own memory, pooled or dedicated, whose last //! placement went, with its buffer of addresses, and a block over fresh pages the runtime //! mapped for a buffer (`fresh_pages.rs`), its pages unmapped here once its memory is freed. -//! Never an import of the caller's memory (a no-copy object's, a read-only view of the -//! caller's pages, a guest RAM chunk): Vulkan has "the application must ensure that the -//! imported memory range remains valid and accessible for the lifetime of the imported memory -//! object" (`VkImportMemoryHostPointerInfoEXT`), and the caller may free its pages once the -//! object's release returns, so such an import is freed before the release returns. A block +//! An import of the caller's memory (a no-copy object's, a read-only view of the caller's +//! pages, a guest RAM chunk) only where a completed command buffer's release lets go of it +//! last ([`AtCompletion`]) and a deallocator or a keep-alive waits for its free +//! ([`PostedImport`]): Vulkan has "the application must ensure that the imported memory range +//! remains valid and accessible for the lifetime of the imported memory object" +//! (`VkImportMemoryHostPointerInfoEXT`), and the caller learns that its pages may go from +//! that deallocator or keep-alive, which go here after the free. Any other import is freed +//! where it goes: a program's own release frees it before the release returns, as the caller +//! may free its pages once it returned, and a command buffer's release with nothing waiting +//! frees it before the command buffer's waiters return. A block //! that waits for the batches in flight (`freed_memory.rs`) is freed by the handler thread that //! sees them complete, and posted here where they had completed as it went. And a spare command //! pool's command buffers that a give-back frees (`spares.rs`'s `PoolFrees`), the pool trimmed, @@ -25,8 +32,9 @@ //! resource ID and Metal address go back with the object: the address space is the runtime's //! own (`address.rs`), a pinned address one of its ranges, never a Vulkan device address, and //! no address is captured for replay. So reusing an ID or an address needs no memory freed. -//! - **Bounded.** At most [`QUEUE`] frees wait; a block or a pool's command buffers that find the -//! queue full, the device's teardown begun, or no thread, are freed where they went. +//! - **Bounded.** At most [`QUEUE`] frees wait; a block, a pool's command buffers or an import +//! that find the queue full, the device's teardown begun, or no thread, are freed where they +//! went. //! - **Still counted.** A posted block counts against `maxMemoryAllocationCount` //! (`allocations.rs`) and against its memory heap's size until its `vkFreeMemory` returns. An //! allocation the count's limit leaves no room for waits for the posted frees first (a spare @@ -39,16 +47,22 @@ //! so a run of posted frees back to back would hold the program's submissions for the whole //! run. Never while a caller waits for the posted frees ([`FreeThread::wait`], the device's //! teardown). Counted: `WorkCounts::memory_frees_paced`, `memory_frees_paced_nanos`. -//! - **Holds nothing of the device.** The thread holds its queue, a share of the device's -//! functions and of its spare command pools. The device's teardown waits for the frees posted -//! before it releases the spares ([`FreeThread::drain`]), and for every free posted and joins the -//! thread before `vkDestroyDevice`. +//! - **Holds nothing of the device** but a posted import's objects, which hold it as a holder +//! does (`device/holds.rs`): the program's last drop on a thread of the program's waits for +//! them, and the thread frees them unpaced once that drop stopped the holds. The thread holds +//! its queue, a share of the device's functions and of its spare command pools. The device's +//! teardown waits for the frees posted before it releases the spares ([`FreeThread::drain`]), +//! and for every free posted and joins the thread before `vkDestroyDevice`; where the program's +//! last drop ran on a thread of the runtime's, which waits for nothing, a posted import's +//! objects may hold the device's last share, and the teardown runs here as they go: it frees +//! the blocks and pools still queued in place of the waits, and ends the thread unjoined. use crate::device::functions::Functions; use crate::device::lock; use crate::exit_guard; use crate::spares::PoolFrees; use ash::vk; +use std::cell::Cell; use std::collections::VecDeque; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; @@ -72,8 +86,9 @@ struct Shared { work: Condvar, /// A free completed. done: Condvar, - /// The frees posted so far. + /// The blocks' frees posted so far, and the host imports'. posted: AtomicU64, + imports: AtomicU64, /// The frees run where they went, the queue full. full: AtomicU64, /// The waits for posted frees: an allocation at the count's limit or past its heap's size. @@ -82,14 +97,19 @@ struct Shared { /// nanoseconds they waited. paced: AtomicU64, paced_nanos: AtomicU64, - /// The crate's device tests' hold of each free as it begins, a block's or a spare pool's - /// (`tests/posted_frees.rs`, `tests/spares.rs`). + /// The crate's device tests' hold of each free as it begins, a block's, a spare pool's or a + /// host import's (`tests/posted_frees.rs`, `tests/spares.rs`, + /// `tests/completion_import_frees.rs`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] held: crate::freed_memory::held::Held, /// The crate's device tests' stand-in for how long each block's free takes /// ([`FreeThread::frees_take`]). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] takes: Mutex>, + /// The device's teardown ran on the thread itself, as a posted import's objects went + /// ([`FreeThread::stop`]): the crate's device tests' sign of it. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + stopped_here: std::sync::atomic::AtomicBool, } #[derive(Default)] @@ -110,6 +130,58 @@ enum Work { Block(Posted), /// A spare command pool's command buffers. Pool(Box), + /// A host import's objects. + Import(PostedImport), +} + +/// A host import's objects, posted to be freed as they drop where a completed command buffer's +/// release let go of them last (the module docs, **What is posted**): their `VkBuffer` and +/// memory, then the deallocators and the keep-alive that waited for the free (`buffer.rs`). +pub(crate) struct PostedImport { + /// The objects, each handle of the device they hold a holder's + /// (`Device::held_for_release`). + pub(crate) objects: Box, + /// The device's holds: once its program's last drop stopped them, the thread frees the + /// objects unpaced, as that drop waits for them. + pub(crate) holds: Arc, +} + +thread_local! { + /// A completed command buffer's release of what its commands used runs on this thread now + /// ([`AtCompletion`]). + static AT_COMPLETION: Cell = const { Cell::new(false) }; + /// This thread is a device's free thread. + static FREE_THREAD: Cell = const { Cell::new(false) }; +} + +/// A completed command buffer's release of what its commands used, on this thread, while it lives +/// (`CommandBufferShared::complete`): a host import whose free a deallocator or a keep-alive +/// waits for, let go of last there, is posted to its device's free thread +/// ([`posts_imports`]). +pub(crate) struct AtCompletion { + was: bool, +} + +impl AtCompletion { + /// The release begins. + pub(crate) fn enter() -> AtCompletion { + AtCompletion { + was: AT_COMPLETION.with(|at| at.replace(true)), + } + } +} + +impl Drop for AtCompletion { + fn drop(&mut self) { + AT_COMPLETION.with(|at| at.set(self.was)); + } +} + +/// Whether a host import that goes now, a deallocator or a keep-alive waiting for its free, is +/// posted to the free thread: a completed command buffer's release lets go of it +/// ([`AtCompletion`]), not inside the program's code (a deallocator that release ran). +pub(crate) fn posts_imports() -> bool { + AT_COMPLETION.with(Cell::get) && !exit_guard::in_program_call() } /// A block's memory, its buffer of addresses and the pages it was imported from, posted to be @@ -161,6 +233,7 @@ impl FreeThread { work: Condvar::new(), done: Condvar::new(), posted: AtomicU64::new(0), + imports: AtomicU64::new(0), full: AtomicU64::new(0), waits: AtomicU64::new(0), paced: AtomicU64::new(0), @@ -169,6 +242,8 @@ impl FreeThread { held: crate::freed_memory::held::Held::default(), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] takes: Mutex::new(None), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + stopped_here: std::sync::atomic::AtomicBool::new(false), }), thread: Mutex::new(None), } @@ -218,6 +293,27 @@ impl FreeThread { Ok(()) } + /// Post `posted`, a host import's objects, to be freed on the thread, started unless it runs; + /// given back, to be freed where they went, where [`post`](Self::post) would give a block + /// back. Paced as a block's free. + pub(crate) fn post_import(&self, posted: PostedImport) -> Result<(), PostedImport> { + let mut state = match self.room() { + Ok(state) => state, + Err(full) => { + if full { + self.shared.full.fetch_add(1, Ordering::Relaxed); + } + return Err(posted); + } + }; + state.pending += 1; + state.queue.push_back(Work::Import(posted)); + drop(state); + self.shared.imports.fetch_add(1, Ordering::Relaxed); + self.shared.work.notify_one(); + Ok(()) + } + /// The thread's state with room for one more free, the thread started unless it runs; else /// whether the queue was full, rather than the device's teardown begun or no thread started. fn room(&self) -> Result, bool> { @@ -289,8 +385,20 @@ impl FreeThread { } /// Wait until no free posted is left: whether one was, the wait counted as it begins where - /// `counted`. + /// `counted`. On the thread itself (the device's teardown, where a posted import's objects + /// held its last share: the module docs), free those still queued here instead, unpaced: the + /// one it frees now is the teardown's own. fn wait_for_posted(&self, counted: bool) -> bool { + if FREE_THREAD.with(Cell::get) { + let mut freed = false; + loop { + let Some(work) = lock(&self.shared.state).queue.pop_front() else { + return freed; + }; + free(&self.shared, work, false); + freed = true; + } + } let mut state = lock(&self.shared.state); if state.pending == 0 { return false; @@ -317,6 +425,11 @@ impl FreeThread { ) } + /// The host imports' frees posted so far ([`post_import`](Self::post_import)). + pub(crate) fn imports_posted(&self) -> u64 { + self.shared.imports.load(Ordering::Relaxed) + } + /// The frees that waited first for those before them, and the nanoseconds they waited. pub(crate) fn paced(&self) -> (u64, u64) { let shared = &*self.shared; @@ -339,6 +452,12 @@ impl FreeThread { *lock(&self.shared.takes) = took; } + /// Whether the device's teardown ran on the thread itself ([`stop`](Self::stop)). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn stopped_here(&self) -> bool { + self.shared.stopped_here.load(Ordering::SeqCst) + } + /// The frees posted and not yet run, and whether the thread was started and not yet joined. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn pending(&self) -> (usize, bool) { @@ -347,10 +466,18 @@ impl FreeThread { } /// The device's teardown, before `vkDestroyDevice`: no free is posted from here on, the - /// thread frees every one posted, and ends, joined. + /// thread frees every one posted, and ends, joined; on the thread itself (the module docs), + /// those still queued freed here, and the thread ends unjoined once the teardown returned. pub(crate) fn stop(&self) { lock(&self.shared.state).stopping = true; self.shared.work.notify_all(); + if FREE_THREAD.with(Cell::get) { + self.wait_for_posted(false); + drop(lock(&self.thread).take()); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + self.shared.stopped_here.store(true, Ordering::SeqCst); + return; + } if let Some(handle) = lock(&self.thread).take() { let _ = handle.join(); } @@ -360,6 +487,7 @@ impl FreeThread { /// The thread's loop: run each free posted, in turn, until stopped with none left. fn run(shared: &Shared) { crate::step_aside::mark_a_paced_thread(); + FREE_THREAD.with(|on| on.set(true)); loop { let work = { let mut state = lock(&shared.state); @@ -373,53 +501,75 @@ fn run(shared: &Shared) { state = (shared.work.wait(state)).unwrap_or_else(PoisonError::into_inner); } }; - let freed = match work { - Work::Block(posted) => { - let (heap, size) = (posted.heap, posted.size); - let hurry = || { - let state = lock(&shared.state); - state.stopping || state.waiting > 0 - }; - if let Some(waited) = crate::step_aside::pace(hurry) { - shared.paced.fetch_add(1, Ordering::Relaxed); - let nanos = u64::try_from(waited.as_nanos()).unwrap_or(u64::MAX); - shared.paced_nanos.fetch_add(nanos, Ordering::Relaxed); - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - shared.held.pass(); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - crate::step_aside::own_calls_take(*lock(&shared.takes)); - // The free is a section of the exit guard: while the process exits, the block, - // and the pages it was imported from, stay to its end (`exit_guard`). - match exit_guard::enter() { - Some(busy) => { - // SAFETY: `post`'s contract. - let after = unsafe { posted.free(shared.functions.get()) }; - drop(busy); - drop(after); - } - None => std::mem::forget(posted), - } - Some((heap, size)) - } - Work::Pool(frees) => { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - shared.held.pass(); - // As a block's: while the process exits, the command buffers stay to its end. - if let Some(busy) = exit_guard::enter() { - // SAFETY: `post_pool`'s contract. - unsafe { (*frees).free(shared.functions.get()) }; - drop(busy); - } - None - } - }; - let mut state = lock(&shared.state); - state.pending -= 1; - if let Some((heap, size)) = freed { - state.heap_bytes[heap] -= size; - } - drop(state); - shared.done.notify_all(); + free(shared, work, true); } } + +/// Run `work`, a free posted, paced first where `paced` (the module docs, **Paced**), and count it +/// freed. +fn free(shared: &Shared, work: Work, paced: bool) { + let hurry = || { + let state = lock(&shared.state); + state.stopping || state.waiting > 0 + }; + let pace = |hurry: &dyn Fn() -> bool| { + if !paced { + return; + } + if let Some(waited) = crate::step_aside::pace(hurry) { + shared.paced.fetch_add(1, Ordering::Relaxed); + let nanos = u64::try_from(waited.as_nanos()).unwrap_or(u64::MAX); + shared.paced_nanos.fetch_add(nanos, Ordering::Relaxed); + } + }; + let freed = match work { + Work::Block(posted) => { + let (heap, size) = (posted.heap, posted.size); + pace(&hurry); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + shared.held.pass(); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + crate::step_aside::own_calls_take(*lock(&shared.takes)); + // The free is a section of the exit guard: while the process exits, the block, + // and the pages it was imported from, stay to its end (`exit_guard`). + match exit_guard::enter() { + Some(busy) => { + // SAFETY: `post`'s contract. + let after = unsafe { posted.free(shared.functions.get()) }; + drop(busy); + drop(after); + } + None => std::mem::forget(posted), + } + Some((heap, size)) + } + Work::Pool(frees) => { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + shared.held.pass(); + // As a block's: while the process exits, the command buffers stay to its end. + if let Some(busy) = exit_guard::enter() { + // SAFETY: `post_pool`'s contract. + unsafe { (*frees).free(shared.functions.get()) }; + drop(busy); + } + None + } + Work::Import(PostedImport { objects, holds }) => { + pace(&|| holds.stopping() || hurry()); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + shared.held.pass(); + drop(holds); + // Their free, and the deallocators and keep-alive after it, each find the exit + // themselves (`buffer.rs`). + drop(objects); + None + } + }; + let mut state = lock(&shared.state); + state.pending -= 1; + if let Some((heap, size)) = freed { + state.heap_bytes[heap] -= size; + } + drop(state); + shared.done.notify_all(); +} diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index abea3d5d9..ef157b319 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -543,8 +543,11 @@ unsafe impl Sync for HostParts {} /// A no-copy buffer's deallocator (Metal's block): called once, with the pointer and the length, /// when the buffer is released. It may run on a runtime thread, as Metal's runs on any thread: a /// command buffer's queue's handler thread, where that command buffer's release lets go of the -/// buffer, or, where the release frees the import, the releasing thread before the release -/// returns, as Metal's; never a thread that submits command buffers or sees them complete. A panic +/// buffer; the device's free thread, after the import's free, where that release lets go of the +/// pages' import last (the free paced there, possibly after the command buffer's waiters +/// returned); or, where the program's release frees the import, the releasing thread before the +/// release returns, as Metal's; never a thread that submits command buffers or sees them complete. +/// A panic /// inside it is caught. Given with no keep-alive, it runs once the buffer's import of the pages /// was freed (but for a buffer lying in another live buffer's import, [`HostMemory::new`]), so the /// pages may be unmapped from inside it on; given with one, it runs at the release, possibly while diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 1049319a9..bf7661b2b 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -801,11 +801,36 @@ impl ImportHold { fn retained(self) -> Option> { match self { #[cfg(unix)] - ImportHold::Held(held) => Some(Box::new(held)), + ImportHold::Held(held) => Some(Box::new(Retained::new(held))), #[cfg(unix)] ImportHold::Waiting(held) => held .upgrade() - .map(|held| Box::new(held) as Box), + .map(|held| Box::new(Retained::new(held)) as Box), + } + } +} + +/// A command buffer's hold of a releasable import's objects until it completes +/// ([`ImportHold::retained`]): where its completion's release lets go of them last, the import +/// gone and a deallocator or a keep-alive waiting for their free, the free goes to the device's +/// free thread (`free_thread.rs`, `Imported::let_go_at_completion`). +#[cfg(unix)] +struct Retained(std::mem::ManuallyDrop>); + +#[cfg(unix)] +impl Retained { + fn new(held: Arc) -> Retained { + Retained(std::mem::ManuallyDrop::new(held)) + } +} + +#[cfg(unix)] +impl Drop for Retained { + fn drop(&mut self) { + // SAFETY: taken once, here, as the hold goes, and never read again. + let held = unsafe { std::mem::ManuallyDrop::take(&mut self.0) }; + if let Some(imported) = Arc::into_inner(held) { + Imported::let_go_at_completion(imported); } } } diff --git a/crates/metal2vulkan-runtime/src/tests/completion_import_frees.rs b/crates/metal2vulkan-runtime/src/tests/completion_import_frees.rs new file mode 100644 index 000000000..8646bc5f6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/completion_import_frees.rs @@ -0,0 +1,221 @@ +//! A completed command buffer's release of host imports it holds last (`free_thread.rs`, **What +//! is posted**): where a deallocator waits for the free, the free goes to the device's free +//! thread, and the deallocator runs there after it; where nothing waits, the import is freed +//! before the command buffer's waiters return; and where the program's last drop of the device ran +//! on a thread of the runtime's while such a free waited, the device's teardown runs on the free +//! thread as the import goes, and ends. + +use super::blit_holds::{busy, device, until, Host, Scratch, BYTES, FILLED}; +use crate::{ + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Deallocator, Device, Error, + HostBacking, ResourceOptions, +}; +use std::ptr::NonNull; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +const WAIT: Duration = Duration::from_secs(60); + +/// The name of the thread a deallocator ran on, once it ran. +type RanOn = Arc>>>; + +/// A no-copy buffer over `host`, with a deallocator that notes its thread in `ran_on` where +/// given; `None`, printed, where the device imports no host memory. +fn no_copy(device: &Device, host: &Host, ran_on: Option<&RanOn>) -> Option { + let deallocator = ran_on.map(|ran_on| { + let ran_on = Arc::clone(ran_on); + Box::new(move |_: NonNull, _: u64| { + let name = std::thread::current().name().map(str::to_owned); + *ran_on.lock().unwrap() = Some(name); + }) as Deallocator + }); + // SAFETY: the memory outlives the buffer (dropped after the device), and only the buffer's + // commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + host.memory(), + BYTES as u64, + ResourceOptions::default(), + deallocator, + ) + }; + match made { + Ok(buffer) if buffer.host_backing() == Some(HostBacking::ImportedByPointer) => Some(buffer), + Ok(buffer) => { + eprintln!( + "COMPLETION-IMPORT-FREES: the pages are not imported by their pointer ({:?})", + buffer.host_backing() + ); + None + } + Err(Error::Unsupported(gap)) => { + eprintln!("COMPLETION-IMPORT-FREES: the device imports no host memory: {gap:?}"); + None + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + } +} + +/// A command buffer of `queue`'s that copies a word of `source` into `target`, committed behind +/// fills that keep the queue busy, and scheduled: the busy one, then it, and whether it was still +/// pending as it was scheduled. +fn copy_behind_fills( + queue: &CommandQueue, + source: &Buffer, + target: &Buffer, +) -> (CommandBuffer, CommandBuffer, bool) { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(source, 0, target, 0, 4) + .unwrap(); + blit.end_encoding().unwrap(); + let busy = busy(queue, target); + command_buffer.commit().unwrap(); + command_buffer.wait_until_scheduled().unwrap(); + let pending = command_buffer.status() != CommandBufferStatus::Completed; + (busy, command_buffer, pending) +} + +/// A no-copy buffer released while the command buffer that copies from it is in flight, with a +/// deallocator: that command buffer's completion lets go of the import last, and its free goes to +/// the free thread, where the deallocator runs after it. +#[test] +fn a_completed_release_frees_an_import_a_deallocator_waits_for_on_the_free_thread() { + let scratch = Scratch::new("completion-import-frees-posted"); + let host = Host::new(); + let device = device(&scratch.0); + // The submission checks' own imports and frees, out of the way first. + let _settled = device.settle_submit_checks(WAIT); + let queue = device.new_command_queue().unwrap(); + let ran_on = RanOn::default(); + let Some(buffer) = no_copy(&device, &host, Some(&ran_on)) else { + return; + }; + let target = device + .new_buffer(FILLED, ResourceOptions::private()) + .unwrap(); + let before = device.work_counts(); + let (busy, command_buffer, pending) = copy_behind_fills(&queue, &buffer, &target); + drop(buffer); + let still = command_buffer.status() != CommandBufferStatus::Completed; + command_buffer.wait_until_completed_for(WAIT).unwrap(); + busy.wait_until_completed_for(WAIT).unwrap(); + until("the deallocator never ran", || { + ran_on.lock().unwrap().is_some() + }); + let posted = device.work_counts().host_import_frees_posted - before.host_import_frees_posted; + let thread = ran_on.lock().unwrap().clone().flatten(); + eprintln!( + "COMPLETION-IMPORT-FREES {}: pending at the release {pending}, still after it {still}; \ + posted {posted}, the deallocator ran on {thread:?}", + device.name() + ); + if !(pending && still) { + eprintln!("COMPLETION-IMPORT-FREES: the copy completed before the release: nothing held"); + return; + } + assert_eq!(posted, 1, "the completion's free was not posted"); + assert_eq!(thread.as_deref(), Some("metal2vulkan-frees")); +} + +/// The same release with no deallocator: nothing waits for the free, and the caller may unmap the +/// pages once the command buffer's waiters returned, so the completion frees the import before +/// they return, posting nothing. +#[test] +fn a_completed_release_frees_an_import_nothing_waits_for_before_its_waiters_return() { + let scratch = Scratch::new("completion-import-frees-in-place"); + let host = Host::new(); + let device = device(&scratch.0); + // The submission checks' own imports and frees, out of the way first. + let _settled = device.settle_submit_checks(WAIT); + let queue = device.new_command_queue().unwrap(); + let live = device.work_counts().host_imports_live; + let Some(buffer) = no_copy(&device, &host, None) else { + return; + }; + let target = device + .new_buffer(FILLED, ResourceOptions::private()) + .unwrap(); + let before = device.work_counts(); + let (busy, command_buffer, pending) = copy_behind_fills(&queue, &buffer, &target); + drop(buffer); + let still = command_buffer.status() != CommandBufferStatus::Completed; + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let after = device.work_counts(); + busy.wait_until_completed_for(WAIT).unwrap(); + eprintln!( + "COMPLETION-IMPORT-FREES {} in place: pending at the release {pending}, still after it \ + {still}; imports live {live} before, {} as the wait returned", + device.name(), + after.host_imports_live + ); + assert_eq!( + after.host_import_frees_posted - before.host_import_frees_posted, + 0, + "a free nothing waits for was posted" + ); + assert_eq!( + after.host_imports_live, live, + "the import outlived the command buffer's wait" + ); +} + +/// The program lets go of the buffer, the command buffers, the queue and the device while the +/// copy is in flight: the completion posts the import's free, and the program's last handle goes +/// on the runtime's thread after it, which waits for nothing. With the free thread held until +/// then, the import's objects hold the device's last share, so the teardown runs on the free +/// thread as they go: it frees what it queued in place of waiting for itself, and ends the thread +/// unjoined. +#[test] +fn a_teardown_the_free_thread_meets_as_a_posted_import_goes_ends_it() { + let scratch = Scratch::new("completion-import-frees-teardown"); + let host = Host::new(); + let device = device(&scratch.0); + // The submission checks' own imports and frees, out of the way first. + let _settled = device.settle_submit_checks(WAIT); + let queue = device.new_command_queue().unwrap(); + let ran_on = RanOn::default(); + let Some(buffer) = no_copy(&device, &host, Some(&ran_on)) else { + return; + }; + let target = device + .new_buffer(FILLED, ResourceOptions::private()) + .unwrap(); + let frees = Arc::clone(&device.shared().frees); + let holds = Arc::clone(&device.shared().holds); + frees.held().hold(); + let (busy, command_buffer, pending) = copy_behind_fills(&queue, &buffer, &target); + drop(buffer); + let still = command_buffer.status() != CommandBufferStatus::Completed; + drop((busy, command_buffer, queue, target, device)); + if !(pending && still) { + frees.held().release(); + eprintln!("COMPLETION-IMPORT-FREES: the copy completed before the release: nothing held"); + return; + } + // The completion posted the free, which waits at the hold; the program's last handle went + // after it. + frees.held().until_waiting(1, WAIT); + until("the program's last handle never went", || holds.stopping()); + frees.held().release(); + until("the deallocator never ran", || { + ran_on.lock().unwrap().is_some() + }); + until("the free thread never ended", || { + frees.pending() == (0, false) + }); + eprintln!( + "COMPLETION-IMPORT-FREES teardown: the deallocator ran on {:?}, the teardown on the free \ + thread {}", + ran_on.lock().unwrap().clone().flatten(), + frees.stopped_here() + ); + assert_eq!( + ran_on.lock().unwrap().clone().flatten().as_deref(), + Some("metal2vulkan-frees") + ); + assert!( + frees.stopped_here(), + "the device's last share went elsewhere than the free thread" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs b/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs index 054b83c68..e6e403b76 100644 --- a/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs @@ -705,8 +705,9 @@ fn import_free_hold_bench_completed() { ); } eprintln!( - "IMPORT-FREE-HOLD completed counts: memory_frees_posted {}, memory_frees_paced {} \ - ({:.3} ms waited)", + "IMPORT-FREE-HOLD completed counts: host_import_frees_posted {}, memory_frees_posted {}, \ + memory_frees_paced {} ({:.3} ms waited)", + after.host_import_frees_posted - before.host_import_frees_posted, after.memory_frees_posted - before.memory_frees_posted, after.memory_frees_paced - before.memory_frees_paced, (after.memory_frees_paced_nanos - before.memory_frees_paced_nanos) as f64 / 1e6 diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index a1661ee10..619ce6479 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -68,6 +68,8 @@ mod completion; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod completion_here; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod completion_import_frees; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod completion_latency; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod completion_order; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 63e4736dd..8eee845ca 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5974,8 +5974,10 @@ pub struct WorkCounts { pub memory_free_waits: u64, /// The frees of the device's own threads that free in runs that first waited as long as the /// thread's own frees before them took, less the time since they ended (`step_aside::pace`): - /// the free thread's, the residency thread's and a guest RAM thread's, so that the device's - /// other threads' submissions go between them. A program's own release never waits so. + /// the free thread's (its blocks, and the host imports posted to it, + /// `host_import_frees_posted`), the residency thread's and a guest RAM thread's, so that the + /// device's other threads' submissions go between them. A program's own release never waits + /// so. pub memory_frees_paced: u64, /// The nanoseconds those frees waited, in all. pub memory_frees_paced_nanos: u64, @@ -7878,6 +7880,11 @@ pub struct WorkCounts { /// keep-alives not yet dropped. A program that waits for a keep-alive's drop after its release /// waits until this falls to 0. pub host_import_releases_pending: u64, + /// Imports of host pages whose free a completed command buffer's release posted to the + /// device's free thread, which paces it (`free_thread.rs`): the command buffer let go of them + /// last, their buffers released, while a deallocator or a keep-alive waited for the free, + /// which runs there after it, possibly after the command buffer's waiters returned. + pub host_import_frees_posted: u64, /// Keep-alives of no-copy buffers and heaps (`KeepAlive`) held now past their release: each /// by the import of its pages, whose last buffer it was while something else (a texture's /// image a submitted command buffer may still read, or a buffer bound inside the import, @@ -10345,6 +10352,7 @@ impl Device { .load(Ordering::Relaxed), host_import_releases_pending: (counters.host_import_releases_pending) .load(Ordering::Acquire), + host_import_frees_posted: self.shared().frees.imports_posted(), host_keep_alives_kept: counters.host_keep_alives_kept.load(Ordering::Relaxed), host_keep_alives_covered: counters.host_keep_alives_covered.load(Ordering::Relaxed), host_releases_held_inside: (counters.host_releases_held_inside).load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 8ba7043a6..8bdc36e3c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2976,6 +2976,7 @@ field metal2vulkan-runtime::WorkCounts.host_copy_blocks_readied pub host_copy_bl field metal2vulkan-runtime::WorkCounts.host_deallocators_delayed pub host_deallocators_delayed: u64 field metal2vulkan-runtime::WorkCounts.host_holds_looked_up pub host_holds_looked_up: u64 field metal2vulkan-runtime::WorkCounts.host_import_fds_kept pub host_import_fds_kept: u64 +field metal2vulkan-runtime::WorkCounts.host_import_frees_posted pub host_import_frees_posted: u64 field metal2vulkan-runtime::WorkCounts.host_import_releases_pending pub host_import_releases_pending: u64 field metal2vulkan-runtime::WorkCounts.host_import_releases_posted pub host_import_releases_posted: u64 field metal2vulkan-runtime::WorkCounts.host_imports_held_for_good pub host_imports_held_for_good: u64 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 8cd6006e0..2d1f1bb3f 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -1475,11 +1475,16 @@ driver's. Each is open work. The runtime's own threads pace their runs of frees so: the free thread (its blocks, a buffer's fresh pages among them), the residency thread's releases of idle imports, a guest RAM's give-backs and idle releases, and the submission checks' import tax (`step_aside.rs`, - `WorkCounts::memory_frees_paced`). A program's own release of a no-copy buffer frees its import - in the release, as Metal lets the buffer go there, so a program that releases many at once holds - the device's other submissions for as long as their frees take together; so does a completed - command buffer's handler that frees the imports its blits held last, unpaced, as a wait there - would delay the completed handlers behind it. Not announced. + `WorkCounts::memory_frees_paced`), and so does it for a completed command buffer's release that + lets go of host imports last while a deallocator or a keep-alive waits for their frees: those + frees go to the free thread, paced, and the deallocators and keep-alives run there after them, + possibly after the command buffer's waiters returned (`WorkCounts::host_import_frees_posted`; + where the thread's queue is full, its teardown began or it cannot start, freed in place). A + program's own release of a no-copy buffer frees its import in the release, as Metal lets the + buffer go there, so a program that releases many at once holds the device's other submissions + for as long as their frees take together; so does a completed command buffer's release of + imports nothing waits for, which frees them before its waiters return, unpaced, as the caller + may unmap their pages once they returned. Not announced. - **With unified memory, `Private` memory lies in the system heap's types before the device-local ones, its buffers' blocks there allocated exportable but for buffers that declare their padding unobserved: about 1 µs a submission for each such block held.** Where the device has unified memory and a heap that is not