diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index d97022ce5..41662625d 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -208,61 +208,70 @@ struct Heap { /// A pooled block the harness took. struct Block { - id: rt::BlockId, + block: rt::Block, class: rt::MemoryClass, free: Ranges, } -/// Where a buffer lies: a range of a pooled block, or a dedicated block of its own (`None`). -struct Placed { - block: rt::BlockId, - range: Option>, +/// Where a buffer lies. +enum Placed { + /// A range of a pooled block. + Pooled { + block: rt::BlockId, + range: Range, + }, + /// A dedicated block of its own, whose handle the buffer holds: the runtime frees it once the + /// handle, the buffer and the work that used it are gone. + Dedicated(rt::Block), +} + +impl Placed { + /// The block's number and the buffer's offset in it. + fn at(&self) -> (rt::BlockId, u64) { + match self { + Placed::Pooled { block, range } => (*block, range.start), + Placed::Dedicated(block) => (block.id, 0), + } + } } impl Heap { /// A place for a buffer of `length` bytes in `class` memory. fn place(&mut self, class: rt::MemoryClass, length: u64) -> Result { if length > class.block_len() { - let block = self.device.take_block(class, length).map_err(error)?.id; - return Ok(Placed { block, range: None }); + let block = self.device.take_block(class, length).map_err(error)?; + return Ok(Placed::Dedicated(block)); } let span = length.next_multiple_of(ALIGN); let found = (self.blocks.iter_mut()) .filter(|block| block.class == class) - .find_map(|block| Some((block.id, block.free.take(span)?))); + .find_map(|block| Some((block.block.id, block.free.take(span)?))); let (block, start) = match found { Some(found) => found, None => { - let info = self.device.take_block(class, span).map_err(error)?; - let mut free = Ranges::new(info.len); + let block = self.device.take_block(class, span).map_err(error)?; + let mut free = Ranges::new(block.len); let start = (free.take(span)).ok_or("a new pooled block is shorter than a buffer")?; - self.blocks.push(Block { - id: info.id, - class, - free, - }); - (info.id, start) + let id = block.id; + self.blocks.push(Block { block, class, free }); + (id, start) } }; - Ok(Placed { + Ok(Placed::Pooled { block, - range: Some(start..start + span), + range: start..start + span, }) } - /// Frees `placed`: its range, or its dedicated block, which the runtime frees once its last - /// buffer is gone. + /// Frees `placed`'s range of a pooled block; a dedicated block goes with its handle, which + /// `placed` holds. fn free(&mut self, placed: &Placed) { - match &placed.range { - Some(range) => { - let block = (self.blocks.iter_mut()) - .find(|block| block.id == placed.block) - .expect("the harness keeps every pooled block it placed a buffer in"); - block.free.give(range.clone()); - } - None => (self.device.release_block(placed.block)) - .expect("the harness holds each dedicated block until its buffer is dropped"), + if let Placed::Pooled { block, range } = placed { + let pooled = (self.blocks.iter_mut()) + .find(|kept| kept.block.id == *block) + .expect("the harness keeps every pooled block it placed a buffer in"); + pooled.free.give(range.clone()); } } } @@ -327,8 +336,8 @@ impl crate::Device for Device { Storage::Private | Storage::Managed => rt::MemoryClass::Private, }; let placed = self.heap.borrow_mut().place(class, length)?; - let start = placed.range.as_ref().map_or(0, |range| range.start); - match self.device.new_buffer(placed.block, start, length, true) { + let (block, start) = placed.at(); + match self.device.new_buffer(block, start, length, true) { Ok(buffer) => Ok(Buffer { buffer, placed, diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 247f6649b..17ccb06f6 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -63,9 +63,9 @@ static destructor or an `atexit` handler: the consumer drops every handle, or ca A device the consumer dropped is never handed out again: only `Device::new` makes a `Device`, and the runtime's threads hold the device's core, never a handle. A call that configures what has started refuses typed, never answering Ok for nothing: every call of a committed command buffer -(`Refusal::Committed`), the release of a block not held (`Error::NoSuchBlock`), and a call that -needs a runtime thread after `Device::quiesce` (`Error::Quiesced`). `DeviceOptions` are read once, -by `Device::new`. +(`Refusal::Committed`), a call naming a block whose last handle is gone (`Error::NoSuchBlock`), +and a call that needs a runtime thread after `Device::quiesce` (`Error::Quiesced`). +`DeviceOptions` are read once, by `Device::new`. ### Counters @@ -82,9 +82,10 @@ in its memory. - `Device::take_block(class, len)` gives a block of `MemoryClass::Private` (device-local, no host mapping) or `MemoryClass::Shared` (host-visible, host-coherent and host-cached, mapped for the - block's life) memory, as a `BlockInfo`: its number, class, length, device address and, for - Shared, its host address. One `VkBuffer` spans each block, with every buffer usage and a device - address. Nothing in a block is exportable. + block's life) memory, as a `Block`: rt's own handle, with no Metal counterpart, which derefs to + the block's `BlockInfo` (its number, class, length, device address and, for Shared, its host + address). One `VkBuffer` spans each block, with every buffer usage and a device address. + Nothing in a block is exportable. - Up to its class's `MemoryClass::block_len`, 16 MiB of Shared memory and 64 MiB of Private on every device, a block is pooled. `Device::new` makes one block of each class before it returns, and the block-maker thread keeps one of each class ready after that, made off every caller's @@ -116,17 +117,22 @@ in its memory. - Every block reads zero when it is handed out, new or taken again, as Metal's new buffers do. A Shared block is zeroed through its mapping, which also makes every page resident before anyone holds it; a Private block by a GPU fill. -- `Device::release_block` gives a block back. It takes effect once no buffer of the block remains. - The block-maker thread then zeroes it and keeps it idle, pooled or dedicated, with the same - number, address and mapping, as its class's latest idle block. Each class keeps at most a bound - of idle bytes, 256 MiB of Shared memory and 128 MiB of Private, beside its ready block, which is - a reserve outside the bound: past it the oldest kept block is freed (after - `BlockMappings::unmap`), and a block longer than the bound is freed at once. A take - past the pooled length takes a kept dedicated block that it fits and fills at least half of +- Dropping a block's last handle gives the block back; `Device::release_block` consumes a handle, + that drop made explicit. Clones of a handle share one claim, so dropping one of two gives nothing + back. It takes effect once no buffer, command buffer or upload using the block remains. The + block-maker thread then zeroes it and keeps it idle, pooled or dedicated, with the same number, + address and mapping, as its class's latest idle block. Each class keeps at most a bound of idle + bytes, 256 MiB of Shared memory and 128 MiB of Private, beside its ready block, which is a + reserve outside the bound: past it the oldest kept block is freed (after + `BlockMappings::unmap`), and a block longer than the bound is freed at once. A take past the + pooled length takes a kept dedicated block that it fits and fills at least half of (`Metrics::dedicated_blocks_reused`) before it allocates, so a program that makes and releases large buffers frame after frame pays the allocation, and the driver's hold on the device's other calls that comes with it, once. `Gauges::shared_idle_bytes` and `Gauges::private_idle_bytes` - count what is kept. Block numbers are never reused during the device's life. + count what is kept. Once the last handle is gone the block's number names nothing + (`Error::NoSuchBlock`), and numbers are never reused during the device's life. The device's + teardown frees every block still claimed, after the consumer's `BlockMappings::unmap` returned + for it; a handle dropped after that does nothing. - `Device::new_buffer(block, offset, length, zeroed)` makes a `Buffer`: a view of the range, with no Vulkan object of its own. Its `gpu_address` is the block's address plus the offset, and its `contents` the block's mapping plus the offset, or `None` in a Private block. `zeroed` zeroes the diff --git a/crates/metal2vulkan-rt/src/block.rs b/crates/metal2vulkan-rt/src/block.rs new file mode 100644 index 000000000..8169d241f --- /dev/null +++ b/crates/metal2vulkan-rt/src/block.rs @@ -0,0 +1,95 @@ +//! The consumer's handle of a block ([`Block`]): one claim, which its clones share and whose last +//! handle's drop gives the block back. + +use crate::device::{lock, Core}; +use crate::memory::{self, BlockInfo}; +use std::fmt; +use std::ops::Deref; +use std::sync::{Arc, Mutex, PoisonError, Weak}; + +/// No Metal counterpart: rt's own handle of a block of memory the consumer places buffers in, as +/// a placement `MTLHeap`'s buffers sit in its memory +/// ([`Device::take_block`](crate::Device::take_block)). It derefs to the block's +/// [`BlockInfo`], plain data. +/// +/// Clones share one claim. Dropping the last handle gives the block back, as +/// [`Device::release_block`](crate::Device::release_block) does: the block's memory lives until +/// the last handle and the last buffer, command buffer or upload using it are gone, and is then +/// zeroed and kept idle, or freed. While a handle lives, the block's number names it to +/// [`Device::new_buffer`](crate::Device::new_buffer) and the other calls that take one; once the +/// last is gone, they answer [`Error::NoSuchBlock`](crate::Error::NoSuchBlock). The device's +/// teardown frees every block still claimed, after the consumer's +/// [`BlockMappings::unmap`](crate::BlockMappings::unmap) returned for it; a handle dropped after +/// that does nothing. +#[derive(Clone)] +pub struct Block { + claim: Arc, +} + +/// One claim of a block, which every clone of its handle shares. +pub(crate) struct Claim { + info: BlockInfo, + /// The device, which the block holds while the slot does. + core: Weak, + /// The block, until the last handle drops or the device's teardown takes it. + block: Mutex>>, +} + +impl Block { + /// A handle of a new claim of `block`, whose info is `info`, on `core`'s device; the device + /// keeps the claim by the block's number ([`Core::claims`]). + pub(crate) fn claim(core: &Arc, info: BlockInfo, block: memory::Block) -> Block { + let claim = Arc::new(Claim { + info, + core: Arc::downgrade(core), + block: Mutex::new(Some(Arc::new(block))), + }); + lock(&core.claims).insert(info.id, Arc::downgrade(&claim)); + Block { claim } + } + + /// Whether the block is of `core`'s device. + pub(crate) fn is_of(&self, core: &Arc) -> bool { + Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core) + } +} + +impl Claim { + /// The block, while the claim holds it. + pub(crate) fn block(&self) -> Option> { + lock(&self.block).clone() + } + + /// At the device's teardown: the block, which the claim no longer holds. + pub(crate) fn take(&self) -> Option> { + lock(&self.block).take() + } +} + +impl Deref for Block { + type Target = BlockInfo; + + fn deref(&self) -> &BlockInfo { + &self.claim.info + } +} + +impl fmt::Debug for Block { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Block").field(&self.claim.info).finish() + } +} + +impl Drop for Claim { + /// The last handle is gone: the device forgets the block's number and gives the block back, + /// as [`Device::release_block`](crate::Device::release_block) does, unless its teardown took + /// the block first. + fn drop(&mut self) { + let slot = self.block.get_mut().unwrap_or_else(PoisonError::into_inner); + let (Some(block), Some(core)) = (slot.take(), self.core.upgrade()) else { + return; + }; + lock(&core.claims).remove(&self.info.id); + core.work.release_block(&block); + } +} diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index fea9c6cf0..600119e20 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -2,17 +2,18 @@ //! its queues, its memory blocks, its threads, quiesce and teardown. use crate::arrays::Arrays; +use crate::block::{Block, Claim}; use crate::cache::{self, Caches}; use crate::complete::{self, Done}; use crate::counters::{Counters, Gauge}; -use crate::error::Error; +use crate::error::{Error, Refusal}; use crate::extension::{self, ConsumerFeature, DeviceExtension}; use crate::fill::Filler; use crate::floor; use crate::hazard::Ids; use crate::instance::{Instance, PhysicalDevice}; use crate::kernel_map::KernelMap; -use crate::memory::{self, Block, BlockId, BlockInfo, BlockMappings, Memory, MemoryClass, Pool}; +use crate::memory::{self, BlockId, BlockMappings, Memory, MemoryClass, Pool}; use crate::pipeline::PUSH_BYTES; use crate::places::Places; use crate::reaper::{self, Job, Reaper}; @@ -30,7 +31,7 @@ use std::collections::HashMap; use std::ffi::{c_char, CString}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -58,11 +59,10 @@ pub struct Device { shared: Arc, } -/// What the device's handles share: the core, the blocks the consumer holds, and the runtime's -/// threads, which hold the core but no handle. +/// What the device's handles share: the core and the runtime's threads, which hold the core but +/// no handle. struct Shared { core: Arc, - claims: Mutex>>, threads: Mutex, } @@ -161,6 +161,9 @@ pub(crate) struct Core { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fail_private: std::sync::atomic::AtomicU32, pub(crate) pool: Pool, + /// The blocks the consumer holds handles of, by number ([`Block`]): each claim goes once its + /// last handle drops, or at teardown. + pub(crate) claims: Mutex>>, /// The blocks textures are placed in. pub(crate) places: Places, /// The blocks Managed buffers' device copies are placed in. @@ -447,6 +450,7 @@ impl Device { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] fail_private: std::sync::atomic::AtomicU32::new(0), pool, + claims: Mutex::new(HashMap::new()), places: Places::new(), copies: Places::new(), filler, @@ -473,7 +477,6 @@ impl Device { let device = Device { shared: Arc::new(Shared { core, - claims: Mutex::new(HashMap::new()), threads: Mutex::new(Threads::default()), }), }; @@ -549,7 +552,7 @@ impl Device { } /// No Metal counterpart: takes a block of `class` memory at least `len` bytes long, for the - /// consumer to place buffers in. + /// consumer to place buffers in: a handle ([`Block`]) whose last drop gives it back. /// /// For `len` up to the class's [`MemoryClass::block_len`] (16 MiB Shared, 64 MiB Private) it /// is a pooled block of that length. The device's making makes one of each class, and the @@ -569,7 +572,7 @@ impl Device { /// [`Limit::MemoryAllocations`](crate::Limit::MemoryAllocations) where the block takes an /// allocation past the device's count; [`Error::Vulkan`] where the device is out of memory or /// lost; [`Error::Quiesced`]. - pub fn take_block(&self, class: MemoryClass, len: u64) -> Result { + pub fn take_block(&self, class: MemoryClass, len: u64) -> Result { let core = &self.shared.core; if core.closed() { return Err(Error::Quiesced); @@ -577,8 +580,8 @@ impl Device { let memory = core.take_memory(class, len)?; let info = memory.info(); core.pool.hand(memory.id); - lock(&self.shared.claims).insert(memory.id, Arc::new(Block::new(memory, Arc::clone(core)))); - Ok(info) + let block = memory::Block::new(memory, Arc::clone(core)); + Ok(Block::claim(core, info, block)) } /// No Metal counterpart: stops the runtime's threads and its GPU work, for a process about to @@ -615,7 +618,8 @@ impl Device { ) } - /// No Metal counterpart: gives a block back. + /// No Metal counterpart: gives a block back where `block` is its last handle: the drop of the + /// handle, made explicit ([`Block`]). /// /// It takes effect once no [`Buffer`](crate::Buffer) of the block remains and every command /// buffer that used it has retired. The block-maker thread then zeroes it and keeps it idle, @@ -625,13 +629,13 @@ impl Device { /// block serves a later [`take_block`](Device::take_block) past the pooled length that it /// fits and that fills at least half of it. /// - /// Err: [`Error::NoSuchBlock`] for a block the consumer does not hold. - pub fn release_block(&self, block: BlockId) -> Result<(), Error> { - let held = lock(&self.shared.claims) - .remove(&block) - .ok_or(Error::NoSuchBlock(block))?; - self.shared.core.work.release_block(&held); - drop(held); + /// Err: [`Refusal::OtherDevice`] for another device's block, whose handle is dropped all the + /// same. + pub fn release_block(&self, block: Block) -> Result<(), Error> { + if !block.is_of(&self.shared.core) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + drop(block); Ok(()) } @@ -656,11 +660,13 @@ impl Device { Arc::strong_count(&self.shared) } - /// A block the consumer holds. Err: [`Error::NoSuchBlock`]. - pub(crate) fn block(&self, id: BlockId) -> Result, Error> { - lock(&self.shared.claims) + /// A block the consumer holds a handle of. Err: [`Error::NoSuchBlock`]. + pub(crate) fn block(&self, id: BlockId) -> Result, Error> { + let claim = lock(&self.shared.core.claims) .get(&id) - .cloned() + .and_then(Weak::upgrade); + claim + .and_then(|claim| claim.block()) .ok_or(Error::NoSuchBlock(id)) } @@ -1071,16 +1077,18 @@ pub struct RawDevice<'a> { impl Drop for Shared { fn drop(&mut self) { let threads = self.take_threads(); - // The blocks the consumer still holds go back to the pool once the threads have stopped, - // for the core to free. No buffer of them is left: each holds a handle of the device. - let claims = std::mem::take( - self.claims - .get_mut() - .unwrap_or_else(PoisonError::into_inner), - ); let teardown = move |core: &Arc| { halt(core, threads, None, false); - drop(claims); + // The blocks the consumer still holds handles of go back to the pool once the threads + // have stopped and the consumer's unmap hook has returned for each (`halt`), for the + // core to free; a handle dropped later finds its claim empty. No buffer of them is + // left: each holds a handle of the device. + let claims: Vec> = lock(&core.claims).drain().map(|(_, c)| c).collect(); + let blocks: Vec> = (claims.iter()) + .filter_map(Weak::upgrade) + .filter_map(|claim| claim.take()) + .collect(); + drop(blocks); // The map's kernels hold the core: a kernel no state holds goes now, its modules and // pipelines freed with the core. core.kernels.clear(&core.counters); diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 72a0a3778..431543b1a 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -33,8 +33,8 @@ pub enum Error { Refused(Refusal), /// One of the device's or the runtime's fixed limits. Limit(Limit), - /// A block the consumer does not hold: never taken, or already released. Metal has no - /// counterpart: blocks are the consumer's memory, not Metal objects. + /// A block the consumer holds no handle of: never taken, or its last handle gone. Metal has + /// no counterpart: blocks are the consumer's memory, not Metal objects. NoSuchBlock(BlockId), /// The runtime could not start one of its threads. Metal has no counterpart. Thread(io::Error), @@ -121,10 +121,11 @@ pub enum Refusal { /// ([`CommandBuffer::encode_wait_for_event`](crate::CommandBuffer::encode_wait_for_event), /// [`CommandBuffer::encode_signal_event`](crate::CommandBuffer::encode_signal_event), or a /// [`ComputeCommandEncoder`](crate::ComputeCommandEncoder) or - /// [`BlitCommandEncoder`](crate::BlitCommandEncoder) call). + /// [`BlitCommandEncoder`](crate::BlitCommandEncoder) call), or a block of another device + /// given to [`Device::release_block`](crate::Device::release_block). /// - /// Basis: ours (an event's semaphore, a buffer's block, a texture's image and a pipeline - /// belong to the `VkDevice` that made them). + /// Basis: ours (an event's semaphore, a buffer's block, a texture's image, a pipeline and a + /// block belong to the `VkDevice` that made them). OtherDevice, /// A queue that may hold no command buffer /// ([`Device::new_command_queue`](crate::Device::new_command_queue) with a count of 0). diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index 543c467b3..71e870c19 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -10,6 +10,7 @@ mod arrays; mod blit; +mod block; mod buffer; mod cache; mod command; @@ -46,6 +47,7 @@ mod times; pub use arrays::{IndexClass, IndexGrant, ResourceId}; pub use blit::{BlitCommandEncoder, BufferLayout, TexturePlace}; +pub use block::Block; pub use buffer::{Buffer, MAX_BUFFER_LENGTH}; pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus}; pub use counters::{Counters, Gauges, Metrics}; diff --git a/crates/metal2vulkan-rt/src/memory.rs b/crates/metal2vulkan-rt/src/memory.rs index f90063794..feb16f05d 100644 --- a/crates/metal2vulkan-rt/src/memory.rs +++ b/crates/metal2vulkan-rt/src/memory.rs @@ -98,8 +98,9 @@ impl BlockId { /// Nearest Metal counterpart: the memory of a placement `MTLHeap`, which the consumer places /// buffers in ([`Device::new_buffer`](crate::Device::new_buffer)). /// -/// Plain data, not a handle: the block lives until it is released and its last buffer is gone, or -/// until the device is torn down. One `VkBuffer` spans it, with every buffer usage and a device +/// Plain data, which the block's handle ([`Block`](crate::Block)) derefs to: the block lives +/// until its last handle and its last buffer, command buffer or upload are gone, or until the +/// device is torn down. One `VkBuffer` spans it, with every buffer usage and a device /// address. Nothing in it is exportable. #[non_exhaustive] #[derive(Clone, Copy, Debug)] diff --git a/crates/metal2vulkan-rt/src/tests/blit.rs b/crates/metal2vulkan-rt/src/tests/blit.rs index 6c3a1d819..815ae96a9 100644 --- a/crates/metal2vulkan-rt/src/tests/blit.rs +++ b/crates/metal2vulkan-rt/src/tests/blit.rs @@ -1259,12 +1259,10 @@ pub(crate) mod on_device { let slice_bytes = slice2.write(13); let volume_bytes = volume0.write(15); let line_before = line1.write(19); - let block = (device.take_block(MemoryClass::Shared, 4096)) - .expect("a Shared block") - .id; + let block = (device.take_block(MemoryClass::Shared, 4096)).expect("a Shared block"); let mut next = 0; let mut buffer = |len: u64, seed: u8| { - let buffer = (device.new_buffer(block, next, len, true)).expect("a buffer"); + let buffer = (device.new_buffer(block.id, next, len, true)).expect("a buffer"); next += len.next_multiple_of(256); let bytes = pattern(len as usize, seed); write(&buffer, &bytes); @@ -1449,10 +1447,8 @@ pub(crate) mod on_device { #[test] fn every_device_fills_a_range_of_a_buffer() { each_device("blit_fill", |name, _, device| { - let block = (device.take_block(MemoryClass::Shared, 4096)) - .expect("a Shared block") - .id; - let buffer = (device.new_buffer(block, 256, 64, true)).expect("a buffer"); + let block = (device.take_block(MemoryClass::Shared, 4096)).expect("a Shared block"); + let buffer = (device.new_buffer(block.id, 256, 64, true)).expect("a buffer"); let before = pattern(64, 21); write(&buffer, &before); let queue = device.new_command_queue(4).expect("a queue"); @@ -1516,14 +1512,12 @@ pub(crate) mod on_device { fn every_device_synchronizes_a_managed_buffer() { each_device("blit_synchronize", |name, _, device| { let copied = !device.core().shared_is_device_local(); - let block = (device.take_block(MemoryClass::Shared, 4096)) - .expect("a Shared block") - .id; + let block = (device.take_block(MemoryClass::Shared, 4096)).expect("a Shared block"); let before = pattern(64, 21); - let start = (device.new_buffer(block, 256, 64, false)).expect("a buffer"); + let start = (device.new_buffer(block.id, 256, 64, false)).expect("a buffer"); write(&start, &before); drop(start); - let managed = (device.new_managed_buffer(block, 256, 64, 64)) + let managed = (device.new_managed_buffer(block.id, 256, 64, 64)) .unwrap_or_else(|error| panic!("{name}: {error}")); // Made before the first command buffer, whose upload moves it home. device @@ -1646,14 +1640,10 @@ pub(crate) mod on_device { device .grant_indices(IndexClass::Texture, 4096, 1) .expect("a grant"); - let shared = (device.take_block(MemoryClass::Shared, 4096)) - .expect("a Shared block") - .id; - let private = (device.take_block(MemoryClass::Private, 4096)) - .expect("a Private block") - .id; - let shared = (device.new_buffer(shared, 0, 256, true)).expect("a Shared buffer"); - let private = (device.new_buffer(private, 0, 256, true)).expect("a Private buffer"); + let shared = (device.take_block(MemoryClass::Shared, 4096)).expect("a Shared block"); + let private = (device.take_block(MemoryClass::Private, 4096)).expect("a Private block"); + let shared = (device.new_buffer(shared.id, 0, 256, true)).expect("a Shared buffer"); + let private = (device.new_buffer(private.id, 0, 256, true)).expect("a Private buffer"); let texture = texture( &device, TextureType::Type2D, @@ -1708,11 +1698,9 @@ pub(crate) mod on_device { #[test] fn every_device_synchronizes_a_managed_texture_into_its_named_bytes() { each_device("blit_synchronize_texture", |name, _, device| { - let block = (device.take_block(MemoryClass::Shared, 8192)) - .expect("a Shared block") - .id; - let named = (device.new_buffer(block, 0, 2048, true)).expect("a buffer"); - let source = (device.new_buffer(block, 4096, 128, true)).expect("a buffer"); + let block = (device.take_block(MemoryClass::Shared, 8192)).expect("a Shared block"); + let named = (device.new_buffer(block.id, 0, 2048, true)).expect("a buffer"); + let source = (device.new_buffer(block.id, 4096, 128, true)).expect("a buffer"); let (level0, level1) = (pattern(64, 21), pattern(16, 99)); write(&source, &[level0.clone(), level1.clone()].concat()); let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 4, 4); diff --git a/crates/metal2vulkan-rt/src/tests/command.rs b/crates/metal2vulkan-rt/src/tests/command.rs index f343ffbe6..c35bf2b42 100644 --- a/crates/metal2vulkan-rt/src/tests/command.rs +++ b/crates/metal2vulkan-rt/src/tests/command.rs @@ -1,15 +1,17 @@ //! Command queues, command buffers and events, under a device cfg on every device of the cfg's //! kind: states, handlers and refusals; holds per segment; the host floor; host values racing GPU //! signals; listeners; abandon; quiesce, also in an `exit()` handler; teardown from a handler and -//! with work held; refusals of what has started; a loss; and a released block kept until its last -//! command buffer retires. +//! with work held; refusals of what has started; a loss; a released block kept until its last +//! command buffer retires; a block whose last handle drops freed once its last command buffer +//! retires; and a block's clones, one dropped giving nothing back, and a handle outliving its +//! device. #[cfg(any(m2v_gpu, m2v_cpu_icd))] pub(crate) mod on_device { use crate::device::lock; use crate::tests::devices_of_the_cfgs_kind; use crate::{ - host_time, BlockId, BlockMappings, Buffer, CommandBuffer, CommandBufferError, + host_time, Block, BlockId, BlockMappings, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, Device, DeviceOptions, DispatchType, Error, Gauges, Instance, MemoryClass, Refusal, SharedEvent, }; @@ -62,7 +64,7 @@ pub(crate) mod on_device { /// Buffers of 256 bytes in one Shared block, each zeroed. pub(crate) struct Arena { device: Device, - block: BlockId, + block: Block, next: u64, } @@ -73,7 +75,7 @@ pub(crate) mod on_device { .expect("a Shared block"); Arena { device: device.clone(), - block: block.id, + block, next: 0, } } @@ -81,7 +83,7 @@ pub(crate) mod on_device { pub(crate) fn buffer(&mut self) -> Buffer { let buffer = self .device - .new_buffer(self.block, self.next, 256, true) + .new_buffer(self.block.id, self.next, 256, true) .expect("a buffer"); self.next += 256; buffer @@ -355,10 +357,11 @@ pub(crate) mod on_device { let block = device .take_block(MemoryClass::Shared, 1) .expect("a Shared block"); - device.release_block(block.id).expect("a release"); + let id = block.id; + device.release_block(block).expect("a release"); assert!( - matches!(device.release_block(block.id), Err(Error::NoSuchBlock(id)) if id == block.id), - "{name}: release_block" + matches!(device.new_buffer(id, 0, 256, true), Err(Error::NoSuchBlock(gone)) if gone == id), + "{name}: a released block's number" ); assert_eq!( held.status(), @@ -1173,7 +1176,7 @@ pub(crate) mod on_device { let mut unmapped = lock(&hook.0).clone(); unmapped.sort(); - let mut handed = vec![(arena.block, None), (private.id, None)]; + let mut handed = vec![(arena.block.id, None), (private.id, None)]; handed.sort(); assert_eq!( unmapped, handed, @@ -1349,17 +1352,100 @@ pub(crate) mod on_device { held.encode_wait_for_event(f.as_event(), 1).expect("a wait"); held.commit().expect("a commit"); drop(buffer); - device.release_block(block.id).expect("a release"); + let id = block.id; + device.release_block(block).expect("a release"); thread::sleep(Duration::from_millis(50)); let pool = &device.core().pool; - assert!(!pool.holds(block.id), "{name}: back while in use"); + assert!(!pool.holds(id), "{name}: back while in use"); f.set_signaled_value(1); finished(name, &held); - within("the block's return", || pool.holds(block.id)); + within("the block's return", || pool.holds(id)); drop((f, queue, device)); }); } + /// A block whose last handle drops, with no `release_block`, while a held command buffer uses + /// it: its number names nothing at once, and the block stays live until the command buffer + /// completes, then is freed. It is a dedicated block, which the pool does not keep, so the + /// live allocations fall back to where they were. + #[test] + fn every_device_frees_a_dropped_block_once_its_last_command_buffer_retires() { + each_device("block_drop", |name, _, device| { + let counters = device.counters(); + let f = shared_event(&device); + let queue = queue(&device); + crate::tests::blit::on_device::settled(&device); + let before = counters.gauges().blocks; + // Longer than the class's idle bound, so it is freed once given back. + let len = MemoryClass::Shared.idle_bound() + 1; + let block = (device.take_block(MemoryClass::Shared, len)).expect("a dedicated block"); + let id = block.id; + let buffer = (device.new_buffer(id, 0, 4096, false)).expect("a buffer"); + let held = queue.command_buffer().expect("a command buffer"); + fill(&held, &buffer, 5); + held.encode_wait_for_event(f.as_event(), 1).expect("a wait"); + held.commit().expect("a commit"); + drop((buffer, block)); + assert!( + matches!(device.new_buffer(id, 0, 256, false), Err(Error::NoSuchBlock(gone)) if gone == id), + "{name}: the dropped block's number" + ); + thread::sleep(Duration::from_millis(50)); + assert_eq!( + counters.gauges().blocks, + before + 1, + "{name}: live while in use" + ); + f.set_signaled_value(1); + finished(name, &held); + within("the dropped block freed", || { + counters.gauges().blocks == before + }); + drop((f, queue, device)); + }); + } + + /// Clones of a block's handle share one claim: dropping one of two gives nothing back, and + /// the block's number still names it; releasing the other frees it. A handle that outlives + /// its device finds its block freed by the teardown, every gauge zero, and its drop does + /// nothing. + #[test] + fn every_device_frees_a_block_at_its_last_clone_and_at_teardown() { + each_device("block_clones", |name, _, device| { + let counters = device.counters(); + crate::tests::blit::on_device::settled(&device); + let before = counters.gauges().blocks; + // Longer than the class's idle bound, so it is freed once given back. + let len = MemoryClass::Shared.idle_bound() + 1; + let block = (device.take_block(MemoryClass::Shared, len)).expect("a dedicated block"); + let clone = block.clone(); + drop(block); + thread::sleep(Duration::from_millis(50)); + assert_eq!( + counters.gauges().blocks, + before + 1, + "{name}: one of two clones dropped" + ); + let buffer = (device.new_buffer(clone.id, 0, 256, false)) + .unwrap_or_else(|error| panic!("{name}: the clone's number: {error}")); + drop(buffer); + device.release_block(clone).expect("a release"); + within("the block freed at its last clone", || { + counters.gauges().blocks == before + }); + + let kept = (device.take_block(MemoryClass::Shared, len)).expect("a dedicated block"); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + drop(kept); + assert_eq!( + counters.gauges(), + Gauges::default(), + "{name}: a handle dropped after the teardown" + ); + }); + } + /// The child's device, its reader thread and whether it reads, for the exit handler. static EXIT_DEVICE: OnceLock = OnceLock::new(); static READER: Mutex>> = Mutex::new(None); @@ -1430,10 +1516,11 @@ pub(crate) mod on_device { held.encode_wait_for_event(event.as_event(), 1) .expect("a wait"); held.commit().expect("a commit"); - for block in &released { - device.release_block(block.id).expect("a release"); + for block in released { + device.release_block(block).expect("a release"); } - std::mem::forget((event, queue, held)); + // The block a reader thread reads stays taken until the process ends. + std::mem::forget((event, queue, held, block)); assert!(EXIT_DEVICE.set(device).is_ok()); // `exit()` from a thread other than the one that made the device, with nothing released. let exiting = thread::spawn(|| { diff --git a/crates/metal2vulkan-rt/src/tests/copy_over.rs b/crates/metal2vulkan-rt/src/tests/copy_over.rs index 1533c3f2e..78cb82377 100644 --- a/crates/metal2vulkan-rt/src/tests/copy_over.rs +++ b/crates/metal2vulkan-rt/src/tests/copy_over.rs @@ -234,7 +234,7 @@ mod on_device { "{name}: the texture's write in the buffer" ); drop((texture, scratch, source, buffer, queue)); - (device.release_block(cpu.id)).unwrap_or_else(|e| panic!("{name}: {e}")); + (device.release_block(cpu)).unwrap_or_else(|e| panic!("{name}: {e}")); }); } @@ -435,7 +435,7 @@ mod on_device { drop((texture, second, scratch, written, target, synced, first)); drop((buffer, kept, zero, out, arena, state, sum, queue)); - (device.release_block(cpu.id)).unwrap_or_else(|e| panic!("{name}: {e}")); + (device.release_block(cpu)).unwrap_or_else(|e| panic!("{name}: {e}")); }); } @@ -518,7 +518,7 @@ entry: assert!(held(&out)[..WORDS * 4] == ran, "{name}: the kernel ran"); used("a use after the kernel that leaves the buffer", 0); drop((texture, scratch, buffer, out, arena, state, queue)); - (device.release_block(cpu.id)).unwrap_or_else(|e| panic!("{name}: {e}")); + (device.release_block(cpu)).unwrap_or_else(|e| panic!("{name}: {e}")); }); } } diff --git a/crates/metal2vulkan-rt/src/tests/fence.rs b/crates/metal2vulkan-rt/src/tests/fence.rs index b06297ba6..923ceb100 100644 --- a/crates/metal2vulkan-rt/src/tests/fence.rs +++ b/crates/metal2vulkan-rt/src/tests/fence.rs @@ -34,11 +34,9 @@ mod on_device { #[test] fn every_device_orders_a_wait_after_an_update_and_records_nothing_for_either() { each_device("fences", |name, _, device| { - let block = (device.take_block(MemoryClass::Shared, 4096)) - .expect("a Shared block") - .id; - let filled = (device.new_buffer(block, 0, 64, false)).expect("a buffer"); - let out = (device.new_buffer(block, 256, 64, false)).expect("a buffer"); + let block = (device.take_block(MemoryClass::Shared, 4096)).expect("a Shared block"); + let filled = (device.new_buffer(block.id, 0, 64, false)).expect("a buffer"); + let out = (device.new_buffer(block.id, 256, 64, false)).expect("a buffer"); let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 4, 4); d.usage = TextureUsage::RENDER_TARGET; let texture = device.new_texture(&d, None).expect("a texture"); diff --git a/crates/metal2vulkan-rt/src/tests/heap.rs b/crates/metal2vulkan-rt/src/tests/heap.rs index 2d51d6747..9fe5a1576 100644 --- a/crates/metal2vulkan-rt/src/tests/heap.rs +++ b/crates/metal2vulkan-rt/src/tests/heap.rs @@ -150,7 +150,7 @@ mod on_device { heap.len ); drop((textures, alias)); - for block in [block.id, shared.id] { + for block in [block, shared] { device .release_block(block) .unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/managed.rs b/crates/metal2vulkan-rt/src/tests/managed.rs index 865285ca6..91ce09e5d 100644 --- a/crates/metal2vulkan-rt/src/tests/managed.rs +++ b/crates/metal2vulkan-rt/src/tests/managed.rs @@ -170,7 +170,7 @@ mod on_device { counters.metrics() ); drop((managed, into)); - for block in [cpu.id, private.id] { + for block in [cpu, private] { device .release_block(block) .unwrap_or_else(|error| panic!("{name}: {error}")); @@ -357,7 +357,7 @@ mod on_device { Ok(()) => panic!("{name}: a level past the texture went"), } drop((texture, plain, named, unmapped)); - for block in [cpu.id, private.id] { + for block in [cpu, private] { device .release_block(block) .unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/memory.rs b/crates/metal2vulkan-rt/src/tests/memory.rs index e4677b151..5bfb72a0f 100644 --- a/crates/metal2vulkan-rt/src/tests/memory.rs +++ b/crates/metal2vulkan-rt/src/tests/memory.rs @@ -85,8 +85,8 @@ mod on_device { use crate::device::lock; use crate::tests::devices_of_the_cfgs_kind; use crate::{ - BlockId, BlockInfo, BlockMappings, Buffer, CommandBufferStatus, Device, DeviceOptions, - Error, Gauges, Instance, Limit, MemoryClass, Refusal, MAX_BUFFER_LENGTH, + Block, BlockId, BlockInfo, BlockMappings, Buffer, CommandBufferStatus, Device, + DeviceOptions, Error, Gauges, Instance, Limit, MemoryClass, Refusal, MAX_BUFFER_LENGTH, }; use ash::vk; use std::collections::HashMap; @@ -147,7 +147,7 @@ mod on_device { } /// A Shared block's bytes. - fn bytes(block: BlockInfo) -> &'static mut [u8] { + fn bytes(block: &BlockInfo) -> &'static mut [u8] { let contents = block.contents.expect("a Shared block's contents"); // SAFETY: the mapping spans the block, which the test holds while it uses the slice. unsafe { std::slice::from_raw_parts_mut(contents.as_ptr(), block.len as usize) } @@ -373,7 +373,7 @@ mod on_device { "{name}: only the 2 GiB buffer" ); drop(buffer); - device.release_block(block.id).expect("a release"); + device.release_block(block).expect("a release"); drop(device); let gauges = counters.gauges(); print_gauges_at_drop("buffer_2_gib", gauges); @@ -410,7 +410,7 @@ mod on_device { (MemoryClass::Shared, MemoryClass::Shared.block_len()) ); assert_ne!(shared.gpu_address, 0, "{name}: a Shared block's address"); - let host = bytes(shared); + let host = bytes(&shared); assert!( host.iter().all(|&byte| byte == 0), "{name}: a new Shared block" @@ -554,7 +554,7 @@ mod on_device { .take_block(MemoryClass::Shared, past + 1) .expect("a dedicated block"); assert_eq!(dedicated.len, past + (64 << 10)); - let dedicated_host = bytes(dedicated); + let dedicated_host = bytes(&dedicated); assert!( dedicated_host.iter().all(|&byte| byte == 0), "{name}: a dedicated block" @@ -567,14 +567,11 @@ mod on_device { // Released, it lives while its buffer does, then, longer than the bound, is freed // through the hook on the block-maker thread, still mapped. - device.release_block(dedicated.id).expect("a release"); + let dedicated_id = dedicated.id; + device.release_block(dedicated).expect("a release"); assert!(matches!( - device.release_block(dedicated.id), - Err(Error::NoSuchBlock(id)) if id == dedicated.id - )); - assert!(matches!( - device.new_buffer(dedicated.id, 0, 16, false), - Err(Error::NoSuchBlock(_)) + device.new_buffer(dedicated_id, 0, 16, false), + Err(Error::NoSuchBlock(id)) if id == dedicated_id )); assert!( hook.unmapped().is_empty(), @@ -589,7 +586,7 @@ mod on_device { }); let unmapped = hook.unmapped(); assert_eq!(unmapped.len(), 1, "{name}: {unmapped:?}"); - assert_eq!(unmapped[0].block, dedicated.id.get()); + assert_eq!(unmapped[0].block, dedicated_id.get()); assert_eq!(unmapped[0].thread.as_deref(), Some("m2v-blocks")); assert_eq!( unmapped[0].first, @@ -603,7 +600,7 @@ mod on_device { let gauges = counters.gauges(); print_gauges_at_drop("blocks_teardown", gauges); assert_eq!(gauges, Gauges::default(), "{name}: gauges after teardown"); - assert_each_unmapped_once(name, &hook, &[shared.id, private.id, dedicated.id]); + assert_each_unmapped_once(name, &hook, &[shared.id, private.id, dedicated_id]); for unmapped in &hook.unmapped()[1..] { assert_eq!(unmapped.thread, this_thread, "{name}: {unmapped:?}"); } @@ -673,7 +670,7 @@ mod on_device { let shared_len = MemoryClass::Shared.block_len(); let room = MemoryClass::Shared.idle_bound() / shared_len; - let taken: Vec = (0..room + 2) + let taken: Vec = (0..room + 2) .map(|_| { device .take_block(MemoryClass::Shared, shared_len) @@ -682,7 +679,7 @@ mod on_device { .collect(); for block in &taken { handed.push(block.id); - let host = bytes(*block); + let host = bytes(block); host[0] = 0x5A; host[host.len() - 1] = 0x5A; hook.record(block); @@ -691,8 +688,9 @@ mod on_device { wait_until("a ready block of each class", || { counters.gauges().blocks == ZERO_SOURCE + 2 + room + 2 }); - for block in &taken { - device.release_block(block.id).expect("a release"); + let infos: Vec = taken.iter().map(|block| **block).collect(); + for block in taken { + device.release_block(block).expect("a release"); } // The bound's worth of Shared blocks kept beside the ready one, the ready Private // block, the zero source. @@ -715,7 +713,7 @@ mod on_device { MemoryClass::Shared.idle_bound() + shared_len, "{name}: the bound's worth kept beside the ready block" ); - let kept: Vec<&BlockInfo> = taken + let kept: Vec<&BlockInfo> = infos .iter() .filter(|block| unmapped.iter().all(|u| u.block != block.id.get())) .collect(); @@ -732,7 +730,7 @@ mod on_device { .unwrap_or_else(|| panic!("{name}: a kept block")); assert_eq!(again.gpu_address, was.gpu_address); assert_eq!(again.contents, was.contents); - let host = bytes(again); + let host = bytes(&again); assert!( host.iter().all(|&byte| byte == 0), "{name}: a block taken again" @@ -741,9 +739,10 @@ mod on_device { // A Private block written by the GPU and released reads zero when taken again. let gpu = Gpu::new(&device); - let private = device + let private_block = device .take_block(MemoryClass::Private, 1) .expect("a Private block"); + let private = *private_block; handed.push(private.id); gpu.fill( vk_buffer(&device, private.id), @@ -751,9 +750,9 @@ mod on_device { MemoryClass::Private.block_len(), u32::MAX, ); - device.release_block(private.id).expect("a release"); + device.release_block(private_block).expect("a release"); // The pool zeroes and keeps it before it makes anything, so it is one of the next two. - let next: Vec = (0..2) + let next: Vec = (0..2) .map(|_| device.take_block(MemoryClass::Private, 1).expect("a block")) .collect(); handed.extend(next.iter().map(|block| block.id)); @@ -807,7 +806,7 @@ mod on_device { let device = device_with(&hook, physical, name); let counters = device.counters(); let shared_len = MemoryClass::Shared.block_len(); - let taken: Vec = (0..3) + let taken: Vec = (0..3) .map(|_| { (device.take_block(MemoryClass::Shared, 100 * MIB)) .unwrap_or_else(|error| panic!("{name}: a dedicated block: {error}")) @@ -816,14 +815,15 @@ mod on_device { let mut handed: Vec = taken.iter().map(|block| block.id).collect(); for block in &taken { assert_eq!(block.len, 100 * MIB, "{name}: a dedicated block"); - let host = bytes(*block); + let host = bytes(block); host[0] = 0x5A; host[host.len() - 1] = 0x5A; hook.record(block); } assert_eq!(counters.metrics().dedicated_blocks_reused, 0, "{name}"); - for block in &taken { - device.release_block(block.id).expect("a release"); + let infos: Vec = taken.iter().map(|block| **block).collect(); + for block in taken { + device.release_block(block).expect("a release"); } // Two kept beside the ready block; the oldest freed. wait_until("one dedicated block freed", || hook.unmapped().len() == 1); @@ -832,7 +832,7 @@ mod on_device { }); let unmapped = hook.unmapped(); assert_eq!(unmapped[0].thread.as_deref(), Some("m2v-blocks"), "{name}"); - let kept: Vec<&BlockInfo> = taken + let kept: Vec<&BlockInfo> = infos .iter() .filter(|block| block.id.get() != unmapped[0].block) .collect(); @@ -852,7 +852,7 @@ mod on_device { "{name}: the kept block as it was" ); assert!( - bytes(again).iter().all(|&byte| byte == 0), + bytes(&again).iter().all(|&byte| byte == 0), "{name}: a kept block taken again" ); assert_eq!(counters.metrics().blocks_made, made, "{name}: a block made"); @@ -863,22 +863,26 @@ mod on_device { "{name}: one kept block left" ); - // A request that fills less than half of it, and one it does not fit, make their own. + // A request that fills less than half of it, and one it does not fit, make their own, + // held to the teardown. + let mut owns = Vec::new(); for len in [40 * MIB, 101 * MIB] { let own = (device.take_block(MemoryClass::Shared, len)) .unwrap_or_else(|error| panic!("{name}: {len}: {error}")); assert_eq!(own.len, len, "{name}: a block of its own"); handed.push(own.id); + owns.push(own); } assert_eq!(counters.metrics().blocks_made, made + 2, "{name}"); assert_eq!(counters.metrics().dedicated_blocks_reused, 1, "{name}"); // A dedicated Private block is kept beside the Private ready block, and taken again. let private_len = MemoryClass::Private.block_len(); - let private = (device.take_block(MemoryClass::Private, private_len + 1)) + let private_block = (device.take_block(MemoryClass::Private, private_len + 1)) .unwrap_or_else(|error| panic!("{name}: a dedicated Private block: {error}")); + let private = *private_block; handed.push(private.id); - device.release_block(private.id).expect("a release"); + device.release_block(private_block).expect("a release"); wait_until("the Private block kept", || { counters.gauges().private_idle_bytes == private_len + private.len }); diff --git a/crates/metal2vulkan-rt/src/tests/over.rs b/crates/metal2vulkan-rt/src/tests/over.rs index be03f5be8..b6ae009f1 100644 --- a/crates/metal2vulkan-rt/src/tests/over.rs +++ b/crates/metal2vulkan-rt/src/tests/over.rs @@ -335,7 +335,7 @@ mod on_device { ); drop((texture, plain, buffer, command_buffer, queue, over, managed)); - (device.release_block(cpu.id)).unwrap_or_else(|error| panic!("{name}: {error}")); + (device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}")); }); } } diff --git a/crates/metal2vulkan-rt/src/tests/places.rs b/crates/metal2vulkan-rt/src/tests/places.rs index 63b8b87cb..093195c8c 100644 --- a/crates/metal2vulkan-rt/src/tests/places.rs +++ b/crates/metal2vulkan-rt/src/tests/places.rs @@ -228,7 +228,7 @@ mod on_device { "{name}: a dedicated {class:?} block" ); for block in [pooled, dedicated] { - (device.release_block(block.id)) + (device.release_block(block)) .unwrap_or_else(|error| panic!("{name}: a release: {error}")); } } diff --git a/crates/metal2vulkan-rt/src/tests/spill.rs b/crates/metal2vulkan-rt/src/tests/spill.rs index aa594cd99..2d360c42d 100644 --- a/crates/metal2vulkan-rt/src/tests/spill.rs +++ b/crates/metal2vulkan-rt/src/tests/spill.rs @@ -46,8 +46,7 @@ mod on_device { Ok(block) => { assert!(!block.device_local, "{name}: a spilled block"); assert_eq!(counters.gauges().spilled_bytes, block.len, "{name}"); - (device.release_block(block.id)) - .unwrap_or_else(|error| panic!("{name}: {error}")); + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); wait_until("the spilled block freed", || { counters.gauges().spilled_bytes == 0 }); @@ -100,7 +99,7 @@ mod on_device { counters.gauges() ); drop((texture, managed)); - for block in [plain.id, shared.id] { + for block in [plain, shared] { device .release_block(block) .unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 67c14d27d..b0415e661 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -17,7 +17,7 @@ mod on_device { use crate::tests::command::on_device::{each_device, finished, within}; use crate::tests::devices_of_the_cfgs_kind; use crate::{ - host_time, BlockId, Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, + host_time, Block, Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DeviceOptions, DispatchType, Error, FunctionDescriptor, Gauges, Instance, Library, Limit, MemoryClass, PrecisionNote, StageSource, MAX_BUFFER_LENGTH, }; @@ -160,7 +160,7 @@ mod on_device { /// Zeroed Shared buffers in one block, each at a 256-byte boundary. struct Buffers { device: Device, - block: BlockId, + block: Block, next: u64, } @@ -171,7 +171,7 @@ mod on_device { .expect("a Shared block"); Buffers { device: device.clone(), - block: block.id, + block, next: 0, } } @@ -179,7 +179,7 @@ mod on_device { fn buffer(&mut self, len: u64) -> Buffer { let buffer = self .device - .new_buffer(self.block, self.next, len, true) + .new_buffer(self.block.id, self.next, len, true) .expect("a buffer"); self.next += len.next_multiple_of(256); buffer diff --git a/crates/metal2vulkan-rt/src/tests/upload.rs b/crates/metal2vulkan-rt/src/tests/upload.rs index f283c6865..70b631963 100644 --- a/crates/metal2vulkan-rt/src/tests/upload.rs +++ b/crates/metal2vulkan-rt/src/tests/upload.rs @@ -215,8 +215,9 @@ mod on_device { .new_buffer(released.id, 0, 256, true) .unwrap_or_else(|error| panic!("{name}: {error}")); drop(buffer); + let released_id = released.id; device - .release_block(released.id) + .release_block(released) .unwrap_or_else(|error| panic!("{name}: {error}")); let (_, bytes, _) = core.work.pending(); assert!( @@ -231,7 +232,7 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); drop(buffer); wait_until("the released block back in the pool", || { - core.pool.holds(released.id) + core.pool.holds(released_id) }); // Zero fills past the upload's calls. @@ -251,7 +252,7 @@ mod on_device { drop(targets); device - .release_block(fills.id) + .release_block(fills) .unwrap_or_else(|error| panic!("{name}: {error}")); drop(device); wait_until("the teardown", || counters.gauges() == Gauges::default()); diff --git a/crates/metal2vulkan-rt/src/tests/view.rs b/crates/metal2vulkan-rt/src/tests/view.rs index 14141a903..55ad791b2 100644 --- a/crates/metal2vulkan-rt/src/tests/view.rs +++ b/crates/metal2vulkan-rt/src/tests/view.rs @@ -91,10 +91,8 @@ mod on_device { .expect("a grant"); let flat = parent(&device, false, 4096); let array = parent(&device, true, 4097); - let block = (device.take_block(MemoryClass::Shared, 256)) - .expect("a Shared block") - .id; - let out = (device.new_buffer(block, 0, 256, true)).expect("a buffer"); + let block = (device.take_block(MemoryClass::Shared, 256)).expect("a Shared block"); + let out = (device.new_buffer(block.id, 0, 256, true)).expect("a buffer"); let queue = device.new_command_queue(1).expect("a queue"); let read = |view: &Texture| bytes(&queue, view, &out); use TextureType::{Type2D, Type2DArray}; @@ -293,10 +291,8 @@ mod on_device { #[test] fn every_device_views_a_managed_texture_s_named_bytes() { each_device("managed texture views", |name, _, device| { - let block = (device.take_block(MemoryClass::Shared, 1)) - .expect("a Shared block") - .id; - let named = (device.new_buffer(block, 0, 4096, true)).expect("a buffer"); + let block = (device.take_block(MemoryClass::Shared, 1)).expect("a Shared block"); + let named = (device.new_buffer(block.id, 0, 4096, true)).expect("a buffer"); // A 4x4 2D array of 2 slices and 2 levels, each level and slice's rows 64 bytes // apart, 512 bytes after the one before. let places: Vec = (0..4) diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index e25aaac36..63781dbd9 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -46,8 +46,9 @@ enum Object { Blit(Box), /// A buffer, and its place where the backend placed it. Buffer(rt::Buffer, Option), - /// A block of the stream (`m2v.newBlockWithLength:storageMode:`) or a heap: its range. - Block(rt::HeapRange, rt::MemoryClass), + /// A block of the stream (`m2v.newBlockWithLength:storageMode:`) or a heap: its range, and + /// the handle that keeps the block while the object lives. + Block(rt::HeapRange, rt::MemoryClass, rt::Block), Texture(rt::Texture), TextureDescriptor(Box), Library(rt::Library), @@ -747,20 +748,20 @@ impl NewRuntime { 2 => rt::MemoryClass::Private, other => return Err(refuse(call, format!("a block of storage mode {other}"))), }; - let info = self + let block = self .device .take_block(class, length) .map_err(failed(call))?; self.block_bytes[class_index(class)] += length; let made = Made { - address: Some(info.gpu_address), + address: Some(block.gpu_address), }; let range = rt::HeapRange { - block: info.id, + block: block.id, offset: 0, len: length, }; - Ok(Some((Object::Block(range, class), made))) + Ok(Some((Object::Block(range, class, block), made))) } "newLibraryWithData:error:" => { let library = rt::Library::from_metallib(data(call, 0)?); @@ -983,10 +984,8 @@ impl Backend for NewRuntime { Some(Object::Buffer(_, Some(place))) => self.places.give(place, self.commits), // The runtime keeps the block while a buffer of it lives or work uses it, as a // heap's resources keep the heap. - Some(Object::Block(range, class)) => { - self.device - .release_block(range.block) - .map_err(failed(call))?; + Some(Object::Block(range, class, block)) => { + self.device.release_block(block).map_err(failed(call))?; self.block_bytes[class_index(class)] -= range.len; } _ => {} @@ -1040,7 +1039,7 @@ impl Backend for NewRuntime { let buffer = buffer.clone(); self.buffer_call(call, &buffer)? } - Object::Block(range, class) => { + Object::Block(range, class, _) => { let (range, class) = (*range, *class); self.block_call(call, range, class)? } @@ -1108,7 +1107,7 @@ impl Backend for NewRuntime { fn write(&mut self, target: u64, offset: u64, bytes: &[u8]) -> Result<(), PlayError> { match self.objects.get(&target) { Some(Object::Buffer(buffer, _)) => write_into(buffer, offset, bytes), - Some(Object::Block(range, rt::MemoryClass::Shared)) => { + Some(Object::Block(range, rt::MemoryClass::Shared, _)) => { let whole = self .device .new_buffer(range.block, range.offset, range.len, false); diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/places.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/places.rs index 821c40e62..edca381b3 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/places.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/places.rs @@ -10,17 +10,17 @@ use std::ops::Range; /// Where a buffer's place starts: Metal's buffers lie at multiples of 256 bytes. const ALIGN: u64 = 256; -/// A buffer's place: its block, its bytes there, and the block's class where the block is its +/// A buffer's place: its block, its bytes there, and the block's handle where the block is its /// own. pub(super) struct Place { pub(super) block: rt::BlockId, pub(super) range: Range, - own: Option, + own: Option, } -/// One pooled block: its free ranges, in order. +/// One pooled block: its handle, and its free ranges, in order. struct Block { - info: rt::BlockInfo, + info: rt::Block, free: Vec>, } @@ -68,12 +68,12 @@ impl Places { ) -> Result { self.free_completed(completed)?; if len > class.block_len() { - let info = self.device.take_block(class, len)?; + let block = self.device.take_block(class, len)?; self.bytes[class_index(class)] += len; return Ok(Place { - block: info.id, + block: block.id, range: 0..len, - own: Some(class), + own: Some(block), }); } let span = len.next_multiple_of(ALIGN); @@ -117,9 +117,10 @@ impl Places { continue; } let (place, _) = self.held.swap_remove(at); - if let Some(class) = place.own { + if let Some(own) = place.own { + let class = own.class; // The runtime keeps the block for the command buffers that use it. - self.device.release_block(place.block)?; + self.device.release_block(own)?; self.bytes[class_index(class)] -= place.range.end; continue; } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 316a8991d..db0c6a420 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9368,9 +9368,9 @@ method metal2vulkan-rt::Device::new_shared_event pub fn new_shared_event(&self) method metal2vulkan-rt::Device::new_texture pub fn new_texture(&self, descriptor: &TextureDescriptor, index: Option) -> Result method metal2vulkan-rt::Device::quiesce pub fn quiesce(&self, timeout: Duration) -> bool method metal2vulkan-rt::Device::raw pub fn raw(&self) -> RawDevice<'_> -method metal2vulkan-rt::Device::release_block pub fn release_block(&self, block: BlockId) -> Result<(), Error> +method metal2vulkan-rt::Device::release_block pub fn release_block(&self, block: Block) -> Result<(), Error> method metal2vulkan-rt::Device::release_indices pub fn release_indices(&self, grant: IndexGrant) -> Result<(), Error> -method metal2vulkan-rt::Device::take_block pub fn take_block(&self, class: MemoryClass, len: u64) -> Result +method metal2vulkan-rt::Device::take_block pub fn take_block(&self, class: MemoryClass, len: u64) -> Result method metal2vulkan-rt::Device::with_present_queue pub fn with_present_queue(&self, f: impl FnOnce(vk::Queue) -> R) -> R method metal2vulkan-rt::DeviceExtension::name pub fn name(&self) -> &CStr method metal2vulkan-rt::DeviceExtension::new pub fn new(name: &CStr) -> DeviceExtension @@ -11451,6 +11451,7 @@ struct metal2vulkan-air::ir::ValueIndex #[derive(Clone, Copy, Debug, PartialEq, struct metal2vulkan-air::tensor_ops::Descriptor #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Descriptor struct metal2vulkan-air::tensor_ops::RunForm #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct RunForm struct metal2vulkan-rt::BlitCommandEncoder pub struct BlitCommandEncoder +struct metal2vulkan-rt::Block #[derive(Clone)] pub struct Block struct metal2vulkan-rt::BlockId #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct BlockId(u32) struct metal2vulkan-rt::BlockInfo #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub struct BlockInfo struct metal2vulkan-rt::Buffer #[derive(Clone)] pub struct Buffer @@ -12033,6 +12034,9 @@ trait-impl metal2vulkan-air::ir::Body impl Graph impl Graph for Body trait-impl metal2vulkan-air::ir::DataLayout impl Default impl Default for DataLayout trait-impl metal2vulkan-air::tensor_ops::Descriptor impl fmt::Display impl fmt::Display for Descriptor trait-impl metal2vulkan-rt::BlitCommandEncoder impl Drop impl Drop for BlitCommandEncoder +trait-impl metal2vulkan-rt::Block impl Deref impl Deref for Block +trait-impl metal2vulkan-rt::Block impl Drop impl Drop for Block +trait-impl metal2vulkan-rt::Block impl fmt::Debug impl fmt::Debug for Block trait-impl metal2vulkan-rt::BlockInfo impl fe impl Send unsafe impl Send for BlockInfo trait-impl metal2vulkan-rt::BlockInfo impl fe impl Sync unsafe impl Sync for BlockInfo trait-impl metal2vulkan-rt::ComputeCommandEncoder impl Drop impl Drop for ComputeCommandEncoder diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 0c1d33cb1..c94ddf6fe 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -620,7 +620,7 @@ Columns: | `ManagedBlockNotShared` | A Managed buffer whose bytes are in a Private block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: a Managed buffer's bytes are the consumer's, which it maps; a Private block has no mapping | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | | `ModifiedRange` | A changed range that leaves its buffer (`Buffer::did_modify_range`) | every device (a public call's own check of its arguments) | `ours`: the copy of such a range would write past the buffer's device copy | 1: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` | `-` | | `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | -| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image and a pipeline belong to the `VkDevice` that made them | 14: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)` (+11) | `-` | +| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image, a pipeline and a block belong to the `VkDevice` that made them | 15: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)` (+12) | `-` | | `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` | `-` | | `EncoderOpen` | A second encoder, an encode call, or a commit or enqueue, while an encoder of the command buffer is open | every device (a public call's own check of its arguments) | `metal-documented`: a command buffer has one active encoder at a time, ended by `endEncoding` before another is made or the command buffer is committed | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | | `NoPipeline` | A dispatch with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | @@ -1187,7 +1187,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::ManagedBlockNotShared`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` - `rt:Refusal::ModifiedRange`: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` - `rt:Refusal::Committed`: `crates/metal2vulkan-rt/src/command.rs (open)` -- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/fence.rs (used_on)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` +- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/device.rs (release_block)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/fence.rs (used_on)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` - `rt:Refusal::EncoderOpen`: `crates/metal2vulkan-rt/src/command.rs (open)` - `rt:Refusal::NoPipeline`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)`