diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index b2e5bfbc6..12cdaa0fb 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -116,6 +116,19 @@ 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. The device's memory-type query picks its form. Where the Shared type + is device-local, 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`: a place in a copy block, a + Private block of the pool (a dedicated one past `BLOCK_LEN`) that holds device copies alone. Its + first `copied` bytes are copied from the consumer's and the rest zeroed, in the upload. + `Buffer::did_modify_range(start, length)` marks a range changed (`Refusal::ModifiedRange` past + the buffer): the upload copies it into the device copy as it goes, ahead of every command buffer + committed after the call on every queue, one copy command per buffer with its ranges merged where + they overlap or touch, and no CPU copy. The copy reads the consumer's bytes when the GPU reaches + it. Each change is one of the upload's 4,096 calls, so changes past them submit it and wait. A + command buffer keeps each device copy it uses until it retires; the copy's place is free then. 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, @@ -386,6 +399,8 @@ that touch blocks first. resource IDs it made up, with no fault. The consumer treats every byte on the device as guest-writable and keeps nothing there that it parses or trusts. - Presenting (the binary semaphore a command buffer signals for a present) comes with presenting. +- A Managed buffer's `synchronizeResource` comes with blit encoders. A Private allocation does not + yet go on to another memory type when device memory runs out. - An indirect dispatch's threadgroup counts are the GPU's to read, so a count above the device's `maxComputeWorkGroupCount` is not refused; Vulkan leaves such a dispatch undefined. A direct dispatch past it is split into dispatches of at most that many, each told its first @@ -719,6 +734,9 @@ only for a created device, so `PhysicalDevice::check` finds a type with each set | Shared | `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`, `VK_MEMORY_PROPERTY_HOST_CACHED_BIT` | Shared storage, which the host maps and reads | | ring | `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`, `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` | the parameter ring, which the host writes with no flush and the GPU reads | +Whether the Shared type also has `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT` decides a Managed buffer's +form: without it, shaders reach a device copy in Private memory (Memory blocks and buffers). + ### Chosen by a query Five features choose between two forms by the device's answer, and no other feature does: 16-bit diff --git a/crates/metal2vulkan-rt/src/buffer.rs b/crates/metal2vulkan-rt/src/buffer.rs index fc0e00adb..6c6559060 100644 --- a/crates/metal2vulkan-rt/src/buffer.rs +++ b/crates/metal2vulkan-rt/src/buffer.rs @@ -1,9 +1,14 @@ -//! Buffers: views of a range of a block, with no Vulkan object of their own. +//! 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`]). use crate::counters::Gauge; -use crate::device::Device; +use crate::device::{Core, Device}; use crate::error::{Error, Refusal}; -use crate::memory::{Block, BlockId, Mapping, MemoryClass}; +use crate::fill; +use crate::memory::{Block, BlockId, Mapping, Memory, MemoryClass}; +use crate::places::Place; +use crate::submit::Held; +use ash::vk; use std::ptr::NonNull; use std::sync::Arc; @@ -13,6 +18,10 @@ 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. /// @@ -27,10 +36,40 @@ struct Inner { device: Device, /// Its resource id, for the hazard sets. id: u32, + /// The block the consumer placed it in: of a Managed buffer, the block of its bytes. block: Arc, offset: u64, length: u64, contents: Option, + /// A Managed buffer's device copy, on a device whose Shared memory is not device-local. + copy: Option>, +} + +/// 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. +pub(crate) struct DeviceCopy { + core: Arc, + place: Place, + block: Memory, +} + +impl DeviceCopy { + /// The copy block's buffer. + pub(crate) fn buffer(&self) -> vk::Buffer { + self.block.buffer + } + + /// The copy's offset in [`buffer`](Self::buffer). + pub(crate) fn offset(&self) -> u64 { + self.place.offset + } +} + +impl Drop for DeviceCopy { + fn drop(&mut self) { + self.core.copies.release(&self.core, self.place); + } } impl Drop for Inner { @@ -96,8 +135,112 @@ impl Device { None => self.core().work.zero(self.core(), &block, offset, end)?, } } + 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: + /// + /// - where the Shared memory type is device-local, 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`]. Its first `copied` bytes (all of them where `copied` is the + /// length or more) are copied from the consumer's bytes, and the rest are zeroed, ahead of + /// every command buffer committed after this call; [`Buffer::did_modify_range`] copies a + /// range again. 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. + /// + /// 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, for a device copy. + pub fn new_managed_buffer( + &self, + block: BlockId, + offset: u64, + length: u64, + copied: u64, + ) -> Result { + if length == 0 { + return Err(Error::Refused(Refusal::EmptyBuffer)); + } + if length > MAX_BUFFER_LENGTH { + return Err(Error::Refused(Refusal::BufferTooLong { + length, + 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 Some(mapping) = block.memory.mapping else { + return Err(Error::Refused(Refusal::ManagedBlockNotShared { + block: block.memory.id, + })); + }; + // SAFETY: `offset` is inside the block. + let contents = Some(Mapping::new(unsafe { mapping.at(offset) })); + let core = self.core(); + if core.shared_is_device_local() { + return Ok(self.buffer(block, offset, length, contents, None)); + } + let (place, copy_block) = core.copies.place(core, length, COPY_ALIGN)?; + let copy = Arc::new(DeviceCopy { + core: Arc::clone(core), + place, + block: copy_block, + }); + let copied = copied.min(length); + if copied < length { + let start = copy.offset() + copied; + let end = copy.offset() + length; + core.work.upload( + core, + None, + [Held::Copy(Arc::clone(©))], + // SAFETY: the upload's command buffer is recording, under the work lock; the copy + // block's buffer has every usage, `start..end` lies in it, and the upload holds + // the copy. + |device, command| unsafe { + fill::record( + device, + command, + core.filler.zeros(), + copy.buffer(), + start, + end, + ) + }, + )?; + } + if copied > 0 { + core.work.modify(core, ©, &block, offset, 0, copied)?; + } + Ok(self.buffer(block, offset, length, contents, Some(copy))) + } + + /// A new buffer's handle, counted in [`Gauges::buffers`](crate::Gauges::buffers). + fn buffer( + &self, + block: Arc, + offset: u64, + length: u64, + contents: Option, + copy: Option>, + ) -> Buffer { self.core().counters.rise(Gauge::Buffers); - Ok(Buffer { + Buffer { inner: Arc::new(Inner { device: self.clone(), id: self.core().ids.take(), @@ -105,15 +248,50 @@ impl Device { offset, length, contents, + copy, }), - }) + } } } impl Buffer { - /// `gpuAddress`: the block's device address plus the buffer's offset. + /// `gpuAddress`: the block's device address plus the buffer's offset; of a Managed buffer with + /// a device copy, the copy's address. pub fn gpu_address(&self) -> u64 { - self.inner.block.memory.address + self.inner.offset + match &self.inner.copy { + Some(copy) => copy.block.address + copy.offset(), + None => self.inner.block.memory.address + self.inner.offset, + } + } + + /// `didModifyRange:`: the consumer changed `length` bytes from `start` of the buffer's bytes. + /// Of a Managed buffer with a device copy, the next submission's upload copies them into the + /// copy, ahead of every command buffer committed after this call on every queue; the copy + /// reads the bytes when the GPU reaches it, so a later write the consumer makes before then + /// may be seen. Of any other buffer it does nothing, as the GPU reads the consumer's bytes. + /// + /// Err: [`Refusal::ModifiedRange`] for a range that leaves the buffer; for a copy, + /// [`Error::Quiesced`], [`Error::Vulkan`] where the upload's command buffer cannot be made, + /// and with `VK_ERROR_DEVICE_LOST` where the device is lost while the call waits for the + /// upload to have room. + pub fn did_modify_range(&self, start: u64, length: u64) -> Result<(), Error> { + let inner = &self.inner; + let end = (start.checked_add(length)) + .filter(|&end| end <= inner.length) + .ok_or(Error::Refused(Refusal::ModifiedRange { + start, + length, + buffer_length: inner.length, + }))?; + let Some(copy) = &inner.copy else { + return Ok(()); + }; + if length == 0 { + return Ok(()); + } + let core = inner.device.core(); + core.work + .modify(core, copy, &inner.block, inner.offset, start, end) } /// `length`. @@ -137,14 +315,22 @@ impl Buffer { self.inner.offset } - /// Whether the buffer is in Shared memory, which the host reads. + /// Whether shaders reach the buffer in Shared memory, which the host reads. pub(crate) fn is_shared(&self) -> bool { - self.held_block().memory.class == MemoryClass::Shared + self.inner.copy.is_none() && self.inner.block.memory.class == MemoryClass::Shared } - /// The block, for a command buffer to keep. - pub(crate) fn held_block(&self) -> &Arc { - &self.inner.block + /// The block, and a Managed buffer's device copy, for a command buffer to keep. + pub(crate) fn held(&self) -> (&Arc, Option<&Arc>) { + (&self.inner.block, self.inner.copy.as_ref()) + } + + /// The `VkBuffer` shaders reach the buffer through and the buffer's offset in it. + pub(crate) fn device_range(&self) -> (vk::Buffer, u64) { + match &self.inner.copy { + Some(copy) => (copy.buffer(), copy.offset()), + None => (self.inner.block.memory.buffer, self.inner.offset), + } } /// Its resource id, for the hazard sets. diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index 32c4f6892..dce623be7 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -1,6 +1,7 @@ //! Command buffers: recorded at once into segments that event waits and signals split, and their //! states from creation to retirement. +use crate::buffer::{Buffer, DeviceCopy}; use crate::counters::Metric; use crate::device::{lock, Core, Device}; use crate::error::{Error, Refusal}; @@ -145,6 +146,9 @@ pub(crate) struct Gpu { /// Each block the commands use, once: a block released meanwhile is reused only after the /// command buffer retires. pub(crate) blocks: Vec>, + /// Each Managed buffer's device copy the commands use, once: its place is freed only after + /// the command buffer retires. + pub(crate) copies: Vec>, /// The pipeline states the commands use, once each, kept until the command buffer retires. pub(crate) pipelines: Vec, /// The textures and sampler states the encoders bound or declared, once each, kept until the @@ -211,6 +215,7 @@ impl CommandBuffer { recorder: None, segments: vec![Segment::default()], blocks: Vec::new(), + copies: Vec::new(), pipelines: Vec::new(), textures: Vec::new(), samplers: Vec::new(), @@ -517,7 +522,7 @@ impl CommandBuffer { building.wrote_host(); f(&building.device.core().device, command); for buffer in buffers { - building.keep(buffer.held_block()); + building.keep(buffer); } Ok(()) }) @@ -715,12 +720,20 @@ impl Building { self.gpu.ring.write(&core, bytes) } - /// Keeps `block` until the command buffer retires. - pub(crate) fn keep(&mut self, block: &Arc) { + /// Keeps `buffer`'s block, and its device copy where it has one, until the command buffer + /// retires. + pub(crate) fn keep(&mut self, buffer: &Buffer) { + let (block, copy) = buffer.held(); let blocks = &mut self.gpu.blocks; if !blocks.iter().rev().any(|kept| Arc::ptr_eq(kept, block)) { blocks.push(Arc::clone(block)); } + if let Some(copy) = copy { + let copies = &mut self.gpu.copies; + if !copies.iter().rev().any(|kept| Arc::ptr_eq(kept, copy)) { + copies.push(Arc::clone(copy)); + } + } } /// Keeps `state` until the command buffer retires. @@ -813,6 +826,7 @@ pub(crate) fn retire( recorder, segments, blocks, + copies, pipelines, textures, samplers, @@ -822,7 +836,7 @@ pub(crate) fn retire( core.recorders.give_back(core, recorder); } ring.give_back(core); - drop((segments, blocks, pipelines, textures, samplers)); + drop((segments, blocks, copies, pipelines, textures, samplers)); times::reset( &core.device, inner.queue.stamps.pool, diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index ce49dcbd0..c7a2a5ba8 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -11,7 +11,9 @@ use crate::fill::Filler; use crate::floor; use crate::hazard::Ids; use crate::instance::{Instance, PhysicalDevice}; -use crate::memory::{self, Block, BlockId, BlockInfo, BlockMappings, MemoryClass, Pool, BLOCK_LEN}; +use crate::memory::{ + self, Block, BlockId, BlockInfo, BlockMappings, Memory, MemoryClass, Pool, BLOCK_LEN, +}; use crate::pipeline::PUSH_BYTES; use crate::places::Places; use crate::reaper::{self, Job, Reaper}; @@ -155,6 +157,8 @@ pub(crate) struct Core { pub(crate) pool: Pool, /// 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, @@ -433,6 +437,7 @@ impl Device { max_allocations, pool: Pool::new(options.block_mappings), places: Places::new(), + copies: Places::new(), filler, recorders: Recorders::new(family), work: Work::new(), @@ -550,12 +555,7 @@ impl Device { if core.closed() { return Err(Error::Quiesced); } - let memory = if len <= BLOCK_LEN { - core.pool.take(class)? - } else { - let len = memory::dedicated_len(len, core.max_block_len)?; - memory::make(core, class, len, core.pool.number()?, false)? - }; + 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)))); @@ -960,6 +960,26 @@ impl Core { } } + /// Whether the Shared memory type is device-local, by the device's memory-type query: then a + /// Managed buffer is its Shared range, with no device copy. + pub(crate) fn shared_is_device_local(&self) -> bool { + self.device_local & (1 << self.memory_types.shared) != 0 + } + + /// A block of `class` for `len` bytes: a pooled one up to [`BLOCK_LEN`], else a dedicated one + /// of `len` rounded up to 64 KiB, made in the call. + /// + /// Err: what [`Pool::take`] and [`memory::make`] return; + /// [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's longest block. + pub(crate) fn take_memory(&self, class: MemoryClass, len: u64) -> Result { + if len <= BLOCK_LEN { + self.pool.take(class) + } else { + let len = memory::dedicated_len(len, self.max_block_len)?; + memory::make(self, class, len, self.pool.number()?, false) + } + } + /// Quiesced or torn down. pub(crate) fn closed(&self) -> bool { self.closed.load(Ordering::Acquire) @@ -1028,7 +1048,12 @@ impl Drop for Core { // SAFETY: every upload that copied through it retired, and no call reads it. unsafe { region.free(self) }; } - for memory in (self.places.remaining().into_iter()).chain(self.pool.remaining()) { + let placed = (self.places.remaining().into_iter()).chain(self.copies.remaining()); + for memory in placed + .collect::>() + .into_iter() + .chain(self.pool.remaining()) + { memory::free(self, memory); } let pools = std::mem::take( diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 0f7d62a6f..90230106b 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -257,7 +257,7 @@ impl ComputeCommandEncoder { if !buffer.is_of(building.device.core()) { return Err(Error::Refused(Refusal::OtherDevice)); } - building.keep(buffer.held_block()); + building.keep(buffer); Slot::Buffer { buffer: buffer.clone(), offset, @@ -384,7 +384,7 @@ impl ComputeCommandEncoder { if !buffer.is_of(building.device.core()) { return Err(Error::Refused(Refusal::OtherDevice)); } - building.keep(buffer.held_block()); + building.keep(buffer); (buffer.id(), buffer.is_shared()) } Resource::Texture(texture) => { @@ -513,7 +513,7 @@ impl ComputeCommandEncoder { length: buffer.length(), })); } - self.building().keep(buffer.held_block()); + self.building().keep(buffer); self.dispatch(Grid::Indirect(buffer, offset), threads_per_threadgroup) } @@ -990,8 +990,8 @@ impl Building { device.cmd_dispatch(command, groups[0], groups[1], groups[2]); } Launch::Indirect(buffer, offset) => { - let block = &buffer.held_block().memory; - device.cmd_dispatch_indirect(command, block.buffer, buffer.offset() + offset); + let (reached, at) = buffer.device_range(); + device.cmd_dispatch_indirect(command, reached, at + offset); } } } diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index c8ca955d9..1e613e313 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -90,6 +90,26 @@ pub enum Refusal { /// The block's length. block_len: u64, }, + /// A Managed buffer whose bytes are in 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). + ManagedBlockNotShared { + /// 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). + ModifiedRange { + /// The range's first byte in the buffer. + start: u64, + /// The range's length. + length: u64, + /// The buffer's length. + buffer_length: u64, + }, /// A call on a command buffer already committed: encoding, adding a handler, enqueueing or /// committing again. /// @@ -595,6 +615,20 @@ impl fmt::Display for Refusal { f, "a buffer of {length} bytes at offset {offset} leaves its block of {block_len} bytes" ), + Refusal::ManagedBlockNotShared { block } => write!( + f, + "a Managed buffer's bytes are in block {}, which is Private", + block.get() + ), + Refusal::ModifiedRange { + start, + length, + buffer_length, + } => write!( + f, + "a changed range of {length} bytes from {start} leaves its buffer of \ + {buffer_length} bytes" + ), Refusal::Committed => f.write_str("the command buffer is already committed"), Refusal::OtherDevice => f.write_str("the object is another device's"), Refusal::NoCommandBuffers => { diff --git a/crates/metal2vulkan-rt/src/memory.rs b/crates/metal2vulkan-rt/src/memory.rs index 08e4e0cf9..cfe0c61f8 100644 --- a/crates/metal2vulkan-rt/src/memory.rs +++ b/crates/metal2vulkan-rt/src/memory.rs @@ -125,6 +125,11 @@ impl Memory { self.memory } + /// Whether the pool made it, to keep once it is given back; a dedicated block is freed then. + pub(crate) fn pooled(&self) -> bool { + self.pooled + } + pub(crate) fn info(&self) -> BlockInfo { BlockInfo { id: self.id, diff --git a/crates/metal2vulkan-rt/src/places.rs b/crates/metal2vulkan-rt/src/places.rs index 71d9a55fa..2c146735d 100644 --- a/crates/metal2vulkan-rt/src/places.rs +++ b/crates/metal2vulkan-rt/src/places.rs @@ -1,36 +1,38 @@ -//! Texture blocks: the pooled Private blocks the runtime places textures in. +//! 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. //! -//! A texture's image is bound at a place in a texture block, a Private block of the pool taken as -//! a block the consumer takes is, so a texture makes no allocation of its own. A place is the -//! image'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. A place is free again -//! once the reaper has freed the texture's image, after every command buffer and upload that used -//! it retired. One empty block is kept for the next texture; another that empties goes back to the -//! pool, which zeroes it and keeps or frees it. +//! 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, or, +//! for a place longer than a pooled block, a dedicated block of its own. A place is free again once +//! its resource is freed, after every command buffer and upload that used it retired. One empty +//! pooled block of a set is kept for the next place; another that empties, and a dedicated block +//! once empty, goes back to the pool, which zeroes and keeps a pooled block or frees it. //! -//! Every image in a block is optimal. The block's own `VkBuffer`, which spans it, aliases them -//! (Vulkan's memory aliasing), and only the pool uses it: to zero the block before it is taken and -//! after it is given back, when no image is in it. +//! An image in a texture block is optimal. The block's own `VkBuffer`, which spans it, aliases the +//! images (Vulkan's memory aliasing), and only the pool uses it: to zero the block before it is +//! taken and after it is given back, when no image is in it. A copy block's `VkBuffer` is what the +//! device copies are reached through. -use crate::device::lock; +use crate::device::{lock, Core}; use crate::error::Error; -use crate::memory::{BlockId, Memory, MemoryClass, Pool}; -use ash::vk; +use crate::memory::{BlockId, Memory, MemoryClass}; use std::sync::{Mutex, PoisonError}; -/// The texture blocks. +/// One set of blocks. pub(crate) struct Places { - blocks: Mutex>, + blocks: Mutex>, } -struct TextureBlock { +struct PlaceBlock { memory: Memory, free: Ranges, /// The places taken in it. live: usize, } -/// A texture's place: `len` bytes at `offset` in a texture block. +/// A resource's place: `len` bytes at `offset` in a block of a set. #[derive(Clone, Copy, Debug)] pub(crate) struct Place { block: BlockId, @@ -45,17 +47,17 @@ impl Places { } } - /// A place of `len` bytes, at most a block's, at a multiple of `align`, a power of two; and - /// the memory of its block. Where no block has room, a Private block is taken from the pool, - /// without the lock. + /// A place of `len` bytes at a multiple of `align`, a power of two, and its block. Where no + /// block has room, a Private block is taken, without the lock: from the pool, or a dedicated + /// one for a place longer than a pooled block. /// - /// Err: what [`Pool::take`] returns. + /// Err: what [`Core::take_memory`] returns. pub(crate) fn place( &self, - pool: &Pool, + core: &Core, len: u64, align: u64, - ) -> Result<(Place, vk::DeviceMemory), Error> { + ) -> Result<(Place, Memory), Error> { let mut blocks = lock(&self.blocks); loop { for block in blocks.iter_mut() { @@ -66,14 +68,13 @@ impl Places { offset, len, }; - return Ok((place, block.memory.device_memory())); + return Ok((place, block.memory)); } } drop(blocks); - let memory = pool.take(MemoryClass::Private)?; - debug_assert!(len <= memory.len); + let memory = core.take_memory(MemoryClass::Private, len)?; blocks = lock(&self.blocks); - blocks.push(TextureBlock { + blocks.push(PlaceBlock { memory, free: Ranges::new(memory.len), live: 0, @@ -81,9 +82,9 @@ impl Places { } } - /// Frees `place`. Where its block empties while another is empty, the block goes back to - /// `pool`. - pub(crate) fn release(&self, pool: &Pool, place: Place) { + /// Frees `place`. Where its block empties and is dedicated, or another pooled block of the + /// set is empty, the block goes back to the pool. + pub(crate) fn release(&self, core: &Core, place: Place) { let mut blocks = lock(&self.blocks); let Some(index) = (blocks.iter()).position(|block| block.memory.id == place.block) else { return; @@ -91,20 +92,23 @@ impl Places { let block = &mut blocks[index]; block.free.give(place.offset, place.len); block.live -= 1; - if block.live == 0 && blocks.iter().filter(|block| block.live == 0).count() > 1 { + let empty = |block: &PlaceBlock| block.live == 0 && block.memory.pooled(); + let surplus = + !block.memory.pooled() || blocks.iter().filter(|block| empty(block)).count() > 1; + if blocks[index].live == 0 && surplus { let emptied = blocks.remove(index); drop(blocks); - pool.give_back(emptied.memory); + core.pool.give_back(emptied.memory); } } - /// For the device tests: the texture blocks taken. + /// For the device tests: the blocks of the set. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn blocks(&self) -> usize { lock(&self.blocks).len() } - /// At teardown, once every texture is freed: the blocks, for the core to free. + /// At teardown, once every resource placed is freed: the blocks, for the core to free. pub(crate) fn remaining(&mut self) -> Vec { let blocks = self .blocks diff --git a/crates/metal2vulkan-rt/src/reaper.rs b/crates/metal2vulkan-rt/src/reaper.rs index e31d3bd7f..15d2e7448 100644 --- a/crates/metal2vulkan-rt/src/reaper.rs +++ b/crates/metal2vulkan-rt/src/reaper.rs @@ -182,7 +182,7 @@ fn free(core: &Core, object: Free) { unsafe { device.free_memory(memory, None) }; core.counters.fall(Gauge::Blocks); } - Backing::Placed(place) => core.places.release(&core.pool, place), + Backing::Placed(place) => core.places.release(core, place), } core.counters.fall(Gauge::Textures); } diff --git a/crates/metal2vulkan-rt/src/submit.rs b/crates/metal2vulkan-rt/src/submit.rs index 7c3649610..eb73d03a3 100644 --- a/crates/metal2vulkan-rt/src/submit.rs +++ b/crates/metal2vulkan-rt/src/submit.rs @@ -18,6 +18,7 @@ //! device's staging region ([`crate::staging`]), which the work lock guards with the upload; the //! upload goes without a wait once its copies' spans take half the region. +use crate::buffer::DeviceCopy; use crate::command::{CbInner, CommandBufferError, Handler, Pending, Segment}; use crate::complete; use crate::counters::Metric; @@ -32,7 +33,7 @@ use crate::staging::{At, Oldest, Region, Stage, Staging, REGION_LEN}; use crate::texture::Image; use crate::times; use ash::vk; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak}; @@ -135,6 +136,21 @@ pub(crate) struct Upload { /// The staging region's spans its copies use, and their bytes. spans: Vec, span_bytes: u64, + /// The Managed buffers whose consumer's bytes changed, in the order of their first change, + /// and each one's place in it by its device copy's address. + modified: Vec, + modified_at: HashMap, +} + +/// A Managed buffer's ranges the consumer changed since the last submission, which the upload +/// copies from the consumer's bytes into the device copy as it is submitted. +struct Modified { + copy: Arc, + /// The block of the consumer's bytes, and the buffer's offset in it. + cpu: Arc, + offset: u64, + /// `start..end` in the buffer, by start, no two overlapping or touching. + ranges: Vec<(u64, u64)>, } /// What an upload keeps until it retires. @@ -144,6 +160,8 @@ pub(crate) enum Held { Texture(Arc), /// The staging buffer of such a copy. Staging(Arc), + /// A Managed buffer's device copy the upload copies into. + Copy(Arc), } impl Held { @@ -153,6 +171,7 @@ impl Held { (Held::Block(a), Held::Block(b)) => Arc::ptr_eq(a, b), (Held::Texture(a), Held::Texture(b)) => Arc::ptr_eq(a, b), (Held::Staging(a), Held::Staging(b)) => Arc::ptr_eq(a, b), + (Held::Copy(a), Held::Copy(b)) => Arc::ptr_eq(a, b), _ => false, } } @@ -174,6 +193,8 @@ impl Upload { staging: 0, spans: Vec::new(), span_bytes: 0, + modified: Vec::new(), + modified_at: HashMap::new(), }), Err(error) => { core.recorders.give_back(core, recorder); @@ -357,6 +378,71 @@ impl Work { recorded } + /// The work lock, once the pending upload has room for a call of `staging` bytes of staging of + /// its own: where it is full ([`UPLOAD_ENTRIES`], [`UPLOAD_BYTES`]), it is submitted and the + /// call waits for it to complete, without the lock. + /// + /// Err: [`Error::Quiesced`]; [`Error::Vulkan`] with `VK_ERROR_DEVICE_LOST` where the device is + /// lost while the call waits. + fn room(&self, core: &Core, staging: u64) -> Result, Error> { + let mut state = self.lock(); + loop { + if state.closed { + return Err(Error::Quiesced); + } + let released = self.released.load(Ordering::Relaxed); + if !(state.upload.as_ref()).is_some_and(|upload| upload.full(staging, released)) { + return Ok(state); + } + let value = state.flush(); + drop(state); + self.wake(); + core.counters.count(Metric::UploadWaits); + core.done.wait(core, value)?; + state = self.lock(); + } + } + + /// `didModifyRange:` of a Managed buffer with a device copy: the consumer's bytes + /// `start..end` of the buffer, at `offset` in `cpu`, changed. The next submission's upload + /// copies them into `copy`, after everything recorded into it before, in one copy command per + /// buffer, whose ranges are merged where they overlap or touch; the copy reads the bytes when + /// the GPU reaches it. Each call is one of the upload's calls, bounded as + /// [`upload`](Self::upload)'s are. + /// + /// Err: as [`upload`](Self::upload). + pub(crate) fn modify( + &self, + core: &Core, + copy: &Arc, + cpu: &Arc, + offset: u64, + start: u64, + end: u64, + ) -> Result<(), Error> { + let mut state = self.room(core, 0)?; + let upload = match state.upload.take() { + Some(upload) => upload, + None => Upload::begin(core)?, + }; + let upload = state.upload.insert(upload); + upload.entries += 1; + let key = Arc::as_ptr(copy) as usize; + match upload.modified_at.get(&key) { + Some(&index) => merge(&mut upload.modified[index].ranges, start, end), + None => { + upload.modified_at.insert(key, upload.modified.len()); + upload.modified.push(Modified { + copy: Arc::clone(copy), + cpu: Arc::clone(cpu), + offset, + ranges: vec![(start, end)], + }); + } + } + Ok(()) + } + /// [`upload`](Self::upload) up to the span's give-up on a failure. fn record_upload( &self, @@ -369,22 +455,7 @@ impl Work { Some(Stage::Own(staging)) => staging.len, _ => 0, }; - let mut state = self.lock(); - loop { - if state.closed { - return Err(Error::Quiesced); - } - let released = self.released.load(Ordering::Relaxed); - if !(state.upload.as_ref()).is_some_and(|upload| upload.full(staging, released)) { - break; - } - let value = state.flush(); - drop(state); - self.wake(); - core.counters.count(Metric::UploadWaits); - core.done.wait(core, value)?; - state = self.lock(); - } + let mut state = self.room(core, staging)?; let device = &core.device; let upload = match state.upload.take() { Some(upload) => upload, @@ -1170,7 +1241,7 @@ fn submit(core: &Core, value: u64, upload: Option, batch: Batch) { } = batch; let device = &core.device; // An upload begun for textures gone before their move records nothing. - let upload = match upload { + let mut upload = match upload { Some(upload) if upload.entries == 0 => { upload.retire(core); None @@ -1179,7 +1250,8 @@ fn submit(core: &Core, value: u64, upload: Option, batch: Batch) { }; // What the upload wrote is visible to every command after it, and to the host once the // submission completes. - let mut ok = upload.as_ref().is_none_or(|upload| { + let mut ok = upload.as_mut().is_none_or(|upload| { + upload.copy_modified(core); record::barrier(device, upload.command, Reach::Host); core.counters.count(Metric::Barriers); // SAFETY: the upload's command buffer was recording under the work lock, which `close` @@ -1236,9 +1308,60 @@ fn submit(core: &Core, value: u64, upload: Option, batch: Batch) { } impl Upload { + /// Records the copies of the Managed buffers' changed ranges, last, after a barrier that puts + /// everything recorded before them (a device copy's zero fill among it) first; the upload + /// holds both blocks of each until it retires. The upload is out of the work lock, on its way + /// to its submission. + fn copy_modified(&mut self, core: &Core) { + if self.modified.is_empty() { + return; + } + let device = &core.device; + record::barrier(device, self.command, Reach::Commands); + core.counters.count(Metric::Barriers); + for modified in self.modified.drain(..) { + let regions: Vec = (modified.ranges.iter()) + .map(|&(start, end)| vk::BufferCopy { + src_offset: modified.offset + start, + dst_offset: modified.copy.offset() + start, + size: end - start, + }) + .collect(); + // SAFETY: the upload's command buffer is recording, and only this thread has it; both + // blocks' buffers have every usage, each range lies in the buffer, and the upload holds + // both blocks until it retires. + unsafe { + device.cmd_copy_buffer( + self.command, + modified.cpu.memory.buffer, + modified.copy.buffer(), + ®ions, + ) + }; + self.held.push(Held::Block(modified.cpu)); + self.held.push(Held::Copy(modified.copy)); + } + self.modified_at.clear(); + } + /// Recycles the upload's recorder and gives up what it holds: once its submission completed, /// or where it never went. pub(crate) fn retire(self, core: &Core) { core.recorders.give_back(core, self.recorder); } } + +/// Adds `start..end` to `ranges` (by start, no two overlapping or touching), joining the ranges it +/// overlaps or touches. +pub(crate) fn merge(ranges: &mut Vec<(u64, u64)>, start: u64, end: u64) { + // The first range that ends at or after `start`, and the first that starts after `end`. + let first = ranges.partition_point(|&(_, stop)| stop < start); + let last = ranges.partition_point(|&(begin, _)| begin <= end); + if first == last { + ranges.insert(first, (start, end)); + return; + } + let joined = (start.min(ranges[first].0), end.max(ranges[last - 1].1)); + ranges.drain(first + 1..last); + ranges[first] = joined; +} diff --git a/crates/metal2vulkan-rt/src/tests/command.rs b/crates/metal2vulkan-rt/src/tests/command.rs index 3ad8b360a..7fb28eb2b 100644 --- a/crates/metal2vulkan-rt/src/tests/command.rs +++ b/crates/metal2vulkan-rt/src/tests/command.rs @@ -90,8 +90,8 @@ pub(crate) mod on_device { /// Records a fill of `buffer` with `word`, keeping its block. fn fill(command_buffer: &CommandBuffer, buffer: &Buffer, word: u32) { - let target = buffer.held_block().memory.buffer; - let (offset, size) = (buffer.offset(), buffer.length()); + let (target, offset) = buffer.device_range(); + let size = buffer.length(); command_buffer .record_for_test(&[buffer], |device, command| { // SAFETY: the command buffer is recording; the range is the buffer's, in whole @@ -681,8 +681,8 @@ pub(crate) mod on_device { /// Commits a command buffer of `fills` fills of `buffer`: work that runs for a while. fn busy(queue: &CommandQueue, buffer: &Buffer, fills: u32) -> CommandBuffer { let command_buffer = queue.command_buffer().expect("a command buffer"); - let target = buffer.held_block().memory.buffer; - let (offset, size) = (buffer.offset(), buffer.length()); + let (target, offset) = buffer.device_range(); + let size = buffer.length(); command_buffer .record_for_test(&[buffer], |device, command| { for word in 0..fills { @@ -761,7 +761,7 @@ pub(crate) mod on_device { let member = |label: &str, log: &Log, buffer: &Buffer, word: u32| { let command_buffer = queue.command_buffer().expect("a command buffer"); fill(&command_buffer, buffer, word); - let target = work.held_block().memory.buffer; + let (target, _) = work.device_range(); command_buffer .record_for_test(&[&work], |device, command| { // SAFETY: as `busy`'s. diff --git a/crates/metal2vulkan-rt/src/tests/managed.rs b/crates/metal2vulkan-rt/src/tests/managed.rs new file mode 100644 index 000000000..787d46053 --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/managed.rs @@ -0,0 +1,173 @@ +//! Managed buffers: changed ranges merge where they overlap or touch; and, under a device cfg, on +//! every device of the cfg's kind, in the form the device's memory-type query picks: with a device +//! copy where Shared memory is not device-local, the copy holds the consumer's first bytes and +//! zeros after them, a changed range reaches it at the next submission and a range not marked +//! changed does not, and changes past the upload's calls submit it; without one, shaders read the +//! consumer's bytes as they are and a changed range submits nothing. A range past the buffer and a +//! Managed buffer over a Private block are refused, and every gauge reads zero after teardown. + +use crate::submit::merge; + +#[test] +fn changed_ranges_merge_where_they_overlap_or_touch() { + let mut ranges = Vec::new(); + merge(&mut ranges, 100, 200); + merge(&mut ranges, 300, 400); + assert_eq!(ranges, [(100, 200), (300, 400)]); + merge(&mut ranges, 0, 50); + assert_eq!(ranges, [(0, 50), (100, 200), (300, 400)], "before, apart"); + merge(&mut ranges, 200, 250); + assert_eq!( + ranges, + [(0, 50), (100, 250), (300, 400)], + "touching the end" + ); + merge(&mut ranges, 290, 300); + assert_eq!( + ranges, + [(0, 50), (100, 250), (290, 400)], + "touching the start" + ); + merge(&mut ranges, 120, 130); + assert_eq!(ranges, [(0, 50), (100, 250), (290, 400)], "inside one"); + merge(&mut ranges, 40, 295); + assert_eq!(ranges, [(0, 400)], "across three"); + merge(&mut ranges, 500, 600); + merge(&mut ranges, 0, 1000); + assert_eq!(ranges, [(0, 1000)], "over all"); +} + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::submit::UPLOAD_ENTRIES; + use crate::tests::command::on_device::{each_device, finished}; + use crate::{Buffer, Device, Error, MemoryClass, Refusal}; + use ash::vk; + + const LEN: u64 = 64 << 10; + + /// The bytes shaders reach at `managed`'s address, copied by the GPU into `into`, a Shared + /// buffer as long. + fn device_bytes(device: &Device, managed: &Buffer, into: &Buffer) -> Vec { + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let (source, from) = managed.device_range(); + let (target, to) = into.device_range(); + command_buffer + .record_for_test(&[managed, into], |device, command| { + let region = vk::BufferCopy { + src_offset: from, + dst_offset: to, + size: LEN, + }; + // SAFETY: the command buffer is recording; both ranges are the buffers', 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); + let contents = into.contents().expect("a Shared buffer"); + // SAFETY: the copy into the buffer completed, and its writes reach the host. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), LEN as usize) }.to_vec() + } + + /// Writes `bytes` at `at` in the consumer's bytes of `managed`. + fn write(managed: &Buffer, at: u64, bytes: &[u8]) { + let contents = managed.contents().expect("the consumer's bytes"); + // SAFETY: `at..at + bytes.len()` lies in the buffer, and nothing reads it meanwhile. + unsafe { + bytes + .as_ptr() + .copy_to_nonoverlapping(contents.as_ptr().add(at as usize), bytes.len()) + }; + } + + #[test] + fn every_device_copies_a_managed_buffer_s_changed_ranges() { + each_device("managed", |name, _, device| { + let core = device.core(); + let copied = !core.shared_is_device_local(); + let counters = device.counters(); + let cpu = (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let into = (device.new_buffer(cpu.id, LEN, LEN, true)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let first: Vec = (0..LEN).map(|i| (i % 251) as u8).collect(); + let start = (device.new_buffer(cpu.id, 0, LEN, false)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + write(&start, 0, &first); + drop(start); + + // The first half copied, the rest zero. + let managed = (device.new_managed_buffer(cpu.id, 0, LEN, LEN / 2)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let mut expected = first.clone(); + if copied { + expected[LEN as usize / 2..].fill(0); + } + assert!( + device_bytes(&device, &managed, &into) == expected, + "{name}: the bytes at creation (device copy: {copied})" + ); + + // Changed ranges, two of them overlapping; and a change not marked. + for (at, len) in [(1000, 2000), (2000, 3000), (40_000, 1)] { + write(&managed, at, &vec![0xA5; len as usize]); + managed + .did_modify_range(at, len) + .unwrap_or_else(|error| panic!("{name}: {error}")); + expected[at as usize..(at + len) as usize].fill(0xA5); + } + write(&managed, 20_000, &[0x5A; 100]); + if !copied { + expected[20_000..20_100].fill(0x5A); + } + assert!( + device_bytes(&device, &managed, &into) == expected, + "{name}: the bytes after the changes (device copy: {copied})" + ); + + // Changes past the upload's calls submit it; without a copy nothing is submitted. + let before = counters.metrics().submissions; + for change in 0..UPLOAD_ENTRIES as u64 + 8 { + managed + .did_modify_range((change * 8) % LEN, 4) + .unwrap_or_else(|error| panic!("{name}: change {change}: {error}")); + } + let submitted = counters.metrics().submissions - before; + match copied { + true => assert!(submitted >= 1, "{name}: the changes went"), + false => assert_eq!(submitted, 0, "{name}: nothing to copy"), + } + + match managed.did_modify_range(LEN - 4, 8) { + Err(Error::Refused(Refusal::ModifiedRange { + start, + length: 8, + buffer_length: LEN, + })) if start == LEN - 4 => {} + other => panic!("{name}: a range past the buffer: {other:?}"), + } + 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) { + Err(Error::Refused(Refusal::ManagedBlockNotShared { block })) => { + assert_eq!(block, private.id, "{name}") + } + Err(error) => panic!("{name}: a Managed buffer over a Private block: {error}"), + Ok(_) => panic!("{name}: a Managed buffer over a Private block was made"), + } + println!( + "managed: {name}: device copy {copied}; metrics {:?}", + counters.metrics() + ); + drop((managed, into)); + for block in [cpu.id, private.id] { + device + .release_block(block) + .unwrap_or_else(|error| panic!("{name}: {error}")); + } + }); + } +} diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index 3b8025d2e..05e8aab7f 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -7,6 +7,7 @@ mod floor; mod hazard; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod kernels; +mod managed; mod memory; mod narrow; mod null_descriptor; diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index 11a5e1209..4db15e924 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -738,9 +738,9 @@ impl Made { && requirements.size <= BLOCK_LEN && bits & (1 << core.memory_type(MemoryClass::Private)) != 0; let (backing, memory, offset) = if placed { - let (place, memory) = - (core.places).place(&core.pool, requirements.size, requirements.alignment)?; - (Backing::Placed(place), memory, place.offset) + let (place, block) = + (core.places).place(core, requirements.size, requirements.alignment)?; + (Backing::Placed(place), block.device_memory(), place.offset) } else { // Vulkan gives every image of no external handle type a device-local type. let local = bits & core.device_local; @@ -811,7 +811,7 @@ impl Made { device.free_memory(memory, None); core.counters.fall(Gauge::Blocks); } - Some(Backing::Placed(place)) => core.places.release(&core.pool, place), + Some(Backing::Placed(place)) => core.places.release(core, place), None => {} } } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 46c66c7c9..b627cd198 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9223,6 +9223,7 @@ method metal2vulkan-air::tensor_ops::RunForm::operand_args pub fn operand_args(& method metal2vulkan-rt::BlockId::get pub fn get(self) -> u32 method metal2vulkan-rt::Buffer::block pub fn block(&self) -> BlockId method metal2vulkan-rt::Buffer::contents pub fn contents(&self) -> Option> +method metal2vulkan-rt::Buffer::did_modify_range pub fn did_modify_range(&self, start: u64, length: u64) -> Result<(), Error> method metal2vulkan-rt::Buffer::gpu_address pub fn gpu_address(&self) -> u64 method metal2vulkan-rt::Buffer::length pub fn length(&self) -> u64 method metal2vulkan-rt::Buffer::offset pub fn offset(&self) -> u64 @@ -9277,6 +9278,7 @@ method metal2vulkan-rt::Device::new pub fn new(physical: &PhysicalDevice, option method metal2vulkan-rt::Device::new_buffer pub fn new_buffer(&self, block: BlockId, offset: u64, length: u64, zeroed: bool) -> Result method metal2vulkan-rt::Device::new_command_queue pub fn new_command_queue(&self, max_command_buffer_count: u32) -> Result method metal2vulkan-rt::Device::new_event pub fn new_event(&self) -> 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_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 method metal2vulkan-rt::Device::new_texture pub fn new_texture(&self, descriptor: &TextureDescriptor, index: Option) -> Result @@ -13387,7 +13389,9 @@ variant metal2vulkan-rt::Refusal::IndicesGranted IndicesGranted { class: IndexCl variant metal2vulkan-rt::Refusal::IndicesInUse IndicesInUse { class: IndexClass, index: u32 } 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::MisalignedBuffer MisalignedBuffer { index: u32, address: u64, align: u64 } +variant metal2vulkan-rt::Refusal::ModifiedRange ModifiedRange { start: u64, length: u64, buffer_length: u64 } variant metal2vulkan-rt::Refusal::NoBufferAtIndex NoBufferAtIndex { index: u32 } variant metal2vulkan-rt::Refusal::NoCommandBuffers NoCommandBuffers variant metal2vulkan-rt::Refusal::NoPipeline NoPipeline diff --git a/docs/API.md b/docs/API.md index d674c8786..d3b021439 100644 --- a/docs/API.md +++ b/docs/API.md @@ -6239,6 +6239,14 @@ each item named states the rule in full. (the call gives no plane height), and a face past the surface lies in the texture's tail, zero when made, announced (`metal2vulkan-degrade-surface-texels-tail`). One of another format, off 16 or of several levels stays `NotImplemented(SurfacePlaneShape)`. +- **The new runtime's Managed buffer copy reads the consumer's bytes when the GPU reaches it** + (`metal2vulkan-rt`'s `Buffer::did_modify_range`). On a device whose Shared memory is not + device-local, a changed range is one device copy from the consumer's bytes into the buffer's + device copy, at the head of the next submission, ahead of every command buffer committed after + the call on every queue. The copy reads the bytes as they are when the GPU runs it, so a write the + consumer makes after the call and before then may be seen. Metal leaves it undefined: an Apple + M3 and an Intel UHD 630 take the bytes when the GPU reads them, an AMD Radeon Pro 5300M at the + commit. **Function constants** diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index c164e567d..4eb54501f 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 | 7 | 7 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 31 | 31 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 33 | 33 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 10 | 10 | 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 | 7 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 10 | 8 | 0 | 0 | 13 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 10 | 8 | 0 | 0 | 15 | 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 | 10 | 0 | 0 | 0 | @@ -613,9 +613,11 @@ Columns: | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| -| `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 | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_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 | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_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 (new_buffer)` | `-` | +| `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)` | `-` | +| `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 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 and a pipeline belong to the `VkDevice` that made them | 8: `crates/metal2vulkan-rt/src/command.rs (check)`, `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` (+5) | `-` | | `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)` | `-` | @@ -1162,9 +1164,11 @@ Each refusal's sites, with the function that builds it. - `floor::QueueFamily`: `crates/metal2vulkan-rt/src/floor.rs (decide)` - `floor::MemoryType`: `crates/metal2vulkan-rt/src/floor.rs (choose)` - `floor::TimeDomain`: `crates/metal2vulkan-rt/src/floor.rs (decide)` -- `rt:Refusal::EmptyBuffer`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)` -- `rt:Refusal::BufferTooLong`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)` -- `rt:Refusal::BufferPastBlock`: `crates/metal2vulkan-rt/src/buffer.rs (new_buffer)` +- `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::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/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)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)`