diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index 42e37f2bf..4798a2bd1 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -11,8 +11,9 @@ //! //! A `Managed` buffer is the runtime's (`Device::new_managed_buffer`) over a range of a Shared //! block: its `contents` are the CPU's bytes, which the harness writes and names with -//! `did_modify_range`, and where the device is neither integrated nor a CPU the runtime keeps a -//! device copy, which the next commit brings up to date. +//! `did_modify_range`. Where the device is neither integrated nor a CPU the runtime keeps a device +//! copy, which the next commit brings up to date, at a range of a Private block the harness places +//! as it places a Private buffer of the same length, and frees with the buffer. //! //! Its known gaps and the device's limits (`Error::Unsupported`, `Error::Limit`) are typed //! refusals ([`Refused`]); its other errors are failures. @@ -170,17 +171,17 @@ impl Indices { } impl Device { - /// A `Managed` buffer over `length` bytes at `start` of Shared block `block`: its bytes zeroed - /// as a zeroed Shared buffer over them zeroes them, and its device copy, where it has one, - /// zeroed with nothing copied. + /// A `Managed` buffer over `length` bytes at `bytes` of a Shared block, its device copy at + /// `copy` of a Private block where the device keeps one: its bytes zeroed as a zeroed Shared + /// buffer over them zeroes them, and its device copy zeroed with nothing copied. fn new_managed_buffer( &self, - block: rt::BlockId, - start: u64, + bytes: (rt::BlockId, u64), + copy: Option<(rt::BlockId, u64)>, length: u64, ) -> std::result::Result { - drop(self.device.new_buffer(block, start, length, Some(0))?); - self.device.new_managed_buffer(block, start, length, 0) + drop(self.device.new_buffer(bytes.0, bytes.1, length, Some(0))?); + self.device.new_managed_buffer(bytes, copy, length, 0) } /// `make` at the next index of `class` that no earlier object still holds. @@ -231,10 +232,12 @@ impl Device { } } -/// `MTLBuffer`: the runtime's buffer, and its place, freed when it is dropped. +/// `MTLBuffer`: the runtime's buffer, and its place and a `Managed` buffer's device copy's, freed +/// when it is dropped. pub struct Buffer { buffer: rt::Buffer, placed: Placed, + copy: Option, heap: Rc>, } @@ -316,7 +319,11 @@ impl Heap { impl Drop for Buffer { fn drop(&mut self) { - self.heap.borrow_mut().free(&self.placed); + let mut heap = self.heap.borrow_mut(); + heap.free(&self.placed); + if let Some(copy) = &self.copy { + heap.free(copy); + } } } @@ -375,9 +382,27 @@ impl crate::Device for Device { Storage::Private => rt::MemoryClass::Private, }; let placed = self.heap.borrow_mut().place(class, length)?; + let copy = match storage { + Storage::Managed if !self.device.has_unified_memory() => { + match self + .heap + .borrow_mut() + .place(rt::MemoryClass::Private, length) + { + Ok(copy) => Some(copy), + Err(why) => { + self.heap.borrow_mut().free(&placed); + return Err(why); + } + } + } + _ => None, + }; let (block, start) = placed.at(); let made = match storage { - Storage::Managed => self.new_managed_buffer(block, start, length), + Storage::Managed => { + self.new_managed_buffer((block, start), copy.as_ref().map(Placed::at), length) + } Storage::Shared | Storage::Private => { self.device.new_buffer(block, start, length, Some(0)) } @@ -386,10 +411,15 @@ impl crate::Device for Device { Ok(buffer) => Ok(Buffer { buffer, placed, + copy, heap: Rc::clone(&self.heap), }), Err(why) => { - self.heap.borrow_mut().free(&placed); + let mut heap = self.heap.borrow_mut(); + heap.free(&placed); + if let Some(copy) = © { + heap.free(copy); + } Err(error(why)) } } diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index bd7b4b3ad..efc8b2aee 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -116,10 +116,9 @@ in its memory. `Gauges::spilled_bytes` counts the bytes until they are freed. A spilled allocation is freed once its last block is given back, so the next tries device-local memory again. Textures are not placed in a spilled block: a texture then takes an allocation of its own, which spills in the - same way where the image allows another type. A Managed buffer whose device copy finds no - device-local room for a copy block takes a Private block of its own, which spills the same way: - still its second copy, so `did_modify_range` and a GPU write keep Metal's two-copy rule. Where - no memory type has room, the buffer is refused with the allocation's error. + same way where the image allows another type. A Managed buffer's device copy that the consumer + places in a spilled block is still its second copy, so `did_modify_range` and a GPU write keep + Metal's two-copy rule. - Every `VkDeviceMemory` the runtime holds counts against the device's `maxMemoryAllocationCount`: each block (texture blocks among them), each texture's own allocation, the staging region (from the first texture copy on), the staging buffer of a copy larger than the region while it runs, the @@ -174,15 +173,18 @@ in its memory. translator may read as signed, so the consumer states a maximum buffer length (Metal's `maxBufferLength`) no larger than `MAX_BUFFER_LENGTH`, and places no buffer longer than that in a block, whether Metal's `newBufferWithLength:`, a heap's or a no-copy buffer stands behind it. -- `Device::new_managed_buffer(block, offset, length, copied)` makes a Managed buffer over a range - of a Shared block (`Refusal::ManagedBlockNotShared` for a Private one): the consumer's bytes, - which `contents` answers. Vulkan's device type picks its form, as `Device::has_unified_memory` - answers it. On an integrated or CPU device the buffer is its bytes, as a Shared buffer is, and - `did_modify_range` does nothing. Elsewhere shaders reach a device copy at `gpu_address`, always: - a place in a copy block, a Private block of the pool of 16 MiB (of the copy's own length past - that) that holds device copies alone, or where device-local memory has no room for one, a - Private block of the copy's own in whatever memory type has room. The rest past its first `copied` bytes is zeroed in the upload, - and those bytes are named as `did_modify_range` names a range. +- `Device::new_managed_buffer(bytes, copy, length, copied)` makes a Managed buffer whose bytes are + `length` bytes at `bytes`, a block the consumer holds and an offset in it: the consumer's bytes, + which `contents` answers, in a block the host maps (`Refusal::ManagedBlockNotShared` for a + Private one). Vulkan's device type picks its form, as `Device::has_unified_memory` answers it. + On an integrated or CPU device the buffer is its bytes, as a Shared buffer is, its `gpu_address` + theirs, `did_modify_range` does nothing, and `copy` is `None` (`Refusal::ManagedCopyOnUnified` + otherwise). Elsewhere shaders reach a device copy at `gpu_address`, always: `length` bytes at + `copy`, a Private block the consumer holds and an offset in it, placed by the consumer as it + places a Private buffer (`Refusal::ManagedCopyMissing` for none, `Refusal::ManagedCopyNotPrivate` + for a Shared block). Either offset is any byte, and `gpu_address` is the block's address plus + it. The copy's rest past its first `copied` bytes is zeroed in the upload, and those bytes are + named as `did_modify_range` names a range. `Buffer::did_modify_range(start, length)` names a range changed (`Refusal::ModifiedRange` past the buffer), merged with the buffer's others where they overlap or touch, and submits nothing. The next commit of a command buffer with commands, on any queue, takes the bytes of every range @@ -206,11 +208,15 @@ in its memory. `capture_waits`, `capture_streams`, `capture_overflows` and `capture_overflow_bytes` count them, `capture_copy_nanos` and `capture_wait_nanos` time the commits' host copies and waits, and `Gauges::capture_bytes` counts the ring and the staging blocks alive. A command buffer - keeps each device copy it uses until it retires; the copy's place is free then. + keeps each device copy it uses, and so the copy's block, until it retires. The consumer's ranges follow Metal's retention: it reuses a range only once the work that named the buffer there before has completed. A command buffer keeps each block it uses until it retires, -so a block released meanwhile goes back to the pool only then. +so a block released meanwhile goes back to the pool only then. Placement is the consumer's, and so +is the slack past a buffer's length: the runtime writes no byte of a block outside the ranges of +the buffers placed in it (a zero fill, a Managed buffer's copy-in and its device copy's zeroing +each cover exactly the buffer's bytes), so what lies between and after them is as the consumer +left it. ### The consumer's mappings @@ -230,8 +236,9 @@ after a quiesce. NVIDIA card the same free takes about 0.5 ms per 16 MiB. rt frees one block at a time and only after 20 ms with no commit. `Metrics::allocations_freed` counts the frees, and `Metrics::submissions_during_frees` the submits made while one was in progress. -- On a full discrete card a Managed buffer's device copy goes to another memory type, host memory - where the card has no other device-local type, and its kernels read it across the host link: +- On a full discrete card a Private block the consumer takes goes to another memory type, host + memory where the card has no other device-local type, and the kernels that read a Managed + buffer's device copy placed there read it across the host link: `Gauges::managed_spilled_bytes` counts those buffers' bytes while they live. ## Set 1 and index grants diff --git a/crates/metal2vulkan-rt/src/buffer.rs b/crates/metal2vulkan-rt/src/buffer.rs index f496bbb9a..543e7e2ae 100644 --- a/crates/metal2vulkan-rt/src/buffer.rs +++ b/crates/metal2vulkan-rt/src/buffer.rs @@ -1,5 +1,5 @@ //! Buffers: views of a range of a block, with no Vulkan object of their own; a Managed buffer's -//! device copy, where the device has one, is a place in a copy block ([`crate::places`]). +//! device copy, where the device has one, is a range of a Private block the consumer placed it in. use crate::capture::Named; use crate::counters::Gauge; @@ -8,7 +8,6 @@ use crate::error::{Error, Refusal}; use crate::fill; use crate::memory::{Block, BlockId, Mapping, Memory, MemoryClass}; use crate::over::ManagedOvers; -use crate::places::Place; use crate::submit::Held; use ash::vk; use std::ptr::NonNull; @@ -20,10 +19,6 @@ use std::sync::Arc; /// answers nil past a device's `maxBufferLength`; the consumer states one no larger than this. pub const MAX_BUFFER_LENGTH: u64 = 1 << 31; -/// The alignment of a device copy in its block: a multiple of every storage buffer, uniform buffer -/// and copy offset alignment Vulkan lets a device require. -const COPY_ALIGN: u64 = 256; - /// `MTLBuffer`: `length` bytes at `offset` in a block the consumer took, with no `VkBuffer` or /// memory of its own. Shaders reach it by its device address. /// @@ -50,56 +45,39 @@ struct Inner { overs: Arc, } -/// A Managed buffer's device copy: a place in a copy block of Private memory, which shaders reach. -/// The buffer, each command buffer that uses it and each upload that copies into it hold it; the -/// last gone frees its place. +/// A Managed buffer's device copy: `len` bytes at `offset` in a Private block the consumer placed +/// it in, which shaders reach. The buffer, each command buffer that uses it and each upload that +/// copies into it hold it, and so the block. Where the block spilled to another memory type than +/// the Private one, its bytes count in +/// [`Gauges::managed_spilled_bytes`](crate::Gauges::managed_spilled_bytes) while it lives. pub(crate) struct DeviceCopy { core: Arc, - at: CopyAt, - block: Memory, -} - -/// Where a device copy lies in its block. -enum CopyAt { - /// A place in a copy block of the device's set. - Place(Place), - /// The whole of a Private block of its own, taken where device-local memory had no room for - /// a copy block: in whatever memory type had room, its `len` bytes counted in - /// [`Gauges::managed_spilled_bytes`](crate::Gauges::managed_spilled_bytes) where that is not - /// device-local. - Own { len: u64 }, + block: Arc, + offset: u64, + len: u64, } impl DeviceCopy { /// The copy block's buffer. pub(crate) fn buffer(&self) -> vk::Buffer { - self.block.buffer + self.block.memory.buffer } /// The copy block's memory. pub(crate) fn memory(&self) -> &Memory { - &self.block + &self.block.memory } /// The copy's offset in [`buffer`](Self::buffer). pub(crate) fn offset(&self) -> u64 { - match self.at { - CopyAt::Place(place) => place.offset, - CopyAt::Own { .. } => 0, - } + self.offset } } impl Drop for DeviceCopy { fn drop(&mut self) { - match self.at { - CopyAt::Place(place) => self.core.copies.release(&self.core, place), - CopyAt::Own { len } => { - if self.block.spilled() { - self.core.counters.fall_by(Gauge::ManagedSpilledBytes, len); - } - self.core.pool.give_back(self.block); - } + if self.block.memory.spilled() { + (self.core.counters).fall_by(Gauge::ManagedSpilledBytes, self.len); } } } @@ -149,16 +127,8 @@ impl Device { max: MAX_BUFFER_LENGTH, })); } - let block = self.block(block)?; - let block_len = block.memory.len; - let end = offset - .checked_add(length) - .filter(|&end| end <= block_len) - .ok_or(Error::Refused(Refusal::BufferPastBlock { - offset, - length, - block_len, - }))?; + let block = self.placed(block, offset, length)?; + let end = offset + length; let contents = block.memory.mapping.map(|mapping| { // SAFETY: `offset` is inside the block. Mapping::new(unsafe { mapping.at(offset) }) @@ -178,38 +148,45 @@ impl Device { Ok(self.buffer(block, offset, length, contents, None)) } - /// `newBufferWithLength:options:` and `newBufferWithBytes:length:options:` with - /// `MTLResourceStorageModeManaged`: `length` bytes at `offset` in a Shared block the consumer - /// holds are the consumer's bytes, which [`Buffer::contents`] answers. Which form the buffer - /// takes is the device's memory-type query's answer: + /// `newBufferWithLength:options:`, `newBufferWithBytes:length:options:` and + /// `newBufferWithBytesNoCopy:length:options:deallocator:` with + /// `MTLResourceStorageModeManaged`: `length` bytes at `bytes` (a block the consumer holds and + /// the offset in it) are the consumer's bytes, which [`Buffer::contents`] answers. The block is + /// one the host maps: a Shared block. Which form the buffer takes is the device's memory-type + /// query's answer: /// /// - where Vulkan's device type is integrated or CPU ([`Device::has_unified_memory`]), the - /// buffer is its bytes, as a Shared buffer is, and [`Buffer::did_modify_range`] does - /// nothing; - /// - elsewhere shaders reach a device copy in Private memory the device holds, at - /// [`Buffer::gpu_address`]. The rest past its first `copied` bytes is zeroed, ahead of every - /// command buffer committed after this call, and those first bytes (all of them where - /// `copied` is the length or more) are named as [`Buffer::did_modify_range`] names a range: - /// the next commit takes them from the consumer's bytes. The consumer's own bytes are as it - /// wrote them. + /// buffer is its bytes, as a Shared buffer is, its [`Buffer::gpu_address`] the bytes' block's + /// address plus their offset, and [`Buffer::did_modify_range`] does nothing. `copy` is + /// `None`; + /// - elsewhere shaders reach a device copy at `copy`, `length` bytes at that offset in a + /// Private block the consumer holds, its [`Buffer::gpu_address`] that block's address plus + /// the offset. The rest past its first `copied` bytes is zeroed, ahead of every command + /// buffer committed after this call, and those first bytes (all of them where `copied` is + /// the length or more) are named as [`Buffer::did_modify_range`] names a range: the next + /// commit takes them from the consumer's bytes. The consumer's own bytes are as it wrote + /// them. /// - /// Metal keeps such a copy on a Mac with a discrete GPU. The consumer chooses the range of its - /// bytes, as for [`Device::new_buffer`]. A buffer a command buffer uses holds its device copy - /// until the command buffer retires. Where device-local memory has no room for a copy block, - /// the device copy is a Private block of its own in whatever memory type has room, still the - /// buffer's second copy, so the two-copy rule holds on every such device; its kernels then - /// read host memory, counted in - /// [`Gauges::managed_spilled_bytes`](crate::Gauges::managed_spilled_bytes). Where no memory - /// type has room, the buffer is refused, as Metal returns nil for a buffer it cannot make. + /// Metal keeps such a copy on a Mac with a discrete GPU, and places it itself. Here the + /// consumer places both, as it places every buffer ([`Device::new_buffer`]): any byte offset, + /// and it reuses either range only once the work that named the buffer there before has + /// completed. The runtime writes the copy's `length` bytes and no byte past them, so the + /// slack the consumer leaves after either range is the consumer's. A buffer a command buffer + /// uses holds its device copy's block until the command buffer retires. A copy placed in a + /// Private block that spilled to another memory type is still the buffer's second copy, so + /// the two-copy rule holds on every such device; its kernels then read host memory, its bytes + /// counted in [`Gauges::managed_spilled_bytes`](crate::Gauges::managed_spilled_bytes) while the + /// buffer lives. /// - /// Err: as [`Device::new_buffer`]; [`Refusal::ManagedBlockNotShared`] for a Private block; - /// [`Error::Quiesced`], and what taking a Private block or the upload's command buffer can - /// return (the allocation's out-of-device-memory error where no memory type has room), for a - /// device copy. + /// Err: as [`Device::new_buffer`], for either range; [`Refusal::ManagedBlockNotShared`] for + /// bytes in a block the host does not map; [`Refusal::ManagedCopyMissing`] for no `copy` where + /// the device keeps one, [`Refusal::ManagedCopyOnUnified`] for a `copy` where it keeps none + /// and [`Refusal::ManagedCopyNotPrivate`] for a `copy` in a Shared block; for a device copy, + /// [`Error::Quiesced`], and [`Error::Vulkan`] where the upload's command buffer cannot be made. pub fn new_managed_buffer( &self, - block: BlockId, - offset: u64, + bytes: (BlockId, u64), + copy: Option<(BlockId, u64)>, length: u64, copied: u64, ) -> Result { @@ -222,45 +199,41 @@ impl Device { max: MAX_BUFFER_LENGTH, })); } - let block = self.block(block)?; - let block_len = block.memory.len; - offset - .checked_add(length) - .filter(|&end| end <= block_len) - .ok_or(Error::Refused(Refusal::BufferPastBlock { - offset, - length, - block_len, - }))?; + let (block, offset) = bytes; + let block = self.placed(block, offset, length)?; let Some(mapping) = block.memory.mapping else { return Err(Error::Refused(Refusal::ManagedBlockNotShared { block: block.memory.id, })); }; + let core = self.core(); + let copy = match (core.unified_memory(), copy) { + (true, None) => None, + (true, Some(_)) => return Err(Error::Refused(Refusal::ManagedCopyOnUnified)), + (false, None) => return Err(Error::Refused(Refusal::ManagedCopyMissing)), + (false, Some((copy_block, copy_offset))) => { + let copy_block = self.placed(copy_block, copy_offset, length)?; + if copy_block.memory.class != MemoryClass::Private { + return Err(Error::Refused(Refusal::ManagedCopyNotPrivate { + block: copy_block.memory.id, + })); + } + Some((copy_block, copy_offset)) + } + }; // SAFETY: `offset` is inside the block. let contents = Some(Mapping::new(unsafe { mapping.at(offset) })); - let core = self.core(); - if core.unified_memory() { + let Some((copy_block, copy_offset)) = copy else { return Ok(self.buffer(block, offset, length, contents, None)); - } - let (at, copy_block) = match core.copies.place(core, length, COPY_ALIGN) { - Ok((place, copy_block)) => (CopyAt::Place(place), copy_block), - // No device-local room for a copy block: a Private block of the copy's own, in - // whatever memory type has room, which is Metal's own second copy; with none, the - // allocation's error. - Err(error) if error.is_out_of_device_memory() => { - let own = core.take_memory(MemoryClass::Private, length)?; - if own.spilled() { - core.counters.rise_by(Gauge::ManagedSpilledBytes, length); - } - (CopyAt::Own { len: length }, own) - } - Err(error) => return Err(error), }; + if copy_block.memory.spilled() { + core.counters.rise_by(Gauge::ManagedSpilledBytes, length); + } let copy = Arc::new(DeviceCopy { core: Arc::clone(core), - at, block: copy_block, + offset: copy_offset, + len: length, }); let copied = copied.min(length); if copied < length { @@ -293,6 +266,23 @@ impl Device { Ok(buffer) } + /// The block `block`, which the consumer holds, where `length` bytes at `offset` lie in it. + /// + /// Err: [`Error::NoSuchBlock`]; [`Refusal::BufferPastBlock`]. + fn placed(&self, block: BlockId, offset: u64, length: u64) -> Result, Error> { + let block = self.block(block)?; + let block_len = block.memory.len; + offset + .checked_add(length) + .filter(|&end| end <= block_len) + .ok_or(Error::Refused(Refusal::BufferPastBlock { + offset, + length, + block_len, + }))?; + Ok(block) + } + /// A new buffer's handle, counted in [`Gauges::buffers`](crate::Gauges::buffers). fn buffer( &self, @@ -320,10 +310,10 @@ impl Device { impl Buffer { /// `gpuAddress`: the block's device address plus the buffer's offset; of a Managed buffer with - /// a device copy, the copy's address. + /// a device copy, the copy block's device address plus the copy's offset. pub fn gpu_address(&self) -> u64 { match &self.inner.copy { - Some(copy) => copy.block.address + copy.offset(), + Some(copy) => copy.block.memory.address + copy.offset(), None => self.inner.block.memory.address + self.inner.offset, } } diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index b6c607d84..9e3f26b32 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -739,9 +739,10 @@ pub struct Gauges { /// was out of memory: blocks whose [`BlockInfo::device_local`](crate::BlockInfo) is false and /// textures' allocations of their own. pub spilled_bytes: u64, - /// Bytes of Managed buffers whose device copy is not in device-local memory: device-local - /// memory had no room when they were made, so the copy went to another memory type and their - /// kernels read host memory. Metal has no counterpart. + /// Bytes of Managed buffers whose device copy the consumer placed in a Private block that + /// spilled to another memory type than the Private one (device-local memory had no room when + /// the block's allocation was made), so their kernels read host memory; counted per buffer + /// while it lives. Metal has no counterpart. pub managed_spilled_bytes: u64, /// Bytes of idle Shared allocations, which hold no block anyone holds: those the idle rule /// keeps (at most the most bytes of Shared allocations in use over the last 3 seconds less diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index afa3692c3..b1736e04c 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -166,8 +166,6 @@ pub(crate) struct Core { pub(crate) claims: Mutex>>, /// The blocks textures are placed in. pub(crate) places: Places, - /// The blocks Managed buffers' device copies are placed in. - pub(crate) copies: Places, pub(crate) filler: Filler, pub(crate) recorders: Recorders, pub(crate) work: Work, @@ -469,7 +467,6 @@ impl Device { pool, claims: Mutex::new(HashMap::new()), places: Places::new(), - copies: Places::new(), filler, recorders: Recorders::new(family), work, @@ -1174,8 +1171,7 @@ impl Drop for Core { // SAFETY: every upload that copied through it retired, and no call reads it. unsafe { region.free(self) }; } - let placed = (self.places.remaining().into_iter()).chain(self.copies.remaining()); - let placed = placed.collect(); + let placed = self.places.remaining(); memory::free_all(self, placed); let pools = std::mem::take( self.query_pools diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 6c27be752..3489427cf 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -90,15 +90,38 @@ pub enum Refusal { /// The block's length. block_len: u64, }, - /// A Managed buffer whose bytes are in a Private block + /// A Managed buffer whose bytes are in a block the host does not map, a Private block /// ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer)). /// - /// Basis: ours (a Managed buffer's bytes are the consumer's, which it maps; a Private block - /// has no mapping). + /// Basis: ours (a Managed buffer's bytes are the consumer's, which the host reaches through + /// the block's mapping; a Private block has none). ManagedBlockNotShared { /// The block named. block: BlockId, }, + /// A Managed buffer given no place for its device copy on a device that keeps one, where + /// [`Device::has_unified_memory`](crate::Device::has_unified_memory) is false + /// ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer)). + /// + /// Basis: ours (Metal keeps a Managed buffer's second copy on a Mac with a discrete GPU; the + /// consumer places it, as it places every buffer). + ManagedCopyMissing, + /// A Managed buffer given a place for a device copy on a device that keeps none, where + /// [`Device::has_unified_memory`](crate::Device::has_unified_memory) is true + /// ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer)). + /// + /// Basis: ours (on unified memory a Managed buffer is its bytes, as Metal keeps one copy of a + /// Managed buffer on Apple silicon). + ManagedCopyOnUnified, + /// A Managed buffer whose device copy is placed in a block that is not Private + /// ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer)). + /// + /// Basis: ours (shaders reach the device copy in Private memory, device-local where it has + /// room, as a discrete GPU's Metal keeps the copy in its own memory). + ManagedCopyNotPrivate { + /// The block named. + block: BlockId, + }, /// A changed range that leaves its buffer ([`Buffer::did_modify_range`](crate::Buffer::did_modify_range)). /// /// Basis: ours (the copy of such a range would write past the buffer's device copy). @@ -1103,6 +1126,19 @@ impl fmt::Display for Refusal { "a Managed buffer's bytes are in block {}, which is Private", block.get() ), + Refusal::ManagedCopyMissing => write!( + f, + "a Managed buffer on a device without unified memory needs a place for its device copy" + ), + Refusal::ManagedCopyOnUnified => write!( + f, + "a Managed buffer on a device with unified memory keeps no device copy to place" + ), + Refusal::ManagedCopyNotPrivate { block } => write!( + f, + "a Managed buffer's device copy is placed in block {}, which is not Private", + block.get() + ), Refusal::ModifiedRange { start, length, diff --git a/crates/metal2vulkan-rt/src/places.rs b/crates/metal2vulkan-rt/src/places.rs index c33218aa2..b4f295a92 100644 --- a/crates/metal2vulkan-rt/src/places.rs +++ b/crates/metal2vulkan-rt/src/places.rs @@ -1,7 +1,6 @@ -//! Places: the Private blocks the runtime places its own resources in, taken as the consumer takes -//! blocks. The device has two sets: texture blocks, where textures' images are bound, and copy -//! blocks, which hold Managed buffers' device copies. Neither set holds the other's kind, so no -//! buffer lies beside an optimal image in one allocation. +//! Places: the Private blocks the runtime places textures' images in, taken as the consumer takes +//! blocks. A texture block holds images alone, so no buffer lies beside an optimal image in one +//! block. //! //! A place is a resource's bytes at a multiple of its alignment: the first that fits, in the //! blocks in the order they were taken; where none fits, the next block comes from the pool: of @@ -12,8 +11,7 @@ //! Nothing zeroes a texture's bytes, as Metal leaves a new texture's contents undefined. //! //! An image in a texture block is optimal. The block's own `VkBuffer`, which spans it, aliases the -//! images (Vulkan's memory aliasing), and nothing records through it. A copy block's `VkBuffer` is -//! what the device copies are reached through. +//! images (Vulkan's memory aliasing), and nothing records through it. use crate::device::{lock, Core}; use crate::error::Error; diff --git a/crates/metal2vulkan-rt/src/tests/blit.rs b/crates/metal2vulkan-rt/src/tests/blit.rs index b950b9057..539fbe0f2 100644 --- a/crates/metal2vulkan-rt/src/tests/blit.rs +++ b/crates/metal2vulkan-rt/src/tests/blit.rs @@ -1668,8 +1668,9 @@ pub(crate) mod on_device { // Into a Managed buffer: its bytes shaders reach, brought to the host by a // synchronize. let copied = !device.core().unified_memory(); - let managed = (device.new_managed_buffer(block.id, 512, 64, 64)) - .unwrap_or_else(|error| panic!("{name}: {error}")); + let managed = + (crate::tests::managed::on_device::new_managed(&device, block.id, 512, 64, 64)) + .unwrap_or_else(|error| panic!("{name}: {error}")); let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); encoder @@ -1723,8 +1724,9 @@ pub(crate) mod on_device { let start = (device.new_buffer(block.id, 256, 64, None)).expect("a buffer"); write(&start, &before); drop(start); - let managed = (device.new_managed_buffer(block.id, 256, 64, 64)) - .unwrap_or_else(|error| panic!("{name}: {error}")); + let managed = + (crate::tests::managed::on_device::new_managed(&device, block.id, 256, 64, 64)) + .unwrap_or_else(|error| panic!("{name}: {error}")); // Made before the first command buffer, whose upload moves it home. device .grant_indices(IndexClass::Texture, 4096, 1) diff --git a/crates/metal2vulkan-rt/src/tests/copy_over.rs b/crates/metal2vulkan-rt/src/tests/copy_over.rs index f8d27e882..0833d58ea 100644 --- a/crates/metal2vulkan-rt/src/tests/copy_over.rs +++ b/crates/metal2vulkan-rt/src/tests/copy_over.rs @@ -249,7 +249,7 @@ mod on_device { let cpu = (device.take_block(MemoryClass::Shared, 1)) .unwrap_or_else(|e| panic!("{name}: {e}")); let managed = |offset: u64| { - (device.new_managed_buffer(cpu.id, offset, LEN, 0)) + (crate::tests::managed::on_device::new_managed(&device, cpu.id, offset, LEN, 0)) .unwrap_or_else(|e| panic!("{name}: {e}")) }; let over = |buffer: &Buffer| { @@ -487,8 +487,9 @@ entry: let pitch = pitch(&device); let cpu = (device.take_block(MemoryClass::Shared, 1)) .unwrap_or_else(|e| panic!("{name}: {e}")); - let buffer = (device.new_managed_buffer(cpu.id, 0, LEN, 0)) - .unwrap_or_else(|e| panic!("{name}: {e}")); + let buffer = + (crate::tests::managed::on_device::new_managed(&device, cpu.id, 0, LEN, 0)) + .unwrap_or_else(|e| panic!("{name}: {e}")); let texture = (buffer.new_texture(&descriptor(), None, 0, pitch)) .unwrap_or_else(|e| panic!("{name}: {e}")); assert!( diff --git a/crates/metal2vulkan-rt/src/tests/managed.rs b/crates/metal2vulkan-rt/src/tests/managed.rs index 6c2af5968..dd875a468 100644 --- a/crates/metal2vulkan-rt/src/tests/managed.rs +++ b/crates/metal2vulkan-rt/src/tests/managed.rs @@ -10,7 +10,11 @@ //! gives back as it retires, and reads the bytes of its commit. Metal's two-copy rule holds where //! `Device::has_unified_memory` is false: a kernel's write stays in the device copy, and a range //! named with no host write puts the consumer's bytes back over it. A range past the buffer and a -//! Managed buffer over a Private block are refused, and every gauge reads zero after teardown. +//! Managed buffer over a Private block are refused, and every gauge reads zero after teardown. The +//! consumer places the device copy: at an odd offset of its Private block it holds the bytes there +//! and nowhere else, the consumer's slack after it and the bytes before it as the consumer left +//! them; a missing copy, a copy on a unified device, one in a Shared block and one past its block +//! are refused. //! //! Managed textures, on every device: the image takes the named bytes of a region at its upload //! and nothing outside it, `get_bytes` reads the named bytes, `replace_region` writes them and @@ -53,15 +57,32 @@ pub(crate) mod on_device { use crate::tests::command::on_device::{each_device, finished, within, Arena}; use crate::tests::compute::on_device::{add, step, WORDS}; use crate::{ - Block, Buffer, BytesPlace, CommandBuffer, ComputePipelineState, Device, DispatchType, - Error, MemoryClass, PixelFormat, Refusal, Region, StorageMode, TextureDescriptor, - TextureType, TextureUsage, + Block, BlockId, Buffer, BytesPlace, CommandBuffer, ComputePipelineState, Device, + DispatchType, Error, MemoryClass, PixelFormat, Refusal, Region, StorageMode, + TextureDescriptor, TextureType, TextureUsage, }; use ash::vk; use std::time::Instant; const LEN: u64 = 64 << 10; + /// [`Device::new_managed_buffer`] of `length` bytes at `offset` in Shared block `bytes`, placed + /// as a consumer places it: its device copy, where the device keeps one, at the start of a + /// Private block taken for it, which the buffer holds once the handle here is gone. + pub(crate) fn new_managed( + device: &Device, + bytes: BlockId, + offset: u64, + length: u64, + copied: u64, + ) -> Result { + if device.has_unified_memory() { + return device.new_managed_buffer((bytes, offset), None, length, copied); + } + let copy = device.take_block(MemoryClass::Private, length)?; + device.new_managed_buffer((bytes, offset), Some((copy.id, 0)), length, copied) + } + /// The bytes shaders reach at `managed`'s address, `len` of them, copied by the GPU into /// `into`, a Shared buffer as long. fn device_bytes(device: &Device, managed: &Buffer, into: &Buffer, len: u64) -> Vec { @@ -123,7 +144,7 @@ pub(crate) mod on_device { drop(start); // The first half copied, the rest zero. - let managed = (device.new_managed_buffer(cpu.id, 0, LEN, LEN / 2)) + let managed = (new_managed(&device, cpu.id, 0, LEN, LEN / 2)) .unwrap_or_else(|error| panic!("{name}: {error}")); let mut expected = first.clone(); if copied { @@ -187,7 +208,7 @@ pub(crate) mod on_device { } let private = (device.take_block(MemoryClass::Private, 1)) .unwrap_or_else(|error| panic!("{name}: {error}")); - match device.new_managed_buffer(private.id, 0, 256, 0) { + match device.new_managed_buffer((private.id, 0), None, 256, 0) { Err(Error::Refused(Refusal::ManagedBlockNotShared { block })) => { assert_eq!(block, private.id, "{name}") } @@ -207,6 +228,173 @@ pub(crate) mod on_device { }); } + /// The bytes of the whole of Private block `block`, `len` of them, copied by the GPU into + /// `into`, a Shared buffer as long; `through` is a buffer in the block for the command buffer + /// to keep. + fn block_bytes(device: &Device, through: &Buffer, into: &Buffer, len: u64) -> Vec { + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let (source, _) = through.device_range(); + let (target, to) = into.device_range(); + command_buffer + .record_for_test(&[through, into], |device, command| { + let region = vk::BufferCopy { + src_offset: 0, + dst_offset: to, + size: len, + }; + // SAFETY: the command buffer is recording; both ranges are the buffers' blocks', + // which it keeps. + unsafe { device.cmd_copy_buffer(command, source, target, &[region]) }; + }) + .expect("a copy"); + command_buffer.commit().expect("a commit"); + finished("the copy", &command_buffer); + read(into, len as usize) + } + + /// The consumer places a Managed buffer's device copy, at any byte offset. Where the device + /// keeps a copy: placed 4099 bytes into a Private block the consumer filled with `0xA5`, + /// `gpu_address` is the block's address plus 4099; the copy's first 600 bytes take the + /// consumer's bytes and the rest of its 1000 zeros, and nothing else of the block changes; a + /// GPU write into the consumer's slack past the copy (at 5100 to 5200) stays through a later + /// copy-in of the whole buffer, which lands at 4099 to 5099 alone. Without one the buffer is + /// its bytes, at their block's address plus their offset. A missing copy, a copy on a unified + /// device, a copy in a Shared block and a copy past its block are refused. + #[test] + fn every_device_places_a_managed_buffer_s_device_copy_where_the_consumer_says() { + const BLOCK: u64 = 64 << 10; + const AT: u64 = 4099; + const LENGTH: u64 = 1000; + const COPIED: u64 = 600; + each_device("managed placed", |name, _, device| { + let cpu = (device.take_block(MemoryClass::Shared, 2 * BLOCK)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let first: Vec = (0..LENGTH).map(|i| (i * 7 % 251 + 1) as u8).collect(); + let start = (device.new_buffer(cpu.id, 0, LENGTH, None)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + write(&start, 0, &first); + drop(start); + if device.has_unified_memory() { + let managed = (device.new_managed_buffer((cpu.id, AT), None, LENGTH, COPIED)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!( + managed.gpu_address(), + cpu.gpu_address + AT, + "{name}: one copy" + ); + let private = (device.take_block(MemoryClass::Private, BLOCK)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + match device.new_managed_buffer((cpu.id, 0), Some((private.id, 0)), 256, 0) { + Err(Error::Refused(Refusal::ManagedCopyOnUnified)) => {} + other => panic!( + "{name}: a copy on a unified device: {:?}", + other.map(|_| ()) + ), + } + println!("managed placed: {name}: no device copy"); + drop(managed); + for block in [cpu, private] { + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + } + return; + } + let private = (device.take_block(MemoryClass::Private, BLOCK)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let whole = (device.new_buffer(private.id, 0, BLOCK, None)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let into = (device.new_buffer(cpu.id, BLOCK, BLOCK, None)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let (target, base) = whole.device_range(); + let fill = |range: std::ops::Range, word: u32| { + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + command_buffer + .record_for_test(&[&whole], |device, command| { + // SAFETY: the command buffer is recording; the range is the block's, which + // it keeps, and whole words. + unsafe { + device.cmd_fill_buffer( + command, + target, + base + range.start, + range.end - range.start, + word, + ) + } + }) + .expect("a fill"); + command_buffer.commit().expect("a commit"); + finished("the fill", &command_buffer); + }; + fill(0..BLOCK, 0xA5A5_A5A5); + + let managed = + (device.new_managed_buffer((cpu.id, 0), Some((private.id, AT)), LENGTH, COPIED)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!( + managed.gpu_address(), + private.gpu_address + AT, + "{name}: the copy where the consumer placed it" + ); + // The consumer's write into its slack, in the commit that takes the first bytes in. + fill(5100..5200, 0x7777_7777); + let mut want = vec![0xA5; BLOCK as usize]; + want[AT as usize..(AT + COPIED) as usize].copy_from_slice(&first[..COPIED as usize]); + want[(AT + COPIED) as usize..(AT + LENGTH) as usize].fill(0); + want[5100..5200].fill(0x77); + assert!( + block_bytes(&device, &whole, &into, BLOCK) == want, + "{name}: the block after the copy's creation and the slack write" + ); + + // The whole buffer named: the copy-in lands on the copy alone. + let second: Vec = (0..LENGTH).map(|i| (i * 13 % 241 + 3) as u8).collect(); + write(&managed, 0, &second); + (managed.did_modify_range(0, LENGTH)).unwrap_or_else(|error| panic!("{name}: {error}")); + want[AT as usize..(AT + LENGTH) as usize].copy_from_slice(&second); + assert!( + block_bytes(&device, &whole, &into, BLOCK) == want, + "{name}: the block after a copy-in of the whole buffer" + ); + + let refused = |copy: Option<(BlockId, u64)>| { + device + .new_managed_buffer((cpu.id, 0), copy, 256, 0) + .map(|_| ()) + }; + match refused(None) { + Err(Error::Refused(Refusal::ManagedCopyMissing)) => {} + other => panic!("{name}: no copy: {other:?}"), + } + match refused(Some((cpu.id, BLOCK))) { + Err(Error::Refused(Refusal::ManagedCopyNotPrivate { block })) => { + assert_eq!(block, cpu.id, "{name}") + } + other => panic!("{name}: a copy in a Shared block: {other:?}"), + } + match refused(Some((private.id, private.len - 255))) { + Err(Error::Refused(Refusal::BufferPastBlock { + offset, + length: 256, + block_len, + })) => { + assert_eq!( + (offset, block_len), + (private.len - 255, private.len), + "{name}" + ) + } + other => panic!("{name}: a copy past its block: {other:?}"), + } + println!("managed placed: {name}: device copy at {AT} of its block"); + drop((managed, whole, into)); + for block in [cpu, private] { + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + } + }); + } + /// The add kernel over `managed`, a zeroed buffer and `out`, encoded into `command_buffer`: /// `out` takes the bytes the kernel reads of `managed`. fn kernel( @@ -240,16 +428,21 @@ pub(crate) mod on_device { let (zero, out) = (arena.buffer(), arena.buffer()); let cpu = (device.take_block(MemoryClass::Shared, 1)) .unwrap_or_else(|error| panic!("{name}: {error}")); - let managed = (device.new_managed_buffer(cpu.id, 0, len, 0)) + // The device copy where the consumer places it: 4 KiB into a Private block it takes. + let copy = two.then(|| { + (device.take_block(MemoryClass::Private, len + 4096)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }); + let at = copy.as_ref().map(|copy| (copy.id, 4096)); + let managed = (device.new_managed_buffer((cpu.id, 0), at, len, 0)) .unwrap_or_else(|error| panic!("{name}: {error}")); - if two { - assert_ne!( + match © { + Some(copy) => assert_eq!( managed.gpu_address(), - cpu.gpu_address, - "{name}: a device that is not unified keeps a device copy" - ); - } else { - assert_eq!(managed.gpu_address(), cpu.gpu_address, "{name}: one copy"); + copy.gpu_address + 4096, + "{name}: a device that is not unified keeps a device copy where it is placed" + ), + None => assert_eq!(managed.gpu_address(), cpu.gpu_address, "{name}: one copy"), } let host: Vec = (0..WORDS as u32).map(|i| i * 3 + 7).collect(); let bytes = @@ -294,10 +487,15 @@ pub(crate) mod on_device { "the kernel's write" } ); - println!("managed two copies: {name}: two copies {two}"); + println!( + "managed two copies: {name}: two copies {two}, the copy's block device-local {:?}", + copy.as_ref().map(|copy| copy.device_local) + ); alive(&managed); drop((managed, zero, out, arena)); - (device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}")); + for block in [Some(cpu), copy].into_iter().flatten() { + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + } } #[test] @@ -321,7 +519,7 @@ pub(crate) mod on_device { let (zero, out) = (arena.buffer(), arena.buffer()); let cpu = (device.take_block(MemoryClass::Shared, 1)) .unwrap_or_else(|error| panic!("{name}: {error}")); - let managed = (device.new_managed_buffer(cpu.id, 0, 256, 0)) + let managed = (new_managed(&device, cpu.id, 0, 256, 0)) .unwrap_or_else(|error| panic!("{name}: {error}")); let state = add(&device); let queue = device.new_command_queue(4).expect("a queue"); @@ -409,7 +607,7 @@ pub(crate) mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let into = (device.new_buffer(side.id, 0, len, None)) .unwrap_or_else(|error| panic!("{name}: {error}")); - let managed = (device.new_managed_buffer(cpu.id, 0, len, 0)) + let managed = (new_managed(device, cpu.id, 0, len, 0)) .unwrap_or_else(|error| panic!("{name}: {error}")); write(&managed, 0, bytes); (managed.did_modify_range(0, len)).unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/over.rs b/crates/metal2vulkan-rt/src/tests/over.rs index 8400cdc7b..f57ed63c4 100644 --- a/crates/metal2vulkan-rt/src/tests/over.rs +++ b/crates/metal2vulkan-rt/src/tests/over.rs @@ -303,8 +303,9 @@ mod on_device { // Over a Managed buffer the image lies in the bytes shaders reach: its device copy, // where it has one, which replace_region's rows reach as did_modify_range's do. - let managed = (device.new_managed_buffer(cpu.id, 2 * AT, LEN, LEN)) - .unwrap_or_else(|error| panic!("{name}: {error}")); + let managed = + (crate::tests::managed::on_device::new_managed(&device, cpu.id, 2 * AT, LEN, LEN)) + .unwrap_or_else(|error| panic!("{name}: {error}")); let mut bytes: Vec = (0..LEN).map(|i| (i % 239) as u8).collect(); write(&managed, &bytes); (managed.did_modify_range(0, LEN)).unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/spill.rs b/crates/metal2vulkan-rt/src/tests/spill.rs index 5173a6178..2b81d87f8 100644 --- a/crates/metal2vulkan-rt/src/tests/spill.rs +++ b/crates/metal2vulkan-rt/src/tests/spill.rs @@ -5,9 +5,10 @@ //! type, the take fails with the allocation's error. While the pool's Private blocks spill, a //! texture takes no texture block (an allocation of its own, itself spilled where the image takes //! another type, else the allocation's error), and Metal's two-copy rule holds for a Managed -//! buffer: where the device is not unified, its device copy is a Private block of its own in -//! another memory type, its bytes counted in `Gauges::managed_spilled_bytes` while it lives. Every -//! gauge reads zero after teardown. +//! buffer: where the device is not unified, its device copy, which the consumer places in a Private +//! block it takes while the pool's Private blocks spill, is in another memory type, its bytes +//! counted in `Gauges::managed_spilled_bytes` while it lives. Every gauge reads zero after +//! teardown. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index 56b1e6472..1a236aa9e 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -253,6 +253,9 @@ pub struct NewRuntime { /// The read-backs of a stream that records its announced bytes, kept out of the CPU copies /// (`aside`). asides: aside::Asides, + /// The places of the GPU copies of the Managed buffers in a place of the play's own, on a + /// device that keeps a GPU copy: given back with the buffer's place. + device_copies: HashMap, /// The queue each command buffer was made on. queue_of: HashMap, /// The bytes those copies staged. @@ -516,6 +519,7 @@ impl NewRuntime { users: HashMap::new(), seconds: second::Seconds::default(), asides: aside::Asides::default(), + device_copies: HashMap::new(), queue_of: HashMap::new(), staged_bytes: 0, unanswered_pipeline_ids: 0, @@ -748,9 +752,18 @@ impl NewRuntime { let shared = shared.map_err(failed(call))?; write_into(&shared, 0, bytes)?; let copied = bytes.len() as u64; - let managed = self.device.new_managed_buffer(block, start, length, copied); + // The GPU copy, placed as a Private buffer of its length is. + let copy = (self + .places + .take(rt::MemoryClass::Private, length, completed)) + .map_err(failed(call))?; + let at = (copy.block, copy.range.start); + let managed = + (self.device).new_managed_buffer((block, start), Some(at), length, copied); self.asides.two_copies(call.result); - managed.map_err(failed(call))? + let managed = managed.map_err(failed(call))?; + self.device_copies.insert(call.result, copy); + managed } _ => { let buffer = self.device.new_buffer(block, start, length, Some(0)); @@ -1341,19 +1354,37 @@ impl NewRuntime { range: rt::HeapRange, class: rt::MemoryClass, ) -> Result, PlayError> { - // A buffer of `length` bytes and storage options `raw` at `offset` in the block. + // A buffer of `length` bytes and storage options `raw` at `offset` in the block. A + // two-copy Managed one's GPU copy, on a device that keeps one, is the one place the play + // holds for it, placed as a Private buffer of its length is; the stream's block holds its + // bytes. let device = self.device.clone(); let mut placed = |length: u64, raw: u64, offset: u64| { let at = range.offset + offset; + let mut copy = None; let buffer = match storage(call, raw)? { rt::StorageMode::Managed if class == rt::MemoryClass::Shared => { match self.managed_form(call)? { ManagedCopies::One => device.new_buffer(range.block, at, length, None), + ManagedCopies::Two if device.has_unified_memory() => { + self.seconds.in_block += 1; + device.new_managed_buffer((range.block, at), None, length, length) + } ManagedCopies::Two => { - if device.has_unified_memory() { - self.seconds.in_block += 1; - } - device.new_managed_buffer(range.block, at, length, length) + let completed = self.completed(); + let place = + (self + .places + .take(rt::MemoryClass::Private, length, completed)) + .map_err(failed(call))?; + let copy_at = (place.block, place.range.start); + copy = Some(place); + device.new_managed_buffer( + (range.block, at), + Some(copy_at), + length, + length, + ) } } } @@ -1364,7 +1395,7 @@ impl NewRuntime { let placed = (call.receiver, offset..offset + length); self.unwritten.made(call.result, Some(placed)); } - addressed(buffer, None) + addressed(buffer, copy) }; match &*call.selector { "newBufferWithLength:options:offset:" => { @@ -1534,6 +1565,9 @@ impl Backend for NewRuntime { match self.objects.remove(&call.receiver) { Some(Object::Buffer(_, Some(place))) => { let users = self.users_of(call.receiver); + if let Some(copy) = self.device_copies.remove(&call.receiver) { + self.places.give(copy, self.commits, users.clone()); + } self.places.give(place, self.commits, users); } // The runtime keeps the block while a buffer of it lives or work uses it, as a diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 888de12b0..b1adc30b6 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9493,7 +9493,7 @@ method metal2vulkan-rt::Device::new_depth_stencil_state pub fn new_depth_stencil method metal2vulkan-rt::Device::new_event pub fn new_event(&self) -> Result method metal2vulkan-rt::Device::new_fence pub fn new_fence(&self) -> Fence method metal2vulkan-rt::Device::new_heap_texture pub fn new_heap_texture(&self, descriptor: &TextureDescriptor, index: Option, heap: HeapRange, offset: u64) -> Result -method metal2vulkan-rt::Device::new_managed_buffer pub fn new_managed_buffer(&self, block: BlockId, offset: u64, length: u64, copied: u64) -> Result +method metal2vulkan-rt::Device::new_managed_buffer pub fn new_managed_buffer(&self, bytes: (BlockId, u64), copy: Option<(BlockId, u64)>, length: u64, copied: u64) -> Result method metal2vulkan-rt::Device::new_managed_texture pub fn new_managed_texture(&self, descriptor: &TextureDescriptor, index: Option, bytes: &Buffer, places: &[BytesPlace]) -> Result method metal2vulkan-rt::Device::new_sampler_state pub fn new_sampler_state(&self, descriptor: &SamplerDescriptor, index: u32) -> Result method metal2vulkan-rt::Device::new_shared_event pub fn new_shared_event(&self) -> Result @@ -13712,6 +13712,9 @@ variant metal2vulkan-rt::Refusal::IndicesInUse IndicesInUse { class: IndexClass, variant metal2vulkan-rt::Refusal::IndicesNotGranted IndicesNotGranted { class: IndexClass, index: u32 } variant metal2vulkan-rt::Refusal::IndirectOffset IndirectOffset { offset: u64, length: u64 } variant metal2vulkan-rt::Refusal::ManagedBlockNotShared ManagedBlockNotShared { block: BlockId } +variant metal2vulkan-rt::Refusal::ManagedCopyMissing ManagedCopyMissing +variant metal2vulkan-rt::Refusal::ManagedCopyNotPrivate ManagedCopyNotPrivate { block: BlockId } +variant metal2vulkan-rt::Refusal::ManagedCopyOnUnified ManagedCopyOnUnified variant metal2vulkan-rt::Refusal::ManagedTextureBytes ManagedTextureBytes { level: u32, slice: u32 } variant metal2vulkan-rt::Refusal::ModifiedRange ModifiedRange { start: u64, length: u64, buffer_length: u64 } variant metal2vulkan-rt::Refusal::NoBufferAtIndex NoBufferAtIndex { index: u32 } diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 6b33a5713..40fc06bee 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,7 +37,7 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 51 | 51 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 54 | 54 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 20 | 20 | 0 | 0 | 0 | 0 | 0 | @@ -55,7 +55,7 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 20 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 23 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 7 | 3 | 0 | 0 | 0 | | The new runtime's `Gap` | 0 | 0 | 0 | 0 | 20 | 0 | 0 | 0 | @@ -618,8 +618,11 @@ Columns: |---|---|---|---|---|---| | `EmptyBuffer` | A buffer of no bytes (`Device::new_buffer` with a length of 0) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: newBufferWithLength:0 answers nil | 2: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`, `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | | `BufferTooLong` | A buffer longer than `MAX_BUFFER_LENGTH` (`Device::new_buffer`) | every device (a public call's own check of its arguments) | `ours`: this crate's cap: a buffer's every byte lies within 2^31 bytes of each bind address in it | 2: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`, `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | -| `BufferPastBlock` | A buffer whose range leaves its block (`Device::new_buffer`) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: a placement heap of 1 MiB answers nil for a 4096-byte buffer at offset 1,047,552 | 2: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`, `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | -| `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)` | `-` | +| `BufferPastBlock` | A buffer whose range leaves its block (`Device::new_buffer`) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: a placement heap of 1 MiB answers nil for a 4096-byte buffer at offset 1,047,552 | 1: `crates/metal2vulkan-rt/src/buffer.rs (placed)` | `-` | +| `ManagedBlockNotShared` | A Managed buffer whose bytes are in a block the host does not map, 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 the host reaches through the block's mapping; a Private block has none | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | +| `ManagedCopyMissing` | A Managed buffer given no place for its device copy on a device that keeps one, where `Device::has_unified_memory` is false... | every device (a public call's own check of its arguments) | `ours`: Metal keeps a Managed buffer's second copy on a Mac with a discrete GPU; the consumer places it, as it places every buffer | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | +| `ManagedCopyOnUnified` | A Managed buffer given a place for a device copy on a device that keeps none, where `Device::has_unified_memory` is true... | every device (a public call's own check of its arguments) | `ours`: on unified memory a Managed buffer is its bytes, as Metal keeps one copy of a Managed buffer on Apple silicon | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | +| `ManagedCopyNotPrivate` | A Managed buffer whose device copy is placed in a block that is not Private (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: shaders reach the device copy in Private memory, device-local where it has room, as a discrete GPU's Metal keeps the copy in its own memory | 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, a pipeline and a block belong to the `VkDevice` that made them | 23: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)` (+20) | `-` | @@ -1200,8 +1203,11 @@ Each refusal's sites, with the function that builds it. - `floor::SetLayout`: `crates/metal2vulkan-rt/src/arrays.rs (supported)` - `rt:Refusal::EmptyBuffer`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`; `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` - `rt:Refusal::BufferTooLong`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`; `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` -- `rt:Refusal::BufferPastBlock`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)`; `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` +- `rt:Refusal::BufferPastBlock`: `crates/metal2vulkan-rt/src/buffer.rs (placed)` - `rt:Refusal::ManagedBlockNotShared`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` +- `rt:Refusal::ManagedCopyMissing`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` +- `rt:Refusal::ManagedCopyOnUnified`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` +- `rt:Refusal::ManagedCopyNotPrivate`: `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_buffer_to_buffer)`; `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/pass.rs (check)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_depth_stencil_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_render_pipeline_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 0d8ca1ba1..271a5b43b 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -409,8 +409,10 @@ counted from 0), completes the work committed so far, reports as at the stream's the bytes it was made with: a copied buffer's bytes, or a no-copy one's bytes at its making (section 5). A stream with no identity record gives a no-copy buffer none, so its GPU copy takes the writes recorded before its first use (a commit of a command buffer one of whose encoders - names it), the nearest record the stream has of its bytes at its making. On a device with - unified memory the runtime keeps one copy anyway. The report's `managed` line says which form + names it), the nearest record the stream has of its bytes at its making. Where the device keeps + a GPU copy, the player places it as it places a Private buffer of the buffer's length (below), a + buffer made in a stream's block or heap included, and frees that range as it frees the buffer's. + On a device with unified memory the runtime keeps one copy anyway. The report's `managed` line says which form played and from what, counts the Managed buffers and the no-copy ones whose contents came from first use, not from create, and says where a two-copy recording played as one copy. - **Announced bytes** (both runtimes' backends). On a stream whose header has bit 0 set (section @@ -555,9 +557,10 @@ counted from 0), completes the work committed so far, reports as at the stream's runtime's. The counts are among its executed counters. A play with any of them above zero is no gate - result: `report.txt` says so on a `skipped` line. It places buffers of their own in the - runtime's blocks of 16 MiB of either class (a longer one in a block of its own), a - range freed for reuse once every command buffer committed before its release completed, gives + result: `report.txt` says so on a `skipped` line. It places buffers of their own, and the GPU + copies of two-copy Managed buffers, in the runtime's blocks of 16 MiB of either class (a longer + one in a block of its own), a range freed for reuse once every command buffer committed before + its release completed, gives the runtime back a block or heap of the stream at its release (`release_block`), and gives textures and sampler states indices from the whole of each index class (section 5): its `indices named N: ...` line counts the objects placed at the index the stream named, those @@ -600,7 +603,8 @@ union of the GPU intervals of the command buffers the frame waited for, where th them, which runs beside the rest; and the backend's gauges then, as they stand, never as growth: the new runtime's live blocks, buffers, textures, pipelines, kernels, command buffers, spilled bytes, Managed buffers' -spilled bytes (`managed_spilled_bytes`) and idle Shared and +spilled bytes (`managed_spilled_bytes`: the bytes of those whose GPU copy the player placed in a +spilled Private block) and idle Shared and Private bytes the pool keeps, and the bytes of the blocks the backend holds for the stream by class, `shared_block_bytes` and `private_block_bytes`; the old runtime's live memory blocks, empty ones kept and dedicated ones),