diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 06223237e..1ae61f92d 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -1048,7 +1048,9 @@ impl Drop for DeviceShared { // queues are idle. self.scheduler.release_kept(self.vk()); self.scheduler.release_idle(self.vk()); - // No command buffer is left to give back a spare, or to hold one. + // No command buffer is left to give back a spare, or to hold one; the spare command pools + // whose command buffers the free thread frees are kept again once it did (`spares.rs`). + self.frees.drain(); self.spares.release(self); if let Some(internal) = lock(&self.internal).take() { internal.destroy(self.vk()); diff --git a/crates/metal2vulkan-runtime/src/free_thread.rs b/crates/metal2vulkan-runtime/src/free_thread.rs index 75c52aa33..5751533f4 100644 --- a/crates/metal2vulkan-runtime/src/free_thread.rs +++ b/crates/metal2vulkan-runtime/src/free_thread.rs @@ -13,7 +13,10 @@ //! 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 //! 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. +//! 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, +//! so that a command buffer's completion, which gives its pool back, frees none: the pool goes +//! back among the spares once they are freed. //! - **Not an event's semaphore**, which its release destroys where it goes (`event.rs`): NVIDIA's //! driver runs a `vkCreateSemaphore` behind a `vkDestroySemaphore` another thread runs, so a //! posted destroy moves its cost onto the program's next event and adds to it @@ -22,25 +25,27 @@ //! 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 that finds the queue full, the device's -//! teardown begun, or no thread, is freed where it went. +//! - **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. //! - **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, then asks -//! again; a block whose making would take its heap past the heap's size while frees of that +//! allocation the count's limit leaves no room for waits for the posted frees first (a spare +//! pool's among them), then asks again; a block whose making would take its heap past the heap's size while frees of that //! heap wait, waits for them first, as one whose making failed for room does (`memory.rs`'s //! `place`). Each such wait is counted (`WorkCounts::memory_free_waits`). -//! - **Holds nothing of the device.** The thread holds its queue and a share of the device's -//! functions. The device's teardown waits for every free posted and joins the thread before -//! `vkDestroyDevice`. +//! - **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`. use crate::device::functions::Functions; use crate::device::lock; use crate::exit_guard; +use crate::spares::PoolFrees; use ash::vk; use std::collections::VecDeque; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread::JoinHandle; /// The most frees that wait for the thread (the module docs): a burst of releases longer than @@ -74,7 +79,7 @@ struct Shared { #[derive(Default)] struct State { - queue: VecDeque, + queue: VecDeque, /// Posted and not yet freed: those queued and the one the thread frees now. pending: usize, /// Per memory heap, the bytes posted and not yet freed. @@ -82,6 +87,14 @@ struct State { stopping: bool, } +/// What is posted to the thread. +enum Work { + /// A block's memory. + Block(Posted), + /// A spare command pool's command buffers. + Pool(Box), +} + /// A block's memory, its buffer of addresses and the pages it was imported from, posted to be /// freed. pub(crate) struct Posted { @@ -149,27 +162,57 @@ impl FreeThread { /// The memory and the buffer are the device's, nothing is placed in the memory or bound to /// the buffer, and no pending command reads either. pub(crate) unsafe fn post(&self, posted: Posted) -> Result<(), Posted> { - if !self.started() { - return Err(posted); - } - let mut state = lock(&self.shared.state); - if state.stopping { - return Err(posted); - } - if state.pending >= QUEUE { - drop(state); - self.shared.full.fetch_add(1, Ordering::Relaxed); - return Err(posted); - } + 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.heap_bytes[posted.heap] += posted.size; - state.queue.push_back(posted); + state.queue.push_back(Work::Block(posted)); drop(state); self.shared.posted.fetch_add(1, Ordering::Relaxed); self.shared.work.notify_one(); Ok(()) } + /// Post `frees` to run on the thread, started unless it runs; given back, to run where they + /// were found, where [`post`](Self::post) would give a block back. + /// + /// # Safety + /// + /// As [`PoolFrees::free`]'s. + pub(crate) unsafe fn post_pool(&self, frees: Box) -> Result<(), Box> { + let Ok(mut state) = self.room() else { + return Err(frees); + }; + state.pending += 1; + state.queue.push_back(Work::Pool(frees)); + drop(state); + 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> { + if !self.started() { + return Err(false); + } + let state = lock(&self.shared.state); + if state.stopping { + return Err(false); + } + if state.pending >= QUEUE { + return Err(true); + } + Ok(state) + } + /// [`post`](Self::post) `posted`, or free it on `device` here where it is given back: what /// goes after its memory, for the caller to let go of with no lock held, where it was freed /// here. @@ -213,13 +256,27 @@ impl FreeThread { lock(&self.shared.state).heap_bytes[heap] } - /// Wait until no free posted is left: whether one was, the wait then counted. + /// Wait until no free posted is left: whether one was, the wait then counted as it begins. pub(crate) fn wait(&self) -> bool { + self.wait_for_posted(true) + } + + /// Wait until no free posted is left, uncounted: the device's teardown, before it releases its + /// spare command pools, which those posted keep again (`spares.rs`). + pub(crate) fn drain(&self) { + self.wait_for_posted(false); + } + + /// Wait until no free posted is left: whether one was, the wait counted as it begins where + /// `counted`. + fn wait_for_posted(&self, counted: bool) -> bool { let mut state = lock(&self.shared.state); if state.pending == 0 { return false; } - self.shared.waits.fetch_add(1, Ordering::Relaxed); + if counted { + self.shared.waits.fetch_add(1, Ordering::Relaxed); + } while state.pending > 0 { state = (self.shared.done.wait(state)).unwrap_or_else(PoisonError::into_inner); } @@ -261,14 +318,14 @@ impl FreeThread { } } -/// The thread's loop: free each block posted, in turn, until stopped with none left. +/// The thread's loop: run each free posted, in turn, until stopped with none left. fn run(shared: &Shared) { loop { - let posted = { + let work = { let mut state = lock(&shared.state); loop { - if let Some(posted) = state.queue.pop_front() { - break posted; + if let Some(work) = state.queue.pop_front() { + break work; } if state.stopping { return; @@ -276,23 +333,39 @@ fn run(shared: &Shared) { state = (shared.work.wait(state)).unwrap_or_else(PoisonError::into_inner); } }; - let (heap, size) = (posted.heap, posted.size); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - shared.held.pass(); - // 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); + let freed = match work { + Work::Block(posted) => { + let (heap, size) = (posted.heap, posted.size); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + shared.held.pass(); + // 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)) } - None => std::mem::forget(posted), - } + Work::Pool(frees) => { + // 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; - state.heap_bytes[heap] -= size; + if let Some((heap, size)) = freed { + state.heap_bytes[heap] -= size; + } drop(state); shared.done.notify_all(); } diff --git a/crates/metal2vulkan-runtime/src/spares.rs b/crates/metal2vulkan-runtime/src/spares.rs index 0bb936dd4..1a500d2cb 100644 --- a/crates/metal2vulkan-runtime/src/spares.rs +++ b/crates/metal2vulkan-runtime/src/spares.rs @@ -19,16 +19,27 @@ //! - **A pool's command buffers follow its recent uses.** A pool given back keeps, of each level, //! as many command buffers as the most that one of its last [`RECENT_USES`] uses handed out (a //! secondary at least, below), and frees the rest; and the oldest spare no command buffer took -//! for [`IDLE_FOR`] frees the command buffers it holds as a later give-back finds it -//! ([`take_idle`]), then goes back among the spares as the oldest. A give-back frees at most -//! [`FREED_AT_ONCE`] command buffers, the rest at the next ones: `vkFreeCommandBuffers`, then -//! `vkTrimCommandPool`, which returns what the driver keeps of freed command buffers -//! (`release.rs`'s `PoolBuffers`), on the thread giving the pool back, inside a section of the -//! exit guard. Kept by their peak, a device's pools held, for its life, what the largest command -//! buffer each ever served recorded, and each burst of command buffers at once added pools and -//! filled them: on RADV each command buffer holds 96 KiB of GTT (buffer objects of 80 and 16 -//! KiB) until its pool is trimmed. Counted: `Spares::command_buffers_held` (the crate's tests). -//! A give-back that frees [`FREED_AT_ONCE`] took, in `tests::spares_bench`: on a Radeon 780M +//! for [`IDLE_FOR`] frees every command buffer it holds as a later give-back finds it +//! ([`take_idle`]), then goes back among the spares as the oldest. Kept by their peak, a +//! device's pools held, for its life, what the largest command buffer each ever served recorded, +//! and each burst of command buffers at once added pools and filled them: on RADV each command +//! buffer holds 96 KiB of GTT (buffer objects of 80 and 16 KiB) until its pool is trimmed. +//! Counted: `Spares::command_buffers_held` (the crate's tests). +//! - **Freed on the device's free thread** ([`PoolFrees`], `free_thread.rs`), not on the thread +//! giving the pool back, which for a command buffer that completed is its queue's completion +//! thread before its completed handlers run and its waiters return: [`FREED_AT_ONCE`] command +//! buffers at a time, `vkFreeCommandBuffers` then `vkTrimCommandPool`, which returns what the +//! driver keeps of freed command buffers (`release.rs`'s `PoolBuffers`), each inside a section +//! of the exit guard. The pool stays out of the spares until its frees ran (a command pool needs +//! external synchronization), so a taker meanwhile takes another spare or makes a pool. Where +//! the free thread's queue is full, or the thread cannot start, they run on the giving thread. +//! The device's teardown waits for those posted before it releases the spares. Counted (the +//! crate's tests): `Spares::freed_on`, the threads that freed them. On a Radeon 780M (RADV), in +//! release (`tests::spares_latency`), a give-back that freed a burst's command buffers on the +//! completion thread held the command buffer's first completed handler 1.5 to 1.6 ms at the +//! median after its status read final (2.2 ms at the slowest), and its waiter's return as long; +//! with the frees posted, 6 us and 15 to 17 us (63 us at the slowest). +//! [`FREED_AT_ONCE`] freed and trimmed took, in `tests::spares_bench`: on a Radeon 780M //! (RADV) 18 to 35 us to free them and 0.63 to 0.70 ms at the median to trim (3.0 ms at the //! slowest), which returned their GTT, where the trim of 252 at once took 5.2 to 6.3 ms; on an //! Iris Xe (ANV) 64 to 103 us and 43 to 47 us, the driver keeping their memory for the command @@ -129,7 +140,7 @@ use super::pending_audit::Freeing; use super::release::{self, Released}; use ash::vk; use std::collections::VecDeque; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; /// The most spare descriptor pools a device keeps (of each list, a command buffer's arenas' and @@ -147,8 +158,8 @@ pub(super) const RECENT_USES: usize = 8; /// module docs). pub(super) const IDLE_FOR: Duration = Duration::from_secs(10); -/// The most command buffers a give-back frees (the module docs): their trim's time is the giving -/// thread's. +/// The most command buffers one `vkFreeCommandBuffers` frees, the pool trimmed after each (the +/// module docs). pub(super) const FREED_AT_ONCE: usize = 32; /// The index of `level`'s list in a [`CommandPool`]: primary 0, secondary 1. @@ -196,9 +207,9 @@ impl CommandPool { /// A command buffer gives the pool back at `now`, having handed out what /// [`handed_out`](Self::handed_out) says: its use is noted, and of the command buffers of /// each level past the most one of its last [`RECENT_USES`] uses handed out (of secondaries, - /// past one at least), at most `most`, the last made, are taken out of it, to be freed (the - /// module docs). Those it handed out come first, so none of them is among those. - pub(super) fn given_back(&mut self, now: Instant, most: usize) -> Vec { + /// past one at least), the last made, are taken out of it, to be freed (the module docs). + /// Those it handed out come first, so none of them is among those. + pub(super) fn given_back(&mut self, now: Instant) -> Vec { if self.uses.len() == RECENT_USES { self.uses.pop_front(); } @@ -211,8 +222,7 @@ impl CommandPool { true => used.max(1), false => used, }; - let made = self.made[at].len(); - let from = made - made.saturating_sub(keep).min(most - past.len()); + let from = keep.min(self.made[at].len()); past.extend(self.made[at].drain(from..)); } past @@ -226,13 +236,12 @@ impl CommandPool { holds && since.is_some_and(|since| since >= IDLE_FOR) } - /// At most `most` of the command buffers it holds, taken out of it to be freed, the primary - /// begun ahead first, then the last made: a spare left idle (the module docs). - pub(super) fn shed(&mut self, most: usize) -> Vec { + /// Every command buffer it holds, taken out of it to be freed, the primary begun ahead first: + /// a spare left idle (the module docs). + pub(super) fn shed(&mut self) -> Vec { let mut shed: Vec = self.begun.take().into_iter().collect(); for made in self.made.iter_mut().rev() { - let from = made.len() - made.len().min(most.saturating_sub(shed.len())); - shed.extend(made.drain(from..)); + shed.append(made); } shed } @@ -390,7 +399,13 @@ pub(super) struct DescriptorPool { /// A device's spares. #[derive(Default)] pub(super) struct Spares { - command_pools: Mutex>, + /// Oldest first, shared with the device's free thread, which keeps a pool again once its + /// command buffers are freed ([`PoolFrees`]). + command_pools: Arc>>, + /// The names of the threads that freed spares' command buffers, one each time, for the + /// crate's device tests. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + freed_on: Arc>>, /// The command buffers' arenas', oldest first. descriptor_pools: Mutex>, /// The fitted arenas' (the module docs), oldest first. @@ -438,10 +453,11 @@ impl Spares { /// Keep `pool` of `device`, of a command buffer whose work ended or that was never /// submitted: nothing of it is pending, and nothing else holds it; `settled` where the /// command buffer completed and ended every command buffer of it handed out, so none is - /// recording (the module docs). Its command buffers past its recent uses are freed first, and - /// a pool that made no secondary command buffer makes one. Then the oldest spare no command - /// buffer took for [`IDLE_FOR`] frees its own ([`take_idle`]), [`FREED_AT_ONCE`] in all. - /// Never released here. + /// recording (the module docs). A pool that made no secondary command buffer makes one. Where + /// it holds command buffers past its recent uses, those are freed, and the oldest spare no + /// command buffer took for [`IDLE_FOR`] frees all of its own ([`take_idle`]), each pool out + /// of the spares until its frees ran on the device's free thread ([`PoolFrees`]). Never + /// released here. pub(super) fn give_command_pool( &self, device: &DeviceShared, @@ -457,24 +473,64 @@ impl Spares { } let now = Instant::now(); pool.recording = !settled; - let past = pool.given_back(now, FREED_AT_ONCE); - // SAFETY: nothing of the pool is pending (the caller's), and it is this thread's alone. - unsafe { free_command_buffers(device, pool.raw, &past) }; + let past = pool.given_back(now); pool.stock(device); - let room = FREED_AT_ONCE - past.len(); - let idle = { + let (given, idle) = { let mut pools = lock(&self.command_pools); - keep_command_pool(&mut pools, pool); - (room > 0).then(|| take_idle(&mut pools, now)).flatten() + let idle = take_idle(&mut pools, now); + let given = match past.is_empty() { + true => { + keep_command_pool(&mut pools, pool); + None + } + false => Some(self.frees(pool, past, false)), + }; + let idle = idle.map(|mut pool| { + let shed = pool.shed(); + self.frees(pool, shed, true) + }); + (given, idle) }; - if let Some(mut pool) = idle { - let shed = pool.shed(room); - // SAFETY: nothing of a spare is pending, and it is out of the spares, this thread's. - unsafe { free_command_buffers(device, pool.raw, &shed) }; - keep_idle_command_pool(&mut lock(&self.command_pools), pool); + for frees in given.into_iter().chain(idle) { + // SAFETY: nothing of a pool given back or of a spare is pending, and each is out of + // the spares. + if let Err(frees) = unsafe { device.frees.post_pool(frees) } { + // Inside a section of the exit guard, which this thread may be outside of (a + // command buffer completes on a handler thread). Once the process is exiting, the + // command buffers are left to its end. + if let Some(_busy) = exit_guard::enter() { + // SAFETY: as above. + unsafe { (*frees).free(device.vk()) }; + } + } } } + /// The frees of `buffers`, taken out of `pool`, which goes back among the spares once they + /// ran, the oldest where `idle`, else the newest. + fn frees( + &self, + pool: CommandPool, + buffers: Vec, + idle: bool, + ) -> Box { + Box::new(PoolFrees { + pool, + buffers, + idle, + spares: Arc::clone(&self.command_pools), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + freed_on: Arc::clone(&self.freed_on), + }) + } + + /// The names of the threads that freed spares' command buffers so far, one each time, for + /// the crate's device tests. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(super) fn freed_on(&self) -> Vec { + lock(&self.freed_on).clone() + } + /// The command buffers the spare command pools hold, for the crate's device tests. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(super) fn command_buffers_held(&self) -> usize { @@ -587,21 +643,48 @@ pub(super) unsafe fn release_in_section(device: &DeviceShared, obje unsafe { release::object(device.vk(), object) }; } -/// Free `buffers`, made from `pool` of `device`, and trim the pool, so that the driver returns -/// what it keeps of them (`release.rs`'s `PoolBuffers`, inside a section of the exit guard). Once -/// the process is exiting, they are left to its end. -/// -/// # Safety -/// -/// None of `buffers` is pending, and the caller holds `pool` alone. -unsafe fn free_command_buffers( - device: &DeviceShared, - pool: vk::CommandPool, - buffers: &[vk::CommandBuffer], -) { - if !buffers.is_empty() { - // SAFETY: the caller's. - unsafe { release_in_section(device, release::PoolBuffers(pool, buffers)) }; +/// A command pool out of the spares, and command buffers taken out of it to be freed: those past +/// its recent uses, or all it held as a spare left idle (the module docs). Run on the device's +/// free thread (`free_thread.rs`), else where the frees were found. +pub(crate) struct PoolFrees { + pool: CommandPool, + buffers: Vec, + /// Kept again as the oldest spare (a spare left idle), else as the newest. + idle: bool, + /// The device's spare command pools. + spares: Arc>>, + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + freed_on: Arc>>, +} + +impl PoolFrees { + /// Free the command buffers through `device`, the device's functions taken inside a section of + /// the exit guard, [`FREED_AT_ONCE`] at a time, the pool trimmed after each (`release.rs`'s + /// `PoolBuffers`), then keep the pool among the spares again. + /// + /// # Safety + /// + /// None of the command buffers is pending, and nothing else holds the pool. + pub(crate) unsafe fn free(self, device: &ash::Device) { + let PoolFrees { + pool, + buffers, + idle, + spares, + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + freed_on, + } = self; + for some in buffers.chunks(FREED_AT_ONCE) { + // SAFETY: the caller's. + unsafe { release::object(device, release::PoolBuffers(pool.raw, some)) }; + } + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + lock(&freed_on).push(std::thread::current().name().unwrap_or_default().to_owned()); + let mut pools = lock(&spares); + match idle { + true => keep_idle_command_pool(&mut pools, pool), + false => keep_command_pool(&mut pools, pool), + } } } diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index c323bf7e3..681c94c4a 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -466,6 +466,8 @@ mod sorted_chunks; mod spares; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod spares_bench; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod spares_latency; mod sparse; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod srgb_fetch_images; diff --git a/crates/metal2vulkan-runtime/src/tests/spares.rs b/crates/metal2vulkan-runtime/src/tests/spares.rs index 7da968699..86a8197e6 100644 --- a/crates/metal2vulkan-runtime/src/tests/spares.rs +++ b/crates/metal2vulkan-runtime/src/tests/spares.rs @@ -289,9 +289,9 @@ fn a_spare_command_pool_begins_ahead_out_of_the_spares() { } /// A pool given back keeps, of each level, the command buffers the most one of its last -/// [`RECENT_USES`] uses handed out, a secondary at least, and gives up the rest to be freed, at -/// most the number asked at once: a command buffer of many encoders leaves its pool holding them -/// only until that many smaller ones used it. +/// [`RECENT_USES`] uses handed out, a secondary at least, and gives up the rest to be freed: a +/// command buffer of many encoders leaves its pool holding them only until that many smaller ones +/// used it. #[test] fn a_pool_given_back_keeps_what_its_recent_uses_handed_out() { let primary = vk::CommandBufferLevel::PRIMARY; @@ -303,31 +303,25 @@ fn a_pool_given_back_keeps_what_its_recent_uses_handed_out() { } pool.made(secondary, vk::CommandBuffer::from_raw(1000)); pool.made(secondary, vk::CommandBuffer::from_raw(1001)); - assert!( - pool.given_back(now, usize::MAX).is_empty(), - "its own use's are kept" - ); + assert!(pool.given_back(now).is_empty(), "its own use's are kept"); assert_eq!(pool.held(), 102); // Smaller uses: three primaries each, no secondary. - let small = |pool: &mut CommandPool, most: usize| { + let small = |pool: &mut CommandPool| { pool.taken(); for _ in 0..3 { assert!(pool.reuse(primary).is_some()); } - pool.given_back(now, most) + pool.given_back(now) }; for use_ in 1..RECENT_USES { assert!( - small(&mut pool, usize::MAX).is_empty(), + small(&mut pool).is_empty(), "use {use_}: the large one is among the last" ); } - // The large use leaves the last ones: at most 40 go at once, the last made first. - let past = small(&mut pool, 40); - let expected: Vec<_> = (61..=100u64).map(vk::CommandBuffer::from_raw).collect(); - assert_eq!(past, expected); - let past = small(&mut pool, usize::MAX); - let mut expected: Vec<_> = (4..=60u64).map(vk::CommandBuffer::from_raw).collect(); + // The large use leaves the last ones: every command buffer past them goes. + let past = small(&mut pool); + let mut expected: Vec<_> = (4..=100u64).map(vk::CommandBuffer::from_raw).collect(); expected.push(vk::CommandBuffer::from_raw(1001)); assert_eq!( past, expected, @@ -343,7 +337,7 @@ fn a_pool_given_back_keeps_what_its_recent_uses_handed_out() { } /// The oldest spare no command buffer took for [`IDLE_FOR`] since it was given back, and that -/// holds a command buffer, is taken out of the spares to shed them, the primary begun ahead +/// holds a command buffer, is taken out of the spares to shed them all, the primary begun ahead /// first, and goes back as the oldest, so that a taker takes a spare that still holds its command /// buffers first. #[test] @@ -354,32 +348,30 @@ fn a_spare_left_idle_sheds_its_command_buffers_and_goes_back_the_oldest() { let mut pool = CommandPool::new(vk::CommandPool::from_raw(n), 0); pool.made(primary, vk::CommandBuffer::from_raw(n * 10)); pool.made(primary, vk::CommandBuffer::from_raw(n * 10 + 1)); - assert!(pool.given_back(given, usize::MAX).is_empty()); + assert!(pool.given_back(given).is_empty()); pool }; let mut pools = vec![pool(1, start), pool(2, start + IDLE_FOR / 2)]; pools[0].begun = Some(vk::CommandBuffer::from_raw(19)); let mut empty = CommandPool::new(vk::CommandPool::from_raw(3), 0); - assert!(empty.given_back(start, usize::MAX).is_empty()); + assert!(empty.given_back(start).is_empty()); keep_command_pool(&mut pools, empty); assert!(take_idle(&mut pools, start + IDLE_FOR / 2).is_none()); let mut pool = take_idle(&mut pools, start + IDLE_FOR).expect("the pool given back first"); assert_eq!(pool.raw, vk::CommandPool::from_raw(1)); assert_eq!( - pool.shed(2), + pool.shed(), [ vk::CommandBuffer::from_raw(19), + vk::CommandBuffer::from_raw(10), vk::CommandBuffer::from_raw(11) ], - "the begun primary first, then the last made" + "the begun primary first" ); + assert_eq!(pool.held(), 0); keep_idle_command_pool(&mut pools, pool); let raws: Vec<_> = pools.iter().map(|pool| pool.raw.as_raw()).collect(); assert_eq!(raws, [1, 2, 3], "the oldest"); - let mut pool = take_idle(&mut pools, start + IDLE_FOR).expect("still idle, still holding one"); - assert_eq!(pool.shed(usize::MAX), [vk::CommandBuffer::from_raw(10)]); - assert_eq!(pool.held(), 0); - keep_idle_command_pool(&mut pools, pool); let idle = take_idle(&mut pools, start + 2 * IDLE_FOR).expect("the second"); assert_eq!( idle.raw, @@ -391,7 +383,6 @@ fn a_spare_left_idle_sheds_its_command_buffers_and_goes_back_the_oldest() { #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod device { use super::RECENT_USES; - use crate::spares::FREED_AT_ONCE; use crate::tests::freed_memory::device; use crate::{Buffer, CommandQueue, Device, ResourceOptions}; use std::time::{Duration, Instant}; @@ -402,9 +393,13 @@ mod device { /// The longest a command buffer, or the spares' count, is waited for. const WAIT: Duration = Duration::from_secs(30); - /// Commit a command buffer of `queue` of `encoders` blit encoders, each filling `target`, and - /// wait for it. - fn fills(queue: &CommandQueue, target: &Buffer, encoders: usize) { + /// The device's free thread (`free_thread.rs`). + const FREE_THREAD: &str = "metal2vulkan-frees"; + + /// Commit a command buffer of `queue` of `device` of `encoders` blit encoders, each filling + /// `target`, and wait for it, then for the frees its pool's give-back posted to the device's + /// free thread, so that the next command buffer takes the pool again. + fn fills(device: &Device, queue: &CommandQueue, target: &Buffer, encoders: usize) { let command_buffer = queue.command_buffer().unwrap(); for at in 0..encoders { let mut blit = command_buffer.blit_command_encoder().unwrap(); @@ -413,6 +408,7 @@ mod device { } command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); + device.shared().frees.drain(); } /// The command buffers the device's spare command pools hold once `done` holds of it, or @@ -428,29 +424,37 @@ mod device { } } + /// A burst's command buffers go once the pool's recent uses no longer reach them, freed on + /// the device's free thread, never on the thread that saw a command buffer complete. #[test] - fn command_buffers_the_spares_hold_fall_back_after_a_burst() { + fn command_buffers_the_spares_hold_fall_back_after_a_burst_freed_on_the_free_thread() { let scratch = std::env::temp_dir().join(format!("m2v-spares-{}", std::process::id())); std::fs::create_dir_all(&scratch).unwrap(); let device = device(&scratch); let queue = device.new_command_queue().unwrap(); let target = device.new_buffer(4096, ResourceOptions::private()).unwrap(); - fills(&queue, &target, 1); + fills(&device, &queue, &target, 1); let before = held_once(&device, |held| held > 0); - fills(&queue, &target, BURST); + fills(&device, &queue, &target, BURST); let burst = held_once(&device, |held| held >= before + BURST / 2); - // The burst's use leaves the pool's recent uses after as many more, and the give-backs - // from then on free what it made, a few at each. - let more = RECENT_USES + BURST.div_ceil(FREED_AT_ONCE); + // The burst's use leaves the pool's recent uses after as many more, and the give-back + // then frees what it made. + let more = RECENT_USES + 1; for _ in 0..more { - fills(&queue, &target, 1); + fills(&device, &queue, &target, 1); } let after = held_once(&device, |held| held <= before + 2); + let freed_on = device.shared().spares.freed_on(); println!( "SPARES {}: command buffers the spares hold: {before} after a command buffer of one \ - blit encoder, {burst} after one of {BURST}, {after} after {more} more of one", + blit encoder, {burst} after one of {BURST}, {after} after {more} more of one; freed \ + on {freed_on:?}", device.name() ); + assert!( + !freed_on.is_empty() && freed_on.iter().all(|name| name == FREE_THREAD), + "the spares' command buffers were freed on {freed_on:?}, not on {FREE_THREAD} alone" + ); assert!( burst >= before + BURST / 2, "the burst's command buffer left {burst} where one encoder's left {before}" diff --git a/crates/metal2vulkan-runtime/src/tests/spares_latency.rs b/crates/metal2vulkan-runtime/src/tests/spares_latency.rs new file mode 100644 index 000000000..4776400b6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/spares_latency.rs @@ -0,0 +1,132 @@ +//! How long a command buffer's completion takes to reach its completed handlers and its waiter +//! where its command pool's give-back frees command buffers (`spares.rs`): a command buffer of +//! [`BURST`] blit encoders fills its pool, then [`RECENT_USES`] command buffers of one encoder +//! each take the pool again, the last of them the one whose give-back frees the burst's command +//! buffers. Each command buffer's status is read on a thread of its own from its commit until it +//! reads final; the time from then to its first completed handler, and to its waiter's return, is +//! taken for that last command buffer and for those before it, whose give-backs free none. Each +//! round waits [`SETTLE`] after its burst and after its last command buffer, so that what a +//! give-back left to the device's free thread ran before the next command buffer takes the pool. +//! +//! Printed (`SPARES-LATENCY`): the medians and slowest of both, and the rounds whose burst's +//! command buffers went from the spares. Ignored: run it alone, by name, under `--cfg m2v_gpu` +//! (or `m2v_cpu_icd`), in release: +//! `cargo nextest run -p metal2vulkan-runtime --lib --release --run-ignored all spares_latency +//! --no-capture`. + +use crate::spares::RECENT_USES; +use crate::tests::freed_memory::device; +use crate::{Buffer, CommandBufferStatus, CommandQueue, ResourceOptions}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// The blit encoders of each round's burst. +const BURST: usize = 64; + +/// The rounds. +const ROUNDS: usize = 32; + +/// The longest a command buffer is waited for. +const WAIT: Duration = Duration::from_secs(30); + +/// How long a round waits after its burst and after its last command buffer. +const SETTLE: Duration = Duration::from_millis(50); + +/// Commit a command buffer of `queue` of `encoders` blit encoders, each filling `target`, and +/// wait for it: the time from its status reading final, on a thread that reads it from the +/// commit on, to its first completed handler, and to the wait's return. +fn measured(queue: &CommandQueue, target: &Buffer, encoders: usize) -> (Duration, Duration) { + let command_buffer = queue.command_buffer().unwrap(); + for at in 0..encoders { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(target, 0..4096, at as u8).unwrap(); + blit.end_encoding().unwrap(); + } + let handled = Arc::new(Mutex::new(None)); + let handler = Arc::clone(&handled); + command_buffer + .add_completed_handler(Box::new(move |_| { + *handler.lock().unwrap() = Some(Instant::now()); + })) + .unwrap(); + let watched = command_buffer.clone(); + let watch = std::thread::spawn(move || loop { + let status = watched.status(); + if matches!( + status, + CommandBufferStatus::Completed | CommandBufferStatus::Error + ) { + return Instant::now(); + } + std::hint::spin_loop(); + }); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let returned = Instant::now(); + let final_at = watch.join().unwrap(); + let handled = + (handled.lock().unwrap()).expect("its completed handlers ran before its waiter returned"); + ( + handled.saturating_duration_since(final_at), + returned.saturating_duration_since(final_at), + ) +} + +/// The median and slowest of `times`, in microseconds. +fn spread(times: &mut [Duration]) -> String { + times.sort_unstable(); + let us = |time: Duration| time.as_secs_f64() * 1e6; + format!( + "median {:.1} us, slowest {:.1} us", + us(times[times.len() / 2]), + us(times[times.len() - 1]) + ) +} + +#[test] +#[ignore = "a measurement: run alone on its device by name"] +fn spares_latency() { + let scratch = std::env::temp_dir().join(format!("m2v-spares-latency-{}", std::process::id())); + std::fs::create_dir_all(&scratch).unwrap(); + let device = device(&scratch); + let queue = device.new_command_queue().unwrap(); + let target = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let (mut none_handler, mut none_wait) = (Vec::new(), Vec::new()); + let (mut freeing_handler, mut freeing_wait) = (Vec::new(), Vec::new()); + let mut freed = 0; + for _ in 0..ROUNDS { + measured(&queue, &target, BURST); + std::thread::sleep(SETTLE); + let held = device.shared().spares.command_buffers_held(); + for use_ in 1..=RECENT_USES { + let (handler, wait) = measured(&queue, &target, 1); + match use_ == RECENT_USES { + true => { + freeing_handler.push(handler); + freeing_wait.push(wait); + } + false => { + none_handler.push(handler); + none_wait.push(wait); + } + } + } + std::thread::sleep(SETTLE); + if device.shared().spares.command_buffers_held() + BURST / 2 <= held { + freed += 1; + } + } + println!( + "SPARES-LATENCY {}: {ROUNDS} rounds, the burst's command buffers gone from the spares \ + after {freed}; from the status reading final to the first completed handler: give-backs \ + that free none {}, the give-back that frees the burst's {}; to the waiter's return: {} \ + and {}", + device.name(), + spread(&mut none_handler), + spread(&mut freeing_handler), + spread(&mut none_wait), + spread(&mut freeing_wait), + ); + drop((target, queue, device)); + let _ = std::fs::remove_dir_all(&scratch); +}