From ac9e2adf622ed7a399fe34b022ede3a30b586744 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 9 Nov 2026 12:31:57 -0800 Subject: [PATCH] Spares: a command pool's command buffers follow its recent uses; idle spares shed theirs A spare command pool kept every command buffer it ever made: each burst of command buffers at once filled its pools, and they held it for the device's life. Mesa recycles freed command buffers into their pool and returns their memory only at vkTrimCommandPool; on RADV each one holds 96 KiB of GTT (buffer objects of 80 and 16 KiB), which the consumer saw grow without end. A pool given back now keeps, of each level, as many command buffers as the most one of its last 8 uses handed out (a secondary at least) and frees the rest; and the oldest spare no command buffer took for 10 s frees what it holds as a later give-back finds it, then goes back as the oldest spare. A give-back frees at most 32: vkFreeCommandBuffers, then vkTrimCommandPool (release.rs's PoolBuffers), inside an exit-guard section, on the giving thread. No vkDestroyCommandPool moves off teardown. The device's priming frees and trims its own command buffers too. The cost of a give-back freeing 32, tests::spares_bench (ignored, run by name): Radeon 780M (RADV) 18 to 35 us to free, 0.63 to 0.70 ms median to trim (3.0 ms slowest), the GTT returned, where 252 at once took 5.2 to 6.3 ms; Iris Xe (ANV) 64 to 103 us and 43 to 47 us; RTX 5080 Laptop (NVIDIA 615.71.09) 4 to 7 us and 0.4 to 48 us (0.22 ms slowest); lavapipe a few microseconds. Verified: tests::spares (CPU tests of the recent-uses and idle rules and a device test that 64 command buffers at once fall back to 2 after 8 + 2 more uses) pass on the 780M, lavapipe, Iris Xe and the 5080 (3 rounds); with development's spares.rs, three of them fail (the device test holds 65+). The 780M and lavapipe suites passed apart from the device test's first form (2003/2004, 2006/2007), since fixed to give back past the 32 cap. (cherry picked from commit 733db7a42c8a0088069a0016ae7d8cf1b0479f4b) --- .../metal2vulkan-runtime/src/device/prime.rs | 7 + crates/metal2vulkan-runtime/src/exit_guard.rs | 4 + crates/metal2vulkan-runtime/src/release.rs | 23 ++ crates/metal2vulkan-runtime/src/spares.rs | 168 +++++++++++++- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../metal2vulkan-runtime/src/tests/spares.rs | 185 ++++++++++++++- .../src/tests/spares_bench.rs | 211 ++++++++++++++++++ 7 files changed, 585 insertions(+), 15 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/spares_bench.rs diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs index 41f9a68c2..9af8bbae7 100644 --- a/crates/metal2vulkan-runtime/src/device/prime.rs +++ b/crates/metal2vulkan-runtime/src/device/prime.rs @@ -782,6 +782,13 @@ impl Primer<'_> { .with(|queue| unsafe { device.queue_wait_idle(queue) }) .map_err(vulkan)?; self.made(Call::QueueWaitIdle); + // A spare pool's command buffers freed and the pool trimmed as a command buffer gives it + // back (`spares.rs`). + // SAFETY: the command buffer is the priming's pool's, its one submission completed, and + // the pool is the priming's alone. + unsafe { release::object(device, release::PoolBuffers(pool, &buffers)) }; + self.made(Call::FreeCommandBuffers); + self.made(Call::TrimCommandPool); if let Some(queries) = queries { let mut results = [[0u64; 2]; 2]; // SAFETY: the pool's two queries were written by the submission, which completed; diff --git a/crates/metal2vulkan-runtime/src/exit_guard.rs b/crates/metal2vulkan-runtime/src/exit_guard.rs index eae538fe2..78c2b3e0d 100644 --- a/crates/metal2vulkan-runtime/src/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/exit_guard.rs @@ -464,6 +464,10 @@ calls! { DeviceWaitIdle => c"vkDeviceWaitIdle", CreateCommandPool => c"vkCreateCommandPool", AllocateCommandBuffers => c"vkAllocateCommandBuffers", + // A spare command pool's command buffers past its recent uses, or an idle spare's, freed as a + // command buffer gives a pool back, and the pool trimmed (`spares.rs`). + FreeCommandBuffers => c"vkFreeCommandBuffers", + TrimCommandPool => c"vkTrimCommandPool", BeginCommandBuffer => c"vkBeginCommandBuffer", CmdPipelineBarrier => c"vkCmdPipelineBarrier", CmdResetQueryPool => c"vkCmdResetQueryPool", diff --git a/crates/metal2vulkan-runtime/src/release.rs b/crates/metal2vulkan-runtime/src/release.rs index 3ec642782..0e7da9887 100644 --- a/crates/metal2vulkan-runtime/src/release.rs +++ b/crates/metal2vulkan-runtime/src/release.rs @@ -144,6 +144,29 @@ pub(crate) unsafe fn generated(commands: &Commands, object: Generated) -> bool { true } +/// Command buffers of one command pool, freed together (`vkFreeCommandBuffers`), the pool then +/// trimmed (`vkTrimCommandPool`), so that the driver returns what it keeps of them: a spare pool's +/// past its recent uses (`spares.rs`). +pub(crate) struct PoolBuffers<'a>( + pub(crate) vk::CommandPool, + pub(crate) &'a [vk::CommandBuffer], +); + +impl Released for PoolBuffers<'_> { + const CALL: Call = Call::FreeCommandBuffers; + + unsafe fn destroy(self, device: &ash::Device, _: Door) { + let PoolBuffers(pool, buffers) = self; + // SAFETY: the caller's: none of the command buffers is pending, and it holds the pool + // alone. + unsafe { + device.free_command_buffers(pool, buffers); + device.trim_command_pool(pool, vk::CommandPoolTrimFlags::empty()); + } + exit_guard::called(Call::TrimCommandPool); + } +} + /// `Released` for handles a device's `vkDestroy*` or `vkFree*` releases. macro_rules! released { ($($handle:ty => $method:ident, $call:ident;)*) => { diff --git a/crates/metal2vulkan-runtime/src/spares.rs b/crates/metal2vulkan-runtime/src/spares.rs index d000380b8..0bb936dd4 100644 --- a/crates/metal2vulkan-runtime/src/spares.rs +++ b/crates/metal2vulkan-runtime/src/spares.rs @@ -8,15 +8,32 @@ //! - **Command pools are kept, never released while the device lives**. Every command pool a //! command buffer gives back is kept, whatever its status, and every command buffer dropped with //! one gives it back too: the runtime calls `vkDestroyCommandPool` on a command buffer's pool -//! only as the device is torn down, after its queues are idle. -//! The spares stay bounded all the same: a command buffer makes a pool only where no spare of its -//! queue's family is free, so the device holds at most as many as its command buffers held at -//! once (Metal bounds those by each queue's `maxCommandBufferCount`), each holding what its -//! largest command buffer recorded. Before, a pool given back past 8 spares, or one that made -//! more than 64 command buffers, was released on the handler thread that completed its command -//! buffer; on NVIDIA's driver 615.71.09 that `vkDestroyCommandPool` intermittently never returned -//! (the driver spinning, with its own `[vkrt] Analysis` thread), so the command buffer never -//! completed and its queue stalled. +//! only as the device is torn down, after its queues are idle. A command buffer makes a pool only +//! where no spare of its queue's family is free, so the device holds at most as many as its +//! command buffers held at once (Metal bounds those by each queue's `maxCommandBufferCount`). +//! Before, a pool given back past 8 spares, or one that made more than 64 command buffers, was +//! released on the handler thread that completed its command buffer; on NVIDIA's driver +//! 615.71.09 that `vkDestroyCommandPool` intermittently never returned (the driver spinning, +//! with its own `[vkrt] Analysis` thread), so the command buffer never completed and its queue +//! stalled. +//! - **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 +//! (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 +//! buffers it makes next; on an RTX 5080 Laptop GPU (NVIDIA 615) 4 to 7 us and 0.4 to 48 us +//! (0.22 ms at the slowest); on lavapipe a few microseconds. //! - **Descriptor pools are bounded.** At most [`DESCRIPTOR_POOLS`] descriptor pools of at most //! [`DESCRIPTORS`] descriptors together; a descriptor pool given back past them releases the //! oldest spares first, so the spares follow the shapes in use. The descriptors bound the @@ -113,6 +130,7 @@ use super::release::{self, Released}; use ash::vk; use std::collections::VecDeque; use std::sync::Mutex; +use std::time::{Duration, Instant}; /// The most spare descriptor pools a device keeps (of each list, a command buffer's arenas' and /// the fitted arenas'): a few frames' worth of a window server's (the module docs). @@ -121,6 +139,18 @@ pub(super) const DESCRIPTOR_POOLS: usize = 256; /// The most descriptors the spare descriptor pools hold together. pub(super) const DESCRIPTORS: u64 = 1 << 18; +/// The uses of a command pool whose command buffers it keeps: given back, it keeps of each level +/// as many as the most one of its last this many uses handed out (the module docs). +pub(super) const RECENT_USES: usize = 8; + +/// How long a spare command pool stays untaken before every command buffer it holds is freed (the +/// 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. +pub(super) const FREED_AT_ONCE: usize = 32; + /// The index of `level`'s list in a [`CommandPool`]: primary 0, secondary 1. fn level_index(level: vk::CommandBufferLevel) -> usize { usize::from(level == vk::CommandBufferLevel::SECONDARY) @@ -141,6 +171,11 @@ pub(super) struct CommandPool { /// did not complete, or left one it was handed unended (the module docs), so its taker /// resets it. pub(super) recording: bool, + /// The command buffers each of its last [`RECENT_USES`] uses handed out, by level, the newest + /// last ([`given_back`](Self::given_back)). + uses: VecDeque<[usize; 2]>, + /// When a command buffer last gave it back, or `None` before one did. + given: Option, } impl CommandPool { @@ -153,9 +188,61 @@ impl CommandPool { handed: [0, 0], begun: None, recording: false, + uses: VecDeque::new(), + given: None, } } + /// 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 { + if self.uses.len() == RECENT_USES { + self.uses.pop_front(); + } + self.uses.push_back(self.handed); + self.given = Some(now); + let mut past = Vec::new(); + for at in 0..2 { + let used = self.uses.iter().map(|used| used[at]).max().unwrap_or(0); + let keep = match at == level_index(vk::CommandBufferLevel::SECONDARY) { + true => used.max(1), + false => used, + }; + let made = self.made[at].len(); + let from = made - made.saturating_sub(keep).min(most - past.len()); + past.extend(self.made[at].drain(from..)); + } + past + } + + /// Whether no command buffer took it since one gave it back [`IDLE_FOR`] or longer before + /// `now`, and it holds a command buffer (the module docs). + fn idle(&self, now: Instant) -> bool { + let holds = self.begun.is_some() || self.made.iter().any(|made| !made.is_empty()); + let since = self.given.map(|given| now.saturating_duration_since(given)); + 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 { + 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 + } + + /// The command buffers it holds, the primary begun ahead among them. + #[cfg(test)] + pub(super) fn held(&self) -> usize { + self.made[0].len() + self.made[1].len() + usize::from(self.begun.is_some()) + } + /// The pool's primary begun ahead (the module docs), handed out: taken by the first encoder /// of the command buffer that took the pool. `None` where it holds none. pub(super) fn take_begun(&mut self) -> Option { @@ -351,8 +438,10 @@ 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). A pool that made no secondary command buffer makes one - /// first. Never released here. + /// 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. pub(super) fn give_command_pool( &self, device: &DeviceShared, @@ -366,9 +455,33 @@ impl Spares { audit.check(device.vk(), Freeing::GiveBack, &pool.buffers()); } } + 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) }; pool.stock(device); - keep_command_pool(&mut lock(&self.command_pools), pool); + let room = FREED_AT_ONCE - past.len(); + let idle = { + let mut pools = lock(&self.command_pools); + keep_command_pool(&mut pools, pool); + (room > 0).then(|| take_idle(&mut pools, now)).flatten() + }; + 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); + } + } + + /// 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 { + lock(&self.command_pools) + .iter() + .map(CommandPool::held) + .sum() } /// Begin a primary ahead in the spare command pool `raw` of `device`, where it is still a @@ -474,6 +587,37 @@ 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)) }; + } +} + +/// The oldest of the spare command pools `pools` left idle at `now` ([`CommandPool::idle`]), +/// taken out, to free its command buffers (the module docs). +pub(super) fn take_idle(pools: &mut Vec, now: Instant) -> Option { + let at = pools.iter().position(|pool| pool.idle(now))?; + Some(pools.remove(at)) +} + +/// Keep `pool`, a spare whose command buffers its idleness freed, among the spare command pools +/// `pools` as the oldest: a taker takes the newest, which still holds its command buffers. +pub(super) fn keep_idle_command_pool(pools: &mut Vec, pool: CommandPool) { + pools.insert(0, pool); +} + /// The newest of the spare command pools `pools` made for queue family `family` that holds a /// primary begun ahead, else the newest of them, taken out. pub(super) fn take_command_pool(pools: &mut Vec, family: u32) -> Option { diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 8dcbaba65..c323bf7e3 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -464,6 +464,8 @@ mod short_row_kinds; mod snapshot_area; mod sorted_chunks; mod spares; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod spares_bench; 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 b318ee739..7da968699 100644 --- a/crates/metal2vulkan-runtime/src/tests/spares.rs +++ b/crates/metal2vulkan-runtime/src/tests/spares.rs @@ -1,13 +1,16 @@ //! A device's spare command pools and descriptor pools (`spares.rs`): which command buffers a pool -//! hands out again, and what the bounds keep. +//! hands out again, and what the bounds keep. The last test runs on a device: device tests compile +//! only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). use crate::descriptor_arena::{Room, SetNeeds}; use crate::spares::{ - keep_command_pool, keep_descriptor_pool, take_command_pool, take_descriptor_pool, - take_to_begin, CommandPool, DescriptorPool, DESCRIPTORS, DESCRIPTOR_POOLS, + keep_command_pool, keep_descriptor_pool, keep_idle_command_pool, take_command_pool, + take_descriptor_pool, take_idle, take_to_begin, CommandPool, DescriptorPool, DESCRIPTORS, + DESCRIPTOR_POOLS, IDLE_FOR, RECENT_USES, }; use ash::vk::{self, Handle}; use std::collections::VecDeque; +use std::time::Instant; /// Needs of `count` storage buffers, with `flags`. fn storage(count: u32, flags: vk::DescriptorPoolCreateFlags) -> SetNeeds { @@ -284,3 +287,179 @@ fn a_spare_command_pool_begins_ahead_out_of_the_spares() { assert!(take_to_begin(&mut pools, vk::CommandPool::from_raw(3)).is_none()); assert_eq!(pools.len(), 2, "a pool that may not begin one stays"); } + +/// 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. +#[test] +fn a_pool_given_back_keeps_what_its_recent_uses_handed_out() { + let primary = vk::CommandBufferLevel::PRIMARY; + let secondary = vk::CommandBufferLevel::SECONDARY; + let now = Instant::now(); + let mut pool = CommandPool::new(vk::CommandPool::from_raw(1), 0); + for n in 0..100u64 { + pool.made(primary, vk::CommandBuffer::from_raw(n + 1)); + } + 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_eq!(pool.held(), 102); + // Smaller uses: three primaries each, no secondary. + let small = |pool: &mut CommandPool, most: usize| { + pool.taken(); + for _ in 0..3 { + assert!(pool.reuse(primary).is_some()); + } + pool.given_back(now, most) + }; + for use_ in 1..RECENT_USES { + assert!( + small(&mut pool, usize::MAX).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(); + expected.push(vk::CommandBuffer::from_raw(1001)); + assert_eq!( + past, expected, + "past the most of its last uses, a secondary kept" + ); + assert_eq!(pool.held(), 4); + pool.taken(); + assert_eq!(pool.reuse(primary), Some(vk::CommandBuffer::from_raw(1))); + assert_eq!( + pool.reuse(secondary), + Some(vk::CommandBuffer::from_raw(1000)) + ); +} + +/// 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 +/// first, and goes back as the oldest, so that a taker takes a spare that still holds its command +/// buffers first. +#[test] +fn a_spare_left_idle_sheds_its_command_buffers_and_goes_back_the_oldest() { + let primary = vk::CommandBufferLevel::PRIMARY; + let start = Instant::now(); + let pool = |n: u64, given: Instant| { + 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()); + 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()); + 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), + [ + vk::CommandBuffer::from_raw(19), + vk::CommandBuffer::from_raw(11) + ], + "the begun primary first, then the last made" + ); + 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, + vk::CommandPool::from_raw(2), + "a pool that holds none is never idle" + ); +} + +#[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}; + + /// The blit encoders of the burst's command buffer. + const BURST: usize = 64; + + /// 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) { + 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(); + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + } + + /// The command buffers the device's spare command pools hold once `done` holds of it, or + /// after [`WAIT`]: a pool is given back as its command buffer's completion is processed. + fn held_once(device: &Device, done: impl Fn(usize) -> bool) -> usize { + let start = Instant::now(); + loop { + let held = device.shared().spares.command_buffers_held(); + if done(held) || start.elapsed() > WAIT { + return held; + } + std::thread::sleep(Duration::from_millis(1)); + } + } + + #[test] + fn command_buffers_the_spares_hold_fall_back_after_a_burst() { + 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); + let before = held_once(&device, |held| held > 0); + fills(&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); + for _ in 0..more { + fills(&queue, &target, 1); + } + let after = held_once(&device, |held| held <= before + 2); + 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", + device.name() + ); + assert!( + burst >= before + BURST / 2, + "the burst's command buffer left {burst} where one encoder's left {before}" + ); + assert!( + after <= before + 2, + "{after} held after {more} command buffers of one encoder, {before} before the burst" + ); + drop((target, queue, device)); + let _ = std::fs::remove_dir_all(&scratch); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/spares_bench.rs b/crates/metal2vulkan-runtime/src/tests/spares_bench.rs new file mode 100644 index 000000000..2d1a97b04 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/spares_bench.rs @@ -0,0 +1,211 @@ +//! What a command pool's command buffers cost, as the device's spares make, free and trim them +//! (`spares.rs`): on the device's own queue family, a pool like the runtime's +//! (`VK_COMMAND_POOL_CREATE_TRANSIENT_BIT`, `VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`) +//! allocates [`MADE`] primaries one at a time, each begun, recording a barrier and ended, as an +//! encoder's would; then frees all but [`KEPT`] of them as give-backs do, [`FREED_AT_ONCE`] in +//! one `vkFreeCommandBuffers`, each followed by the pool's trim (`vkTrimCommandPool`), and does it +//! again [`ROUNDS`] times, its command buffers allocated anew each round. +//! +//! Printed (`SPARES-BENCH`), per round: each call's time (`vkAllocateCommandBuffers`'s median and +//! slowest, the begins', the frees' and the trims'), and the process's memory before the makings, +//! once they were made, and after the frees and trims: where its DRM file reports it +//! (`/proc/self/fdinfo`, `drm-total-*` and `drm-resident-*`, summed over the device files the +//! process holds), and on macOS its physical footprint (`proc_pid_rusage`'s `ri_phys_footprint`, +//! which counts the GPU memory the process owns). Ignored: run it alone, by name, under +//! `--cfg m2v_gpu` (or `m2v_cpu_icd`): +//! `cargo nextest run -p metal2vulkan-runtime --lib --run-ignored all spares_bench --no-capture`. + +use crate::spares::FREED_AT_ONCE; +use crate::tests::freed_memory::device; +use ash::vk; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +/// The command buffers each round makes. +const MADE: usize = 256; + +/// The command buffers each round keeps as it frees the rest. +const KEPT: usize = 4; + +/// The rounds. +const ROUNDS: usize = 6; + +/// The process's memory by key, in KiB: its DRM memory (`drm-total-gtt`, `drm-resident-system0`, +/// ...) summed over its DRM files, and on macOS its physical footprint (`phys-footprint`); empty +/// where neither is reported. +fn process_memory() -> BTreeMap { + let mut memory = BTreeMap::new(); + #[cfg(target_os = "macos")] + { + let mut info = std::mem::MaybeUninit::::zeroed(); + // SAFETY: `info` is as large as the flavor's answer, and the pid is this process's. + let read = unsafe { + libc::proc_pid_rusage( + std::process::id() as libc::c_int, + libc::RUSAGE_INFO_V4, + info.as_mut_ptr().cast(), + ) + }; + if read == 0 { + // SAFETY: the call filled it. + let info = unsafe { info.assume_init() }; + memory.insert("phys-footprint".to_owned(), info.ri_phys_footprint / 1024); + } + } + let Ok(entries) = std::fs::read_dir("/proc/self/fdinfo") else { + return memory; + }; + for entry in entries.flatten() { + let Ok(text) = std::fs::read_to_string(entry.path()) else { + continue; + }; + if !text.contains("drm-driver:") { + continue; + } + for line in text.lines() { + let Some((key, value)) = line.split_once(':') else { + continue; + }; + if !(key.starts_with("drm-total-") || key.starts_with("drm-resident-")) { + continue; + } + let mut words = value.split_whitespace(); + let (Some(number), unit) = (words.next(), words.next()) else { + continue; + }; + let Ok(number) = number.parse::() else { + continue; + }; + let kib = match unit { + Some("MiB") => number * 1024, + Some("KiB") => number, + Some("GiB") => number * 1024 * 1024, + _ => number / 1024, + }; + *memory.entry(key.to_owned()).or_default() += kib; + } + } + memory +} + +/// The keys of `memory` that are nonzero, with their KiB. +fn said(memory: &BTreeMap) -> String { + let nonzero: Vec = (memory.iter()) + .filter(|(_, kib)| **kib > 0) + .map(|(key, kib)| format!("{key} {kib} KiB")) + .collect(); + match nonzero.is_empty() { + true => "not reported".to_owned(), + false => nonzero.join(", "), + } +} + +/// 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_bench() { + let scratch = std::env::temp_dir().join(format!("m2v-spares-bench-{}", std::process::id())); + std::fs::create_dir_all(&scratch).unwrap(); + let device = device(&scratch); + let shared = device.shared(); + let vk = shared.vk(); + let info = vk::CommandPoolCreateInfo::default() + .flags( + vk::CommandPoolCreateFlags::TRANSIENT + | vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER, + ) + .queue_family_index(shared.queue_family); + // SAFETY: the device is live and `info` valid. + let pool = unsafe { vk.create_command_pool(&info, None) }.unwrap(); + let mut kept: Vec = Vec::new(); + for round in 0..ROUNDS { + let before = process_memory(); + let (mut allocations, mut begins) = (Vec::new(), Vec::new()); + let mut made = Vec::new(); + while kept.len() + made.len() < MADE { + let allocate = vk::CommandBufferAllocateInfo::default() + .command_pool(pool) + .level(vk::CommandBufferLevel::PRIMARY) + .command_buffer_count(1); + let start = Instant::now(); + // SAFETY: the pool is this thread's alone. + let buffer = unsafe { vk.allocate_command_buffers(&allocate) }.unwrap()[0]; + allocations.push(start.elapsed()); + made.push(buffer); + } + for &buffer in kept.iter().chain(&made) { + let begin = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + let barrier = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) + .dst_access_mask(vk::AccessFlags::TRANSFER_READ); + let start = Instant::now(); + // SAFETY: the command buffer is the pool's, never pending, and its begin resets it + // (the pool's reset flag); the barrier names no resource. + unsafe { + vk.begin_command_buffer(buffer, &begin).unwrap(); + vk.cmd_pipeline_barrier( + buffer, + vk::PipelineStageFlags::TRANSFER, + vk::PipelineStageFlags::TRANSFER, + vk::DependencyFlags::empty(), + &[barrier], + &[], + &[], + ); + vk.end_command_buffer(buffer).unwrap(); + } + begins.push(start.elapsed()); + } + let full = process_memory(); + // The first round keeps the last few it made, as a pool's recent uses keep theirs. + if kept.is_empty() { + kept = made.split_off(made.len() - KEPT.min(made.len())); + } + let (mut frees, mut trims) = (Vec::new(), Vec::new()); + for some in made.chunks(FREED_AT_ONCE) { + let start = Instant::now(); + // SAFETY: none of them was submitted, and the pool is this thread's alone. + unsafe { vk.free_command_buffers(pool, some) }; + frees.push(start.elapsed()); + let start = Instant::now(); + // SAFETY: the pool is this thread's alone. + unsafe { vk.trim_command_pool(pool, vk::CommandPoolTrimFlags::empty()) }; + trims.push(start.elapsed()); + } + let after = process_memory(); + println!( + "SPARES-BENCH {} round {round}: {} allocated, {}; begin, barrier and end of {}, {}; \ + {} vkFreeCommandBuffers of up to {FREED_AT_ONCE}, {}; their vkTrimCommandPool, {}; \ + DRM memory before: {}; made: {}; freed and trimmed: {}", + device.name(), + made.len(), + spread(&mut allocations), + begins.len(), + spread(&mut begins), + frees.len(), + spread(&mut frees), + spread(&mut trims), + said(&before), + said(&full), + said(&after), + ); + } + // SAFETY: none of its command buffers is pending; the pool is this thread's alone. + unsafe { + vk.free_command_buffers(pool, &kept); + vk.destroy_command_pool(pool, None); + } + drop(device); + let _ = std::fs::remove_dir_all(&scratch); +}