Keep a GPU pool's blocks while in use, and release a command buffer's own objects after its handlers

The steps this packet landed as, in order:
- Count the most GPU pool blocks leased at once
- Share one GPU pool block per queue among its command buffers
- Keep an arena's fitted list on the pools a completing command buffer takes out

Content: the tree of `development` at 0a94bc93a0, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:03 +02:00
1 parent c1e9b6b2b9
commit 644e055652
15 files changed
+734 -80

No files matched your search

@@ -502,11 +502,11 @@ pub(super) struct State {
pub(super) capture_tallies: Vec<CaptureTally>,
/// The index pool of the commands' index bounds and rewrite passes (`index_bounds.rs`,
/// `index_rewrite.rs`), once a draw needs it: its counter in the arena, starting at 0, and
/// the block of the device's its indices lie in (`gpu_pools.rs`).
/// its lease of its queue's block, which its indices lie in (`gpu_pools.rs`).
index_pool: Option<(Upload, PoolLease)>,
/// The records pool of the commands' scanned emulated mesh draws (`render/mesh.rs`), once a
/// draw needs it: a block of the device's (`gpu_pools.rs`); the scans' cursor is a status
/// word.
/// draw needs it: its lease of its queue's block (`gpu_pools.rs`); the scans' cursor is a
/// status word.
mesh_pool: Option<PoolLease>,
/// The emulated mesh draws numbered so far, each by its order.
mesh_draws: u32,
@@ -1290,9 +1290,10 @@ impl State {
/// The command buffer's index pool (`index_bounds.rs`, `index_rewrite.rs`), taken when a
/// draw first needs it: its counter, `IndexBoundsPass::POOL_HEADER_BYTES` of the arena, zero;
/// and the block its indices lie in, from the block's
/// `IndexBoundsPass::POOL_HEADER_BYTES` on, leased from the device (`gpu_pools.rs`): the
/// block's `VkBuffer` and bytes, the header's included.
pub(super) fn index_pool(&mut self, device: &Device) -> Result<IndexPool, Error> {
/// `IndexBoundsPass::POOL_HEADER_BYTES` on, its queue's (`queue`, the command buffer's
/// `CommandQueue::id`), leased from the device (`gpu_pools.rs`): the block's `VkBuffer` and
/// bytes, the header's included.
pub(super) fn index_pool(&mut self, device: &Device, queue: u64) -> Result<IndexPool, Error> {
if let Some((counter, block)) = &self.index_pool {
return Ok(IndexPool::of(counter, block));
}
@@ -1300,7 +1301,7 @@ impl State {
let counter = self
.uploads
.upload(device, &vec![0; header as usize], header)?;
let block = device.lease_pool(PoolKind::Index)?;
let block = device.lease_pool(PoolKind::Index, queue)?;
let pool = IndexPool::of(&counter, &block);
self.index_pool = Some((counter, block));
Ok(pool)
@@ -1310,11 +1311,15 @@ impl State {
/// budget, leased when a scanned emulated mesh draw first needs it, a host step's replay of
/// one among them (`gpu_pools.rs`): its `VkBuffer` and bytes. Its words need no value before
/// the scans reserve them.
pub(super) fn mesh_pool(&mut self, device: &Device) -> Result<(vk::Buffer, u64), Error> {
pub(super) fn mesh_pool(
&mut self,
device: &Device,
queue: u64,
) -> Result<(vk::Buffer, u64), Error> {
if let Some(pool) = &self.mesh_pool {
return Ok((pool.raw(), pool.bytes()));
}
let pool = device.lease_pool(PoolKind::MeshRecords)?;
let pool = device.lease_pool(PoolKind::MeshRecords, queue)?;
let leased = (pool.raw(), pool.bytes());
self.mesh_pool = Some(pool);
Ok(leased)
@@ -3279,11 +3284,11 @@ impl CommandBufferShared {
}
/// Finish the command buffer with `result` (or the failure of a batch): take the device's
/// trail mark (`trails.rs`), set its status, decode its status words, release its uploads,
/// run its completed handlers on this thread, give its queue's slot back, release what it
/// retained and its encoders' logs, then open its gate, which releases its waiters once the
/// transition's [`Hold`] (and every other) is gone, and they wait for the trails below the
/// mark. Waits from inside these steps answer as [`own`] says.
/// trail mark (`trails.rs`), set its status, decode its status words, run its completed
/// handlers on this thread, give its queue's slot back, release its uploads, pools and heap
/// versions, what it retained and its encoders' logs, then open its gate, which releases its
/// waiters once the transition's [`Hold`] (and every other) is gone, and they wait for the
/// trails below the mark. Waits from inside these steps answer as [`own`] says.
fn complete(self: &Arc<Self>, result: Result<(), CommandBufferError>) {
// A capture replay found a primitive whose reach was not measured: its pass rewrote
// every tile, announced once the lock is let go (below).
@@ -3293,6 +3298,8 @@ impl CommandBufferShared {
// Its command pool, where it settled, whose primary the device's spares begin ahead once
// its completed handlers ran (below).
let mut settled_pool = None;
// The heap versions its commands bound, let go of once its completed handlers ran.
let released_versions;
{
let mut state = lock(&self.state);
// Every trail of the work it waited for (a pipeline's making, a twin's decode) was
@@ -3400,17 +3407,15 @@ impl CommandBufferShared {
self.answer(&state);
state.status_words = None;
state.capture_tallies.clear();
state.index_pool = None;
state.mesh_pool = None;
state.uploads.clear();
state.heaps.clear();
// Its heap versions, uploads, pools and descriptor pools go once its completed
// handlers ran (below).
released_versions = state.heaps.clear();
// Its work ended: a detach waiting for it goes on (`detach.rs`).
state.submitted_holds.clear();
// Its work ended (its fences were signaled, or its queues drained after a failed
// wait), so nothing of its pools is pending: its command pool goes to the device's
// spares whatever its status, never released on this thread (`spares.rs`); a command
// buffer that completed gives back its descriptor pools too, one that failed releases
// them here.
// spares whatever its status, never released on this thread (`spares.rs`); its
// descriptor pools go once its completed handlers ran (below).
if let Some(pool) = state.pool.take() {
// None of the pool's command buffers is recording where it completed and ended
// every one the pool handed out: a recording it left unused leaves one so.
@@ -3432,11 +3437,6 @@ impl CommandBufferShared {
shared.spares.give_command_pool(shared, pool, settled);
}
}
if state.status == CommandBufferStatus::Completed {
state.descriptors.give_back();
} else {
state.descriptors.release();
}
state.unplaced();
parked = state.parked > 0;
}
@@ -3517,6 +3517,31 @@ impl CommandBufferShared {
drop(residencies);
let check = lock(&self.state).check.take();
drop(check);
// Then the runtime's own: its uploads, its index and mesh records pools' blocks, its
// heap versions and its descriptor pools, none of them the program's, last. Each may
// take a driver's lock as it goes (MoltenVK's `vkDestroyBuffer`, `vkFreeMemory` and
// `vkDestroyDescriptorPool` take the lock of its device's residency set, which its
// `vkBindBufferMemory` holds across a commit that took 24 to 39 ms for a 1 GiB block
// on the M3 Max, `gpu_pools.rs`), so they go after the completed handlers, which wait
// for none of them, and after what the program's commands used.
let (uploads, index_pool, mesh_pool, mut descriptors, completed) = {
let mut state = lock(&self.state);
(
state.uploads.take(),
state.index_pool.take(),
state.mesh_pool.take(),
state.descriptors.take(),
state.status == CommandBufferStatus::Completed,
)
};
drop((uploads, index_pool, mesh_pool, released_versions));
// A command buffer that completed gives its descriptor pools back to the device's
// spares; one that failed releases them.
if completed {
descriptors.give_back();
} else {
descriptors.release();
}
}
self.gate.finish();
// Its pool's primary begun ahead, where no command buffer took the pool since
@@ -238,6 +238,18 @@ impl DescriptorArena {
Ok(set)
}
/// Every pool, taken out, for the caller to give back or release where it holds no lock: to
/// the spares' list the arena takes from (fitted or not).
pub(crate) fn take(&mut self) -> DescriptorArena {
self.book.rooms.clear();
DescriptorArena {
book: Book::default(),
pools: std::mem::take(&mut self.pools),
device: self.device.clone(),
fitted: self.fitted,
}
}
/// Give every pool to the device's spares: the command buffer completed, so no command uses
/// their sets any more.
pub(crate) fn give_back(&mut self) {
+202 -39
View File
@@ -10,17 +10,41 @@
//! pool's within a `u32` of bytes, its counter's. Not a constant of the runtime's: a device of
//! twice the memory has pools of twice the bytes. Before, the index pool was 1 MiB on every
//! device.
//! - **Leased per command buffer, made lazily.** The first pass of a command buffer that needs a
//! pool takes the device's spare block of its kind, or makes one; the command buffer holds the
//! [`PoolLease`] until it completes, or until it is dropped unsubmitted, and then the block is
//! given back. No other command buffer gets a block while it is leased, so command buffers in
//! flight at once each have their own. The device keeps at most one spare of each kind (the
//! blocks are all one size, so the spare is any given back while none is idle); a block given
//! back beside a spare is released. A command buffer that reaches no pass of a pool takes none.
//! - **One block of each kind per queue, shared by its command buffers** ([`QueueBlocks`]). The
//! first pass of a command buffer that needs a pool leases its queue's block of that kind,
//! which the first lease of the queue makes; the command buffer holds the [`PoolLease`] until
//! it completes (its completed handlers ran, `command_buffer/mod.rs`), or until it is dropped
//! unsubmitted. Every command buffer of the queue reserves from the block's start (each one's
//! counter, or cursor, is its own), so they overwrite one another's reservations, in order:
//! - The queue's batches go to its `VkQueue` in commit order, a command buffer's after every
//! batch of the command buffers committed before it (`scheduler/mod.rs`, the order), so no
//! other command buffer of the queue lies between a command buffer's batches.
//! - Every command that writes a pool's bytes (an index bounds plan and fill, an index
//! rewrite's dispatches, an emulated mesh draw's and a tessellation draw's scan) runs after a
//! `Barrier::everything` its own command buffer records before it, from `ALL_COMMANDS` and
//! `MEMORY_WRITE`. Vulkan applies that barrier's first scope to every command submitted to
//! the `VkQueue` before it, earlier command buffers' included ("The first synchronization
//! scope and access scope of each memory dependency defined by pDependencyInfo are applied
//! to operations that occurred earlier in submission order", `vkCmdPipelineBarrier2`): so a
//! command buffer's writes wait for the earlier ones' draws, which read the block (a write
//! after a read needs only that execution dependency), and for their writes (the memory
//! dependency). The barrier was there before; sharing adds no wait.
//! - Queues sharing a `VkQueue` interleave their batches there (`scheduler/mod.rs`, many
//! logical queues), so a block is the queue's, not the `VkQueue`'s.
//!
//! A queue's block goes once no lease held it for [`QUIET`] or longer, as a later lease of its
//! kind ends on any queue, or as the queue goes. Before, each command buffer in flight had a
//! block of its own: two in flight at once made and released one a round, and keeping them made
//! none but held as many as were in flight. A block of 1 GiB (a sixty-fourth of a 64 GiB heap)
//! took 24 to 29 ms to make on the M3 Max (MoltenVK 1.4.1, macOS 27.0.1), 35 to 39 ms while the
//! GPU ran, all of it MoltenVK's commit of the block to its device's residency set inside
//! `vkBindBufferMemory`, under the lock its `vkDestroyBuffer` and `vkFreeMemory` take too, and
//! wired its 1 GiB of host memory whatever the GPU wrote of it.
//! - **Raw.** A block is a `VkBuffer` bound to private memory, outside the Metal address space,
//! not a `Buffer`, which would hold the device from the device's own spare (as the mipmap
//! scratch's, `mipmap_scratch.rs`). The device releases its spares as it is destroyed.
//! - **Not cleared.** Nothing reads a pool's bytes before a pass of the command buffer wrote them:
//! not a `Buffer`, which would hold the device from the device's own blocks (as the mipmap
//! scratch's, `mipmap_scratch.rs`). The device releases the blocks left as it is destroyed.
//! - **Not cleared.** Nothing reads a pool's bytes before a pass of the same command buffer wrote
//! them:
//! the index pool's counter lies in the command buffer's upload arena (zero as it is uploaded),
//! and its block holds only the indices the fills and writes place (the block's first
//! `IndexBoundsPass::POOL_HEADER_BYTES` are never read); the records pool's cursor is a status
@@ -33,15 +57,21 @@
use super::device::lock;
use super::error::Error;
use super::memory::Memory;
use super::mipmap_scratch::{Block, Spare, Take};
use super::mipmap_scratch::Block;
use super::upload::Upload;
use super::Device;
use ash::vk;
use metal2vulkan::bind::IndexBoundsPass;
use std::collections::BTreeMap;
use std::time::{Duration, Instant};
/// The share of the largest device-local heap a pool takes: one part in this many.
const POOL_SHARE: u64 = 64;
/// How long a queue's block stays without a lease before the end of another lease of its kind
/// releases it (the module docs).
pub(super) const QUIET: Duration = Duration::from_secs(2);
/// The bytes of a pool of a device with `properties`' heaps, whose storage bindings reach
/// `max_range` bytes and whose allocations `max_allocation`, behind `header` bytes the block
/// holds before them: a sixty-fourth of the largest device-local heap, within one binding and
@@ -88,15 +118,118 @@ impl PoolKind {
}
}
/// A device's pools: each kind's bytes and its spare block (the module docs).
/// One queue's block of a kind and the leases holding it.
#[derive(Debug)]
struct Slot<T> {
block: Option<T>,
/// The leases holding the block now.
leases: usize,
/// When the last lease ended, where none holds the block.
idle_since: Instant,
}
/// The blocks of one kind, one for each queue that leased one, the decisions pure so that the
/// CPU tests cover them (the module docs).
#[derive(Debug)]
pub(super) struct QueueBlocks<T> {
/// By the queue's identity (`CommandQueue::id`).
slots: BTreeMap<u64, Slot<T>>,
}
impl<T> Default for QueueBlocks<T> {
fn default() -> QueueBlocks<T> {
QueueBlocks {
slots: BTreeMap::new(),
}
}
}
impl<T> QueueBlocks<T> {
/// A lease of `queue`'s block: what `raw` reads of it, and the leases holding it now, this
/// one's included; `None` where the queue holds none, and the lease makes one ([`made`]).
///
/// [`made`]: Self::made
pub(super) fn take<R>(&mut self, queue: u64, raw: impl FnOnce(&T) -> R) -> Option<(R, usize)> {
let slot = self.slots.get_mut(&queue)?;
let block = slot.block.as_ref()?;
slot.leases += 1;
Some((raw(block), slot.leases))
}
/// `block`, made for a lease of `queue`, which held none: what `raw` reads of the queue's
/// block, the leases holding it now, and the block to release, `block` itself where another
/// lease of the queue made one meanwhile.
pub(super) fn made<R>(
&mut self,
queue: u64,
block: T,
now: Instant,
raw: impl FnOnce(&T) -> R,
) -> (R, usize, Option<T>) {
let slot = self.slots.entry(queue).or_insert(Slot {
block: None,
leases: 0,
idle_since: now,
});
let (read, extra) = match &slot.block {
Some(held) => (raw(held), Some(block)),
None => (raw(slot.block.insert(block)), None),
};
slot.leases += 1;
(read, slot.leases, extra)
}
/// A lease of `queue`'s block ended at `now`: the blocks to release, each queue's that no
/// lease held for [`QUIET`] or longer.
pub(super) fn give(&mut self, queue: u64, now: Instant) -> Vec<T> {
if let Some(slot) = self.slots.get_mut(&queue) {
slot.leases = slot.leases.saturating_sub(1);
if slot.leases == 0 {
slot.idle_since = now;
}
}
let quiet: Vec<u64> = (self.slots.iter())
.filter(|(_, slot)| {
slot.leases == 0 && now.saturating_duration_since(slot.idle_since) >= QUIET
})
.map(|(&queue, _)| queue)
.collect();
quiet
.into_iter()
.filter_map(|queue| self.slots.remove(&queue).and_then(|slot| slot.block))
.collect()
}
/// `queue` went, so no lease holds its block: the block, to release.
pub(super) fn forget(&mut self, queue: u64) -> Option<T> {
self.slots.remove(&queue).and_then(|slot| slot.block)
}
/// Every block, as the device is destroyed.
pub(super) fn drain(&mut self) -> Vec<T> {
let slots = std::mem::take(&mut self.slots);
slots.into_values().filter_map(|slot| slot.block).collect()
}
/// The blocks held.
#[cfg(test)]
pub(super) fn blocks(&self) -> usize {
self.slots
.values()
.filter(|slot| slot.block.is_some())
.count()
}
}
/// A device's pools: each kind's bytes and its queues' blocks (the module docs).
#[derive(Default)]
pub(super) struct GpuPools {
/// The index pool's bytes of indices, behind its header.
pub(super) index_bytes: u64,
/// The mesh records pool's bytes.
pub(super) mesh_bytes: u64,
index: std::sync::Mutex<Spare<Block>>,
mesh: std::sync::Mutex<Spare<Block>>,
index: std::sync::Mutex<QueueBlocks<Block>>,
mesh: std::sync::Mutex<QueueBlocks<Block>>,
}
impl GpuPools {
@@ -110,7 +243,7 @@ impl GpuPools {
}
}
fn spare(&self, kind: PoolKind) -> &std::sync::Mutex<Spare<Block>> {
fn blocks(&self, kind: PoolKind) -> &std::sync::Mutex<QueueBlocks<Block>> {
match kind {
PoolKind::Index => &self.index,
PoolKind::MeshRecords => &self.mesh,
@@ -125,27 +258,31 @@ impl GpuPools {
}
}
/// Release the spares as the device is destroyed.
/// Release the blocks as the device is destroyed.
pub(super) fn destroy(&self, device: &ash::Device, memory: &mut Memory) {
for kind in [PoolKind::Index, PoolKind::MeshRecords] {
lock(self.spare(kind)).destroy(device, memory);
for block in lock(self.blocks(kind)).drain() {
// SAFETY: the device is idle, so no command uses the block.
unsafe { block.release(device, memory) };
}
}
}
}
/// A command buffer's lease of a block of a pool, given back to its device as it drops (the
/// module docs).
/// A command buffer's lease of its queue's block of a pool, which ends as it drops (the module
/// docs).
pub(super) struct PoolLease {
device: Device,
kind: PoolKind,
block: Option<Block>,
queue: u64,
raw: vk::Buffer,
bytes: u64,
}
impl PoolLease {
/// The leased block's buffer.
pub(super) fn raw(&self) -> vk::Buffer {
self.block.as_ref().map_or(vk::Buffer::null(), Block::raw)
self.raw
}
/// The block's bytes.
@@ -165,15 +302,13 @@ impl std::fmt::Debug for PoolLease {
impl Drop for PoolLease {
fn drop(&mut self) {
let Some(block) = self.block.take() else {
return;
};
let shared = self.device.shared();
let released = lock(shared.gpu_pools.spare(self.kind)).give(block, self.bytes);
if let Some(block) = released {
let released = lock(shared.gpu_pools.blocks(self.kind)).give(self.queue, Instant::now());
for block in released {
// SAFETY: a lease ends when its command buffer completes or is dropped unsubmitted,
// and the spare is leased to none, so no command uses either block.
// and no lease holds a block released, so no command uses it.
unsafe { block.release(shared.vk(), &mut lock(&shared.memory)) };
shared.counts.gpu_pool_block_released();
}
}
}
@@ -210,27 +345,55 @@ impl IndexPool {
}
impl Device {
/// A lease of a block of `kind` for a command buffer: the device's spare, or a new block
/// (the module docs). Refused as memory is.
pub(super) fn lease_pool(&self, kind: PoolKind) -> Result<PoolLease, Error> {
/// A lease of `queue`'s block of `kind` for a command buffer of that queue (its
/// `CommandQueue::id`), which the queue's first lease makes (the module docs). Refused as
/// memory is.
pub(super) fn lease_pool(&self, kind: PoolKind, queue: u64) -> Result<PoolLease, Error> {
let shared = self.shared();
let bytes = shared.gpu_pools.block_bytes(kind);
let taken = lock(shared.gpu_pools.spare(kind)).take(bytes);
let block = match taken {
Take::Reuse(block, _) => block,
Take::Make(stale) => {
if let Some(block) = stale {
// SAFETY: the spare was leased to none, so no command uses it.
unsafe { block.release(shared.vk(), &mut lock(&shared.memory)) };
let taken = lock(shared.gpu_pools.blocks(kind)).take(queue, Block::raw);
let (raw, leases) = match taken {
Some(taken) => taken,
None => {
// Made without the lock: a lease of another queue, or one ending, waits for no
// making.
let block = self.make_block(bytes, kind.usage())?;
shared.counts.gpu_pool_block_made();
let (raw, leases, extra) = lock(shared.gpu_pools.blocks(kind)).made(
queue,
block,
Instant::now(),
Block::raw,
);
if let Some(extra) = extra {
// SAFETY: made just now, the block was never bound to a command.
unsafe { extra.release(shared.vk(), &mut lock(&shared.memory)) };
shared.counts.gpu_pool_block_released();
}
self.make_block(bytes, kind.usage())?
(raw, leases)
}
};
shared.counts.gpu_pool_leased(leases as u64);
Ok(PoolLease {
device: self.clone(),
kind,
block: Some(block),
queue,
raw,
bytes,
})
}
/// `queue` went: no lease holds its blocks, which are released (the module docs).
pub(super) fn forget_queue_pools(&self, queue: u64) {
let shared = self.shared();
for kind in [PoolKind::Index, PoolKind::MeshRecords] {
let block = lock(shared.gpu_pools.blocks(kind)).forget(queue);
if let Some(block) = block {
// SAFETY: every command buffer of the queue holds it, so none is left, and no
// command uses the block.
unsafe { block.release(shared.vk(), &mut lock(&shared.memory)) };
shared.counts.gpu_pool_block_released();
}
}
}
}
+5 -3
View File
@@ -1339,14 +1339,16 @@ impl HeapUse {
})
}
/// Release what the command buffer held: it completed.
pub(super) fn clear(&mut self) {
self.versions.clear();
/// The command buffer completed: its listing goes, and the versions its commands bound come
/// out, for the caller to let go of once its completed handlers ran (each version's last
/// hold releases its descriptor pool).
pub(super) fn clear(&mut self) -> Vec<Arc<SetVersion>> {
self.listed = None;
self.lists_samplers = false;
self.committed = false;
self.wants_ticket = false;
self.ticketed = false;
std::mem::take(&mut self.versions)
}
}
@@ -20,8 +20,9 @@
//! buffer as the draw binds it, the second over the pool. Exactly one draws the primitives.
//! - **The pool** (decision (a) made it 1 MiB on every device): its counter is a region of the
//! command buffer's upload arena, zero, so every plan of the command buffer reserves after the
//! ones before; its indices lie in a block the command buffer leases from the device, a
//! sixty-fourth of the device's largest device-local heap within one binding (`gpu_pools.rs`).
//! ones before; its indices lie in its queue's block, which the command buffer leases from the
//! device, a sixty-fourth of the device's largest device-local heap within one binding
//! (`gpu_pools.rs`).
//! The plan binds the counter as the pool, the fill the block (whose header bytes nothing reads),
//! and the second draw the block's indices. A draw it cannot hold draws nothing and sets
//! `INDEX_POOL_OVERFLOW`, and the command buffer fails with
@@ -102,13 +103,14 @@ impl BoundsPass {
.ok_or_else(refused)?;
let plan = device.owned_kernel(OwnedModule::IndexBoundsPlan)?;
let fill = device.owned_kernel(OwnedModule::IndexBoundsFill)?;
let queue = core.command_buffer().command_queue().id();
let (words, pool, status) = {
let mut state = core.command_buffer().state();
let words =
state
.uploads
.upload(&device, &pass.parameter_bytes(), IndexBoundsPass::BYTES)?;
let pool = state.index_pool(&device)?;
let pool = state.index_pool(&device, queue)?;
(words, pool, state.status_words(&device)?)
};
let region = |upload: &Upload, len: u64| (upload.raw(), upload.offset(), len);
@@ -17,7 +17,7 @@
//! - **The list** of a direct draw lies in a buffer of its own, of the program's capacity of the
//! draw's count, made for the draw; an indirect draw's, whose count only the GPU knows, in the
//! command buffer's index pool, which the index bounds pass shares (its counter in the arena,
//! its indices in a block the command buffer leases from the device, `gpu_pools.rs`): the count
//! its indices in its queue's block, which the command buffer leases, `gpu_pools.rs`): the count
//! and place dispatches bind the counter as the output, the write dispatch the block. A list the
//! pool cannot hold draws nothing and fails the command buffer with
//! `CommandBufferError::IndexPoolOverflow`.
@@ -172,7 +172,10 @@ impl RewritePass {
// device's, made without a submission.
let output = match owned {
Some((_, bytes)) => Output::Owned(device.scratch_buffer(bytes)?),
None => Output::Pooled(core.command_buffer().state().index_pool(&device)?),
None => {
let queue = core.command_buffer().command_queue().id();
Output::Pooled(core.command_buffer().state().index_pool(&device, queue)?)
}
};
let (words, status) = {
let mut state = core.command_buffer().state();
+8
View File
@@ -251,6 +251,14 @@ impl Device {
}
}
impl Drop for QueueShared {
fn drop(&mut self) {
// Every command buffer of the queue holds it, so none is left: no lease holds its pools'
// blocks (`gpu_pools.rs`).
self.device.forget_queue_pools(self.id);
}
}
impl CommandQueue {
/// `device`.
pub fn device(&self) -> &Device {
@@ -57,8 +57,8 @@
//! grid), reserves their records in the command buffer's records pool, and writes the mesh
//! dispatch's and the draw's indirect arguments; between barriers, the mesh dispatch and the draw
//! read them. The pool is a sixty-fourth of the device's largest device-local heap, within one
//! binding and one allocation, a block the command buffer leases from the device's spare
//! (`gpu_pools.rs`; made for each command buffer before); a draw whose records the rest of it
//! binding and one allocation, its queue's block, which the command buffer leases from the
//! device (`gpu_pools.rs`); a draw whose records the rest of it
//! cannot hold draws nothing and fails the command buffer
//! (`CommandBufferError::MeshRecordsOverflow`, naming the first such draw's number, its object
//! threadgroups and its mesh threadgroups). The dispatches record before the pass, as a draw's
@@ -596,6 +596,7 @@ impl MeshWork {
/// and buffers are.
pub(crate) fn new(core: &EncoderCore, dispatch: &MeshDispatch) -> Result<MeshWork, Error> {
let device = core.device().clone();
let queue = core.command_buffer().command_queue().id();
let mut state = core.command_buffer().state();
let mut words = dispatch.work.clone();
let mut set = |at: usize, value: u32| match words.get_mut(at) {
@@ -612,7 +613,7 @@ impl MeshWork {
(region.raw(), region.offset(), region.len())
}
MeshRecordsRegion::Pool => {
let (raw, bytes) = state.mesh_pool(&device)?;
let (raw, bytes) = state.mesh_pool(&device, queue)?;
let words = u32::try_from(bytes / 4)
.map_err(|_| internal("a mesh records pool past a u32's words"))?;
set(MeshDispatch::POOL_WORDS, words)?;
@@ -69,6 +69,7 @@ impl TessellationWork {
dispatch: &TessellationDispatch,
) -> Result<TessellationWork, Error> {
let device = core.device().clone();
let queue = core.command_buffer().command_queue().id();
let mut state = core.command_buffer().state();
let (records, pool) = match dispatch.records {
TessellationRecords::Exact { .. } => {
@@ -78,7 +79,7 @@ impl TessellationWork {
((region.raw(), region.offset(), region.len()), None)
}
TessellationRecords::Pool => {
let (raw, bytes) = state.mesh_pool(&device)?;
let (raw, bytes) = state.mesh_pool(&device, queue)?;
((raw, 0, bytes), Some(bytes))
}
_ => return Err(internal("tessellation records of another kind")),
@@ -0,0 +1,104 @@
//! A queue's blocks of the GPU pools (`gpu_pools.rs`): the command buffers of one queue share its
//! block, made once, round after round; another queue has a block of its own; a block no lease
//! held for [`QUIET`] goes as a later lease ends, and a queue's goes with the queue.
use super::super::gpu_pools::{QueueBlocks, QUIET};
use std::time::{Duration, Instant};
/// A lease of `queue`'s block from `blocks` at `now`: the block (`made + 1` where the lease
/// makes it) and the leases holding it now.
fn lease(blocks: &mut QueueBlocks<u32>, queue: u64, made: &mut u32, now: Instant) -> (u32, usize) {
if let Some(taken) = blocks.take(queue, |&block| block) {
return taken;
}
*made += 1;
let (block, leases, extra) = blocks.made(queue, *made, now, |&block| block);
assert_eq!(extra, None, "no other lease made one meanwhile");
(block, leases)
}
/// Two command buffers of one queue in flight at once, round after round, share one block, made
/// in the first round alone.
#[test]
fn command_buffers_of_one_queue_share_its_block() {
let mut blocks = QueueBlocks::default();
let mut made = 0;
let start = Instant::now();
for round in 0..8u32 {
let now = start + Duration::from_millis(16) * round;
let first = lease(&mut blocks, 7, &mut made, now);
let second = lease(&mut blocks, 7, &mut made, now);
assert_eq!((first, second), ((1, 1), (1, 2)), "round {round}");
assert!(blocks.give(7, now).is_empty(), "round {round}");
assert!(blocks.give(7, now).is_empty(), "round {round}");
}
assert_eq!((made, blocks.blocks()), (1, 1));
}
/// Another queue's command buffers take a block of their own.
#[test]
fn another_queue_takes_its_own_block() {
let mut blocks = QueueBlocks::default();
let mut made = 0;
let now = Instant::now();
assert_eq!(lease(&mut blocks, 1, &mut made, now), (1, 1));
assert_eq!(lease(&mut blocks, 2, &mut made, now), (2, 1));
assert_eq!(lease(&mut blocks, 1, &mut made, now), (1, 2));
assert_eq!((made, blocks.blocks()), (2, 2));
}
/// A block two leases made at once is made twice: the second made is the one released.
#[test]
fn a_block_made_meanwhile_is_released() {
let mut blocks = QueueBlocks::default();
let now = Instant::now();
assert_eq!(blocks.take(3, |&block: &u32| block), None);
assert_eq!(blocks.take(3, |&block: &u32| block), None);
assert_eq!(blocks.made(3, 10, now, |&block| block), (10, 1, None));
assert_eq!(blocks.made(3, 11, now, |&block| block), (10, 2, Some(11)));
assert_eq!(blocks.blocks(), 1);
}
/// A queue's block no lease held for the quiet period goes as a lease of another queue ends; a
/// block in use stays, however old, and one whose last lease ended less than the quiet period
/// before stays too.
#[test]
fn a_block_no_lease_held_for_the_quiet_period_goes() {
let mut blocks = QueueBlocks::default();
let mut made = 0;
let start = Instant::now();
// Queue 1 leases once and stops; queue 2 keeps one lease held throughout; queue 3 leases on.
lease(&mut blocks, 1, &mut made, start);
assert!(blocks.give(1, start).is_empty());
lease(&mut blocks, 2, &mut made, start);
let mut now = start;
let mut released = Vec::new();
while now < start + QUIET + Duration::from_millis(100) {
now += Duration::from_millis(16);
lease(&mut blocks, 3, &mut made, now);
let gone = blocks.give(3, now);
if now.duration_since(start) < QUIET {
assert!(gone.is_empty(), "nothing goes before the quiet period");
}
released.extend(gone);
}
assert_eq!(released, [1], "queue 1's block alone");
assert_eq!(blocks.blocks(), 2);
assert_eq!(made, 3);
}
/// A queue that goes takes its block with it; the device's teardown takes the rest.
#[test]
fn blocks_go_with_their_queue_and_with_the_device() {
let mut blocks = QueueBlocks::default();
let mut made = 0;
let now = Instant::now();
for queue in [1, 2, 3] {
lease(&mut blocks, queue, &mut made, now);
assert!(blocks.give(queue, now).is_empty());
}
assert_eq!(blocks.forget(2), Some(2));
assert_eq!(blocks.forget(2), None);
assert_eq!(blocks.drain(), [1, 3]);
assert_eq!(blocks.blocks(), 0);
}
@@ -66,6 +66,7 @@ mod freed_memory;
mod fresh_unwritten;
mod function_table;
mod gate;
mod gpu_pools;
mod gpu_time;
mod heap;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
+8 -3
View File
@@ -83,10 +83,15 @@ impl Uploads {
}
}
/// Release every chunk: no command reads the arena any more.
pub(super) fn clear(&mut self) {
self.chunks.clear();
/// Every chunk, taken out: no command reads the arena any more, and the chunks go as the
/// arena returned drops.
pub(super) fn take(&mut self) -> Uploads {
let opened = self.opened;
self.opened = 0;
Uploads {
chunks: std::mem::take(&mut self.chunks),
opened,
}
}
/// A region of `len` bytes (at least `bytes.len()`) holding `bytes` and then zeros.
@@ -103,6 +103,9 @@ pub(crate) struct Counters {
visibility_queries_begun: AtomicU64,
indirect_draws_recorded: AtomicU64,
indirect_records_read: AtomicU64,
gpu_pool_blocks_made: AtomicU64,
gpu_pool_blocks_released: AtomicU64,
gpu_pool_leases_peak: AtomicU64,
internal_submissions: AtomicU64,
queue_submissions: AtomicU64,
submit_infos: AtomicU64,
@@ -773,6 +776,26 @@ impl Counters {
.fetch_add(count, Ordering::Relaxed);
}
/// A command buffer's lease made its queue's block of a GPU pool: the queue held none
/// (`gpu_pools.rs`).
pub(crate) fn gpu_pool_block_made(&self) {
self.gpu_pool_blocks_made.fetch_add(1, Ordering::Relaxed);
}
/// A lease of a queue's block of a GPU pool began, `leased` leases holding it now, this one's
/// included (`gpu_pools.rs`).
pub(crate) fn gpu_pool_leased(&self, leased: u64) {
self.gpu_pool_leases_peak
.fetch_max(leased, Ordering::Relaxed);
}
/// A queue's block of a GPU pool was released before the device's teardown: no lease held it
/// for too long, or its queue went (`gpu_pools.rs`).
pub(crate) fn gpu_pool_block_released(&self) {
self.gpu_pool_blocks_released
.fetch_add(1, Ordering::Relaxed);
}
/// A host step's variant made immutable samplers no live set had (`pipeline/objects.rs`).
pub(crate) fn host_step_sampler_set_made(&self) {
self.host_step_sampler_sets_made
@@ -2458,6 +2481,20 @@ pub struct WorkCounts {
/// `IndirectCommandCheck`) or `IndirectCommandBuffer::commands` reads it; a setter's own
/// read of the command it changes is not counted.
pub indirect_records_read: u64,
/// Blocks of the GPU pools made: a queue's index pool block (for its index bounds passes and
/// index rewrites) or its mesh records pool block, made by the first command buffer of the
/// queue that needs one where the queue holds none. A queue's command buffers share its block
/// of each kind, so a queue makes one while it keeps using them. Each block is a sixty-fourth
/// of the device's largest device-local heap. Those made less those released are the blocks
/// the device holds.
pub gpu_pool_blocks_made: u64,
/// Blocks of the GPU pools released before the device's teardown: a queue's block no command
/// buffer held for two seconds, released as another lease of its kind ended, or the block of
/// a queue that went.
pub gpu_pool_blocks_released: u64,
/// The most command buffers that held one queue's block of a GPU pool at once: between each
/// one's first pass that needs it and its completion.
pub gpu_pool_leases_peak: u64,
/// Internal submissions made (`device/submit.rs`), each one a host call waits for: a host
/// copy through the GPU, a clear of a live buffer, a neutral's making.
pub internal_submissions: u64,
@@ -3634,6 +3671,9 @@ impl Device {
visibility_queries_begun: counters.visibility_queries_begun.load(Ordering::Relaxed),
indirect_draws_recorded: counters.indirect_draws_recorded.load(Ordering::Relaxed),
indirect_records_read: counters.indirect_records_read.load(Ordering::Relaxed),
gpu_pool_blocks_made: counters.gpu_pool_blocks_made.load(Ordering::Relaxed),
gpu_pool_blocks_released: counters.gpu_pool_blocks_released.load(Ordering::Relaxed),
gpu_pool_leases_peak: counters.gpu_pool_leases_peak.load(Ordering::Relaxed),
internal_submissions: counters.internal_submissions.load(Ordering::Relaxed),
queue_submissions: counters.queue_submissions.load(Ordering::Relaxed),
submit_infos: counters.submit_infos.load(Ordering::Relaxed),
@@ -499,6 +499,8 @@ mod host_memory;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod index_fetches;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod index_pools;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod indirect_command_buffers;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod indirect_dispatches;
@@ -0,0 +1,285 @@
//! Device tests of the index pool blocks (the runtime's `gpu_pools.rs`) on the device the cfg
//! selects, under the validation layer.
//!
//! Each command buffer here draws one indexed indirect draw of points with rasterization disabled
//! (the owned fixture `ob3_index_buffer`), from two 32-bit indices inside their buffer, on a
//! device opened without the robustness features, so every device's draw takes the index bounds
//! pass (`indirect-index-bounds-pass`), whose first pass in a command buffer leases its queue's
//! index pool block as it encodes and holds it until the command buffer completed.
//!
//! - The command buffers of one queue share its block, two in flight at once round after round,
//! and the queue makes it once (`WorkCounts::gpu_pool_blocks_made`); another queue makes its
//! own; a block no command buffer held for two seconds goes as a later one's lease ends, and a
//! queue's goes with the queue (`WorkCounts::gpu_pool_blocks_released`). Before, each command
//! buffer in flight held a block of its own, made where none was spare: on the M3 Max (MoltenVK
//! 1.4.1, macOS 27.0.1) a block is 1 GiB, whose making took 24 to 39 ms inside
//! `vkBindBufferMemory`, and wired its 1 GiB.
//! - A command buffer's completed handler runs while another thread makes a block: its uploads
//! and pools go after its handlers. Before, its uploads went first, and on MoltenVK their
//! `vkDestroyBuffer` waited for the lock that making holds, so the handler ran as the making
//! ended, 20 to 27 ms after the command buffer completed.
use super::{buffer_with, validated_device_with, Messages, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::coverage::ROBUSTNESS_FEATURES;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::metal::{IndexType, PrimitiveType};
use metal2vulkan::pipeline::{RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
host_time, Buffer, CommandBuffer, CommandQueue, Device, PipelineOptions, RenderPassDescriptor,
RenderPipelineState,
};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// The rounds of two command buffers in flight at once.
const ROUNDS: usize = 6;
/// The runtime's quiet period: a block no command buffer held this long goes as a later lease
/// ends (`gpu_pools::QUIET`).
const QUIET: Duration = Duration::from_secs(2);
/// The shortest making of a block that tells a handler that waited for it from one that did not
/// (on the M3 Max a block took 24 to 39 ms; a handler that waits for nothing runs within a
/// millisecond of its command buffer's completion).
const MAKING_TELLS: f64 = 0.010;
/// The device, opened without the robustness features, the fixture's vertex-only pipeline state
/// and the draw's buffers.
struct Lane {
device: Device,
pipeline: RenderPipelineState,
seen: Buffer,
indices: Buffer,
arguments: Buffer,
}
impl Lane {
fn new(messages: &Messages, cache: &ScratchCache) -> Lane {
let device = validated_device_with(TEST_DEVICE, messages, cache.path(), |options| {
options.withheld_features = ROBUSTNESS_FEATURES.into_iter().collect();
})
.unwrap();
let bitcode = llvm_assemble(&engine_dir().join("ob3_index_buffer.ll")).unwrap();
let library = device.new_library_with_air(&bitcode).unwrap();
let function = library.new_function_with_name("ob3_index_buffer").unwrap();
let mut descriptor =
RenderPipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
descriptor.rasterization_enabled = false;
let pipeline = device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
let words = |words: &[u32]| -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
};
// Two positions, both inside the buffer's two indices: a valid draw, which reserves
// nothing of the pool its pass leases.
let indices = buffer_with(&device, &words(&[1, 2])).unwrap();
let arguments = buffer_with(&device, &words(&[2, 1, 0, 0, 0])).unwrap();
let seen = buffer_with(&device, &[0; 32]).unwrap();
Lane {
device,
pipeline,
seen,
indices,
arguments,
}
}
fn queue(&self) -> CommandQueue {
self.device.new_command_queue().unwrap()
}
/// A command buffer of `queue` with the draw, encoded: its pass leased the queue's block.
fn encoded(&self, queue: &CommandQueue) -> CommandBuffer {
let mut pass = RenderPassDescriptor::new();
pass.render_target_width = 1;
pass.render_target_height = 1;
pass.default_raster_sample_count = 1;
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
encoder.set_render_pipeline_state(&self.pipeline).unwrap();
encoder.set_vertex_buffer(Some(&self.seen), 0, 0).unwrap();
encoder
.draw_indexed_primitives_indirect(
PrimitiveType::Point,
IndexType::UInt32,
&self.indices,
0,
&self.arguments,
0,
)
.unwrap();
encoder.end_encoding().unwrap();
command_buffer
}
/// One command buffer of `queue` with the draw, committed and completed.
fn drawn(&self, queue: &CommandQueue) {
let command_buffer = self.encoded(queue);
command_buffer.commit().unwrap();
completed(&command_buffer);
}
/// The blocks of the device's GPU pools made and released so far.
fn blocks(&self) -> (u64, u64) {
let counts = self.device.work_counts();
(counts.gpu_pool_blocks_made, counts.gpu_pool_blocks_released)
}
}
/// Wait for `command_buffer`, which completes without an error.
fn completed(command_buffer: &CommandBuffer) {
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
}
/// Two command buffers of one queue encoded before either commits, so both hold its block,
/// round after round: the first round makes the one block, and every later one makes and
/// releases none (the module docs).
#[test]
fn command_buffers_of_one_queue_share_one_pool_block() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let lane = Lane::new(&messages, &cache);
let queue = lane.queue();
for round in 0..ROUNDS {
let (made, released) = lane.blocks();
let first = lane.encoded(&queue);
let second = lane.encoded(&queue);
first.commit().unwrap();
second.commit().unwrap();
completed(&first);
completed(&second);
let (made_now, released_now) = lane.blocks();
let expected = if round == 0 { (1, 0) } else { (0, 0) };
assert_eq!(
(made_now - made, released_now - released),
expected,
"round {round}: blocks made and released"
);
}
assert_eq!(
lane.device.work_counts().gpu_pool_leases_peak,
2,
"two command buffers held the block at once at most"
);
}
assert_eq!(messages.take(), Vec::new(), "the validation layer reported");
}
/// A second queue's command buffer makes a block of its own, which goes as the queue goes; the
/// first queue's block stays.
#[test]
fn a_second_queue_takes_its_own_pool_block() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let lane = Lane::new(&messages, &cache);
let queue = lane.queue();
lane.drawn(&queue);
assert_eq!(lane.blocks(), (1, 0), "the first queue's block");
let other = lane.queue();
lane.drawn(&other);
assert_eq!(lane.blocks(), (2, 0), "the second queue's own block");
lane.drawn(&queue);
assert_eq!(lane.blocks(), (2, 0), "the first queue's block again");
// The queue goes once its last command buffer's hold goes, which may be on a handler
// thread just after the wait returned.
drop(other);
let deadline = Instant::now() + Duration::from_secs(5);
while lane.blocks().1 == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(1));
}
assert_eq!(
lane.blocks(),
(2, 1),
"the second queue's block went with it"
);
}
assert_eq!(messages.take(), Vec::new(), "the validation layer reported");
}
/// A queue's block that no command buffer held for the quiet period goes as another queue's
/// command buffer's lease ends; that queue's block, just held, stays.
#[test]
fn a_pool_block_no_command_buffer_held_goes_after_the_quiet_period() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let lane = Lane::new(&messages, &cache);
let idle = lane.queue();
let busy = lane.queue();
lane.drawn(&idle);
lane.drawn(&busy);
assert_eq!(lane.blocks(), (2, 0));
std::thread::sleep(QUIET + Duration::from_millis(200));
lane.drawn(&busy);
assert_eq!(lane.blocks(), (2, 1), "the idle queue's block went");
lane.drawn(&busy);
assert_eq!(lane.blocks(), (2, 1), "the busy queue's block stayed");
lane.drawn(&idle);
assert_eq!(lane.blocks(), (3, 1), "the idle queue makes one again");
}
assert_eq!(messages.take(), Vec::new(), "the validation layer reported");
}
/// A command buffer's completed handler runs while another queue's first command buffer makes
/// that queue's block on this thread: where the making took long enough to tell and the command
/// buffer completed in its first half, the handler ran less than half the making after the
/// completion (the module docs).
#[test]
fn a_completed_handler_waits_for_no_pool_block_made_meanwhile() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let lane = Lane::new(&messages, &cache);
let queue = lane.queue();
let other = lane.queue();
// The pipeline's first draw, which makes the first queue's block.
lane.drawn(&queue);
let first = lane.encoded(&queue);
let ran: Arc<Mutex<Option<f64>>> = Arc::default();
let log = Arc::clone(&ran);
first
.add_completed_handler(Box::new(move |_| {
*log.lock().unwrap() = Some(host_time());
}))
.unwrap();
let (made, _) = lane.blocks();
first.commit().unwrap();
let start = host_time();
let second = lane.encoded(&other);
let encoded = host_time();
assert_eq!(
lane.blocks().0 - made,
1,
"the second queue's command buffer made a block"
);
second.commit().unwrap();
completed(&first);
completed(&second);
let handled = ran.lock().unwrap().expect("the completed handler ran");
let seen = first.gpu_end_time().unwrap();
let making = encoded - start;
let lag = handled - seen;
eprintln!(
"making {:.3} ms, completion {:+.3} ms into it, handler {:.3} ms after the completion",
making * 1e3,
(seen - start) * 1e3,
lag * 1e3
);
if making >= MAKING_TELLS && seen < start + making / 2.0 {
assert!(
lag < making / 2.0,
"the completed handler ran {:.3} ms after its command buffer completed, during a \
making of {:.3} ms",
lag * 1e3,
making * 1e3
);
}
}
assert_eq!(messages.take(), Vec::new(), "the validation layer reported");
}