diff --git a/crates/metal2vulkan-harness/src/authored.rs b/crates/metal2vulkan-harness/src/authored.rs index f3004603a..05a0afb15 100644 --- a/crates/metal2vulkan-harness/src/authored.rs +++ b/crates/metal2vulkan-harness/src/authored.rs @@ -166,6 +166,10 @@ pub const WORKLOADS: [Workload; 36] = [ name: "draw_2000", plan: draw_2000, }, + Workload { + name: "bind_2000", + plan: bind_2000, + }, ]; /// A creation workload: objects of one kind made and released in turn (`Session::create`). @@ -275,6 +279,27 @@ fn draw_2000() -> Plan { draws("draw_2000", 16, 2000) } +/// The binds a draw makes, timed: 2,000 draws in one pass, as [`draw_2000`]'s, each with its +/// vertex function's positions (buffer 0) and a fragment texture (texture 0) set before it, both +/// alternating between two objects, so every bind is of an object the slot does not hold. The +/// fragment function reads no texture, so the draws' work is `draw_2000`'s; what the row adds is +/// the binds. +fn bind_2000() -> Plan { + let mut plan = draws("bind_2000", 16, 2000); + plan.buffers.push(plan.buffers[0].clone()); + plan.textures.push(TexturePlan::rgba16_float(4, 4, None)); + plan.textures.push(TexturePlan::rgba16_float(4, 4, None)); + for (at, dispatch) in plan.dispatches.iter_mut().enumerate() { + let other = at % 2; + dispatch + .bindings + .retain(|binding| !matches!(binding, Binding::Buffer { index: 0, .. })); + dispatch.bindings.push(buffer(0, [0, 2][other])); + dispatch.bindings.push(texture(0, 1 + other)); + } + plan +} + /// `count` draws in one pass into a `side` by `side` `RGBA16Float` target, each of /// `colored_vertex` and `colored_fragment` of the render library over one triangle that covers /// the target, flat green: the target's every texel is green after the first run. The first diff --git a/crates/metal2vulkan-harness/src/lib.rs b/crates/metal2vulkan-harness/src/lib.rs index 064bfa2b6..982c4570e 100644 --- a/crates/metal2vulkan-harness/src/lib.rs +++ b/crates/metal2vulkan-harness/src/lib.rs @@ -18,7 +18,9 @@ //! again before each run (`plan::BufferPlan::modified`), and `constant_private` the same reads //! from a `Private` table, its reference. `draw_full` and `draw_2000` are draws of the render //! library's `colored_vertex` and `colored_fragment` (`plan::Grid::Draw`) in one pass: 64 that -//! each cover a 512 by 512 target, and 2,000 that each cover a 16 by 16 one. +//! each cover a 512 by 512 target, and 2,000 that each cover a 16 by 16 one; `bind_2000` is +//! `draw_2000` with a vertex buffer and a fragment texture set before each draw, each alternating +//! between two objects. //! A [`run::Session`] makes its objects, checks the first run, then times the rest. The authored //! workloads ([`authored`]) are MSL kernels committed as public fixtures //! (`crates/metal2vulkan-validation/fixtures/public/harness/workloads.metal`, compiled by @@ -452,6 +454,9 @@ pub trait RenderCommandEncoder { /// `setVertexBuffer:offset:atIndex:`. fn set_vertex_buffer(&mut self, buffer: &D::Buffer, offset: u64, index: u32) -> Result<()>; + /// `setFragmentTexture:atIndex:`. + fn set_fragment_texture(&mut self, texture: &D::Texture, index: u32) -> Result<()>; + /// `drawPrimitives:vertexStart:vertexCount:` of triangles. fn draw_triangles(&mut self, vertex_start: u32, vertex_count: u32) -> Result<()>; diff --git a/crates/metal2vulkan-harness/src/old.rs b/crates/metal2vulkan-harness/src/old.rs index 8f92c16c5..87b4a5aba 100644 --- a/crates/metal2vulkan-harness/src/old.rs +++ b/crates/metal2vulkan-harness/src/old.rs @@ -461,6 +461,14 @@ impl crate::RenderCommandEncoder for runtime::RenderCommandEnco )?) } + fn set_fragment_texture(&mut self, texture: &Texture, index: u32) -> Result<()> { + Ok(runtime::RenderCommandEncoder::set_fragment_texture( + self, + Some(&texture.texture), + index, + )?) + } + fn draw_triangles(&mut self, vertex_start: u32, vertex_count: u32) -> Result<()> { let triangle = metal2vulkan::metal::PrimitiveType::Triangle; Ok(runtime::RenderCommandEncoder::draw_primitives( diff --git a/crates/metal2vulkan-harness/src/plan.rs b/crates/metal2vulkan-harness/src/plan.rs index cc5373876..4976c62b1 100644 --- a/crates/metal2vulkan-harness/src/plan.rs +++ b/crates/metal2vulkan-harness/src/plan.rs @@ -682,7 +682,8 @@ pub enum Grid { /// starts: consecutive draws into one target share one pass. The step's function is the /// vertex function, its render pipeline state `fragment`'s too, drawing into `target`'s /// format with Metal's defaults otherwise; its bindings are the vertex function's buffers - /// (`setVertexBuffer:offset:atIndex:`), and a draw binds nothing else. + /// (`setVertexBuffer:offset:atIndex:`) and the fragment function's textures + /// (`setFragmentTexture:atIndex:`), and a draw binds nothing else. Draw { /// The fragment function's name in the plan's library. fragment: &'static str, @@ -885,12 +886,13 @@ impl Plan { ) .into()); } - let buffers_only = (dispatch.bindings.iter()) - .all(|binding| matches!(binding, Binding::Buffer { .. })); - if !dispatch.blits.is_empty() || !buffers_only { + let drawn = (dispatch.bindings.iter()).all(|binding| { + matches!(binding, Binding::Buffer { .. } | Binding::Texture { .. }) + }); + if !dispatch.blits.is_empty() || !drawn { return Err(format!( - "{name}: dispatch {i} is a draw, which binds vertex buffers alone and \ - takes no blit" + "{name}: dispatch {i} is a draw, which binds vertex buffers and fragment \ + textures alone and takes no blit" ) .into()); } diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index 2381f8521..5f516b8f1 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -783,6 +783,10 @@ impl crate::RenderCommandEncoder for rt::RenderCommandEncoder { .map_err(error) } + fn set_fragment_texture(&mut self, texture: &rt::Texture, index: u32) -> Result<()> { + rt::RenderCommandEncoder::set_fragment_texture(self, Some(texture), index).map_err(error) + } + fn draw_triangles(&mut self, vertex_start: u32, vertex_count: u32) -> Result<()> { let triangle = rt::PrimitiveType::Triangle; rt::RenderCommandEncoder::draw_primitives(self, triangle, vertex_start, vertex_count, 1, 0) diff --git a/crates/metal2vulkan-harness/src/run.rs b/crates/metal2vulkan-harness/src/run.rs index 1edffda21..a188fb3ea 100644 --- a/crates/metal2vulkan-harness/src/run.rs +++ b/crates/metal2vulkan-harness/src/run.rs @@ -728,13 +728,16 @@ impl Harness { *bound = Some(state); } for binding in &dispatch.bindings { - if let Binding::Buffer { - index, - buffer, - offset, - } = binding - { - encoder.set_vertex_buffer(&made.buffers[*buffer], *offset, *index)?; + match binding { + Binding::Buffer { + index, + buffer, + offset, + } => encoder.set_vertex_buffer(&made.buffers[*buffer], *offset, *index)?, + Binding::Texture { index, texture } => { + encoder.set_fragment_texture(&made.textures[*texture], *index)? + } + _ => {} } } encoder.draw_triangles(0, vertex_count)?; diff --git a/crates/metal2vulkan-harness/src/tests.rs b/crates/metal2vulkan-harness/src/tests.rs index a3498f944..f980b20c7 100644 --- a/crates/metal2vulkan-harness/src/tests.rs +++ b/crates/metal2vulkan-harness/src/tests.rs @@ -291,9 +291,9 @@ fn parts_cut_a_range_in_order_the_last_one_shorter() { } /// A draw's target is a texture of the plan made with `RenderTarget` usage, and a draw binds -/// vertex buffers alone. +/// vertex buffers and fragment textures alone. #[test] -fn a_draw_needs_a_render_target_and_binds_buffers_alone() { +fn a_draw_needs_a_render_target_and_binds_buffers_and_textures_alone() { let plan = || { (WORKLOADS .iter() diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index ed4b9aa57..af387df08 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -239,8 +239,8 @@ in its memory. 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. Placement is the consumer's, and so +the buffer there before has completed. A command buffer keeps each buffer it uses, and so its +block, until it retires, 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 @@ -832,9 +832,13 @@ that touch blocks first. blocks of the floor's ring memory type (device-local, host-visible, coherent), split into 64 KiB chunks that a command buffer takes as it records and gives back when it retires; a block is made when no chunk is free and kept for the device's life. -- The command buffer keeps each pipeline state it dispatches with, and each texture and sampler - state an encoder binds or declares, until it retires, so their elements of set 1 stay theirs - while work may read them. +- The command buffer keeps each pipeline state, buffer, texture and sampler state an encoder + sets, binds, declares or copies, once, until it retires, as Metal's command buffer retains each + object once, so their memory and their elements of set 1 stay theirs while work may read them. + The first use of an object in a command buffer takes its one reference; a later bind of it, and + every binding slot that holds it, borrows that one and changes no count. The completion thread + releases them as the command buffer retires, and the lists keep their capacity for the queue's + next command buffer. ## Blit encoders diff --git a/crates/metal2vulkan-rt/src/buffer.rs b/crates/metal2vulkan-rt/src/buffer.rs index 820a9df67..8714cf1ca 100644 --- a/crates/metal2vulkan-rt/src/buffer.rs +++ b/crates/metal2vulkan-rt/src/buffer.rs @@ -367,6 +367,13 @@ impl Device { } } +// SAFETY: the handle is its one `Arc` and nothing else, and its address is that `Arc`'s pointer. +unsafe impl crate::kept::Handle for Buffer { + fn address(&self) -> usize { + Arc::as_ptr(&self.inner) as *const () as usize + } +} + impl Buffer { /// `gpuAddress`: the block's device address plus the buffer's offset; of a Managed buffer with /// a device copy, the copy block's device address plus the copy's offset. diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index 1b7f790e8..b289e31e4 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -1,13 +1,14 @@ //! 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::buffer::Buffer; use crate::capture::CopyIn; use crate::counters::{Metric, Tally}; use crate::device::{lock, Core, Device}; use crate::error::{Error, Refusal}; use crate::event::{Event, EventInner}; use crate::hazard::{Access, Hazards}; +use crate::kept::{Lent, Objects}; use crate::memory::Block; use crate::over::{self, Overs}; use crate::pipeline::ComputePipelineState; @@ -187,19 +188,14 @@ impl Pushed { pub(crate) struct Gpu { pub(crate) recorder: Option, pub(crate) segments: Vec, - /// Each block the commands use, once: a block released meanwhile is reused only after the - /// command buffer retires. + /// Each heap's block the commands use (`useHeap:`), 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, - pub(crate) render_pipelines: Vec, - /// The textures and sampler states the encoders bound or declared, once each, kept until the - /// command buffer retires: their elements of set 1 stay theirs while work may read them. - pub(crate) textures: Vec, - pub(crate) samplers: Vec, + /// The buffers, textures, sampler states and pipeline states the encoders bound, declared or + /// copied, once each, kept until the command buffer retires: a buffer's block and device copy + /// with it, and a texture's and a sampler's elements of set 1 stay theirs while work may read + /// them (`crate::kept`). + pub(crate) kept: Objects, /// What the commands wrote into the parameter ring. pub(crate) ring: Writes, /// A texture over a Managed buffer's device copy in an image of its own is kept: the submit @@ -280,8 +276,14 @@ impl Pending { } impl CommandBuffer { - /// A new command buffer of `queue`, which gave it `slot`, whose two queries are reset. - pub(crate) fn new(queue: Arc, device: Device, slot: u32) -> CommandBuffer { + /// A new command buffer of `queue`, which gave it `slot`, whose two queries are reset, keeping + /// its objects in `kept`, empty, the lists of a retired one where the queue had them. + pub(crate) fn new( + queue: Arc, + device: Device, + slot: u32, + kept: Objects, + ) -> CommandBuffer { let stamps = (queue.stamps.pool, Stamps::first(slot)); CommandBuffer { inner: Arc::new(CbInner { @@ -297,11 +299,7 @@ impl CommandBuffer { recorder: None, segments: vec![Segment::default()], blocks: Vec::new(), - copies: Vec::new(), - pipelines: Vec::new(), - render_pipelines: Vec::new(), - textures: Vec::new(), - samplers: Vec::new(), + kept, ring: Writes::default(), managed: false, images: Vec::new(), @@ -945,17 +943,22 @@ impl Building { self.gpu.ring.write(self.device.core(), bytes) } - /// Keeps `buffer`'s block, and its device copy where it has one, until the command buffer - /// retires. + /// Keeps `buffer`, with its 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(); - self.keep_block(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)); - } - } + self.gpu.kept.buffers.hold(buffer); + } + + /// Keeps `buffer` as [`keep`](Self::keep) does, and lends it for a binding slot: no count + /// changes but at the recording's first use of it. + /// + /// # Safety + /// + /// The borrow is used only until the command buffer commits: in an encoder's tables. + pub(crate) unsafe fn lend_buffer(&mut self, buffer: &Buffer) -> Lent { + // SAFETY: the caller uses the borrow only before the commit, and the lists are cleared + // only once the command buffer retired. + unsafe { self.gpu.kept.buffers.keep(buffer) } } /// Keeps `block` until the command buffer retires. @@ -966,32 +969,52 @@ impl Building { } } - /// Keeps `state` until the command buffer retires. - pub(crate) fn keep_pipeline(&mut self, state: &ComputePipelineState) { - let pipelines = &mut self.gpu.pipelines; - if !pipelines.iter().rev().any(|kept| kept.is(state)) { - pipelines.push(state.clone()); - } + /// Keeps `state` until the command buffer retires, and lends it to the encoder that set it. + /// + /// # Safety + /// + /// As [`lend_buffer`](Self::lend_buffer). + pub(crate) unsafe fn lend_pipeline( + &mut self, + state: &ComputePipelineState, + ) -> Lent { + // SAFETY: as `lend_buffer`. + unsafe { self.gpu.kept.pipelines.keep(state) } } - /// Keeps `state` until the command buffer retires. - pub(crate) fn keep_render_pipeline(&mut self, state: &RenderPipelineState) { - let pipelines = &mut self.gpu.render_pipelines; - if !pipelines.iter().rev().any(|kept| kept.is(state)) { - pipelines.push(state.clone()); - } + /// Keeps `state` until the command buffer retires, and lends it to the encoder that set it. + /// + /// # Safety + /// + /// As [`lend_buffer`](Self::lend_buffer). + pub(crate) unsafe fn lend_render_pipeline( + &mut self, + state: &RenderPipelineState, + ) -> Lent { + // SAFETY: as `lend_buffer`. + unsafe { self.gpu.kept.render_pipelines.keep(state) } } /// Keeps `texture` until the command buffer retires, as Metal's command buffer retains every /// object its encoders bind: each object once, a view apart from its parent. pub(crate) fn keep_texture(&mut self, texture: &Texture) { - let textures = &mut self.gpu.textures; - if !textures.iter().rev().any(|kept| kept.is(texture)) { + if self.gpu.kept.textures.hold(texture) { self.gpu.managed |= texture.managed_over().is_some(); - textures.push(texture.clone()); } } + /// Keeps `texture` as [`keep_texture`](Self::keep_texture) does, and lends it for a binding + /// slot. + /// + /// # Safety + /// + /// As [`lend_buffer`](Self::lend_buffer). + pub(crate) unsafe fn lend_texture(&mut self, texture: &Texture) -> Lent { + self.keep_texture(texture); + // SAFETY: as `lend_buffer`; the texture is kept now. + unsafe { self.gpu.kept.textures.keep(texture) } + } + /// Whether the commands track what they write for textures over a buffer in an image of /// their own (`crate::over`): while any lives. pub(crate) fn copies_over(&self) -> bool { @@ -1032,7 +1055,7 @@ impl Building { let last = segments.len() - 1; segments[last] .overs - .before(accesses, &self.gpu.textures, unbound) + .before(accesses, self.gpu.kept.textures.as_slice(), unbound) } /// Records `copies`, ordered as a blit's copy is; nothing where there are none. @@ -1118,12 +1141,14 @@ impl Building { self.last().overs.after(&[], true); } - /// Keeps `state` until the command buffer retires. - pub(crate) fn keep_sampler(&mut self, state: &SamplerState) { - let samplers = &mut self.gpu.samplers; - if !samplers.iter().rev().any(|kept| kept.is(state)) { - samplers.push(state.clone()); - } + /// Keeps `state` until the command buffer retires, and lends it for a binding slot. + /// + /// # Safety + /// + /// As [`lend_buffer`](Self::lend_buffer). + pub(crate) unsafe fn lend_sampler(&mut self, state: &SamplerState) -> Lent { + // SAFETY: as `lend_buffer`. + unsafe { self.gpu.kept.samplers.keep(state) } } } @@ -1201,11 +1226,7 @@ pub(crate) fn retire( recorder, segments, blocks, - copies, - pipelines, - render_pipelines, - textures, - samplers, + mut kept, ring, managed: _, images, @@ -1217,22 +1238,15 @@ pub(crate) fn retire( copy_in.retire(core); } ring.give_back(core); - drop(( - blocks, - copies, - pipelines, - render_pipelines, - textures, - samplers, - images, - )); + drop((blocks, images)); + kept.clear(); times::reset( &core.device, inner.queue.stamps.pool, Stamps::first(inner.slot), written, ); - inner.queue.release(inner.slot); + inner.queue.release(inner.slot, kept); let handle = CommandBuffer { inner }; for handler in handlers.scheduled.into_iter().chain(handlers.completed) { handler(&handle); @@ -1250,11 +1264,18 @@ impl Drop for CbInner { // retired. if let Some(Building { device, gpu, .. }) = state.building.take() { let core = device.core(); - if let Some(recorder) = gpu.recorder { + let Gpu { + recorder, + mut kept, + ring, + .. + } = gpu; + if let Some(recorder) = recorder { core.recorders.give_back(core, recorder); } - gpu.ring.give_back(core); - self.queue.release(self.slot); + ring.give_back(core); + kept.clear(); + self.queue.release(self.slot, kept); } } } diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index eb7300f9b..db519ebd4 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -8,10 +8,11 @@ use crate::error::{Error, Gap, Limit, Refusal}; use crate::fence::Fence; use crate::floor; use crate::hazard::Access; +use crate::kept::{Handle, Lent}; use crate::memory::BlockId; use crate::over; use crate::pipeline::{ - ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Variant, Which, PUSH_BYTES, + ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Which, PUSH_BYTES, PUSH_STAGES, SQUARE, }; use crate::record::Reach; @@ -94,7 +95,7 @@ enum Slot { #[default] Empty, Buffer { - buffer: Buffer, + buffer: Lent, offset: u64, }, /// The address of a `set_bytes` copy in the parameter ring. @@ -174,14 +175,18 @@ pub struct ComputeCommandEncoder { /// What the command buffer records, held while the encoder is open. building: Option, serial: bool, - pipeline: Option, + /// The state set, and the objects of the argument tables below, borrowed from what the + /// command buffer keeps (`crate::kept`). + pipeline: Option>, slots: Vec, /// The texture argument table. - textures: Vec>, + textures: Vec>>, /// The sampler argument table. - samplers: Vec>, + samplers: Vec>>, /// Threadgroup memory lengths by index, as set. threadgroup_lengths: Vec<(u32, u32)>, + /// The lengths of the last variant looked up, in its kernel's order, kept to reuse. + lengths: Vec, /// `use_resource` declarations, by resource id. declared: Vec<(u32, Access)>, /// A `use_resource` declaration writes a Shared buffer. @@ -399,6 +404,7 @@ impl CommandBuffer { textures: vec![None; TEXTURE_SLOTS as usize], samplers: vec![None; SAMPLER_SLOTS as usize], threadgroup_lengths: Vec::new(), + lengths: Vec::new(), declared: Vec::new(), declared_shared_write: false, last: None, @@ -433,15 +439,15 @@ impl ComputeCommandEncoder { if self.pipeline.as_ref().is_some_and(|set| set.is(state)) { return Ok(()); } - self.building().keep_pipeline(state); - self.pipeline = Some(state.clone()); + // SAFETY: the encoder holds the borrow, and it ends before its command buffer commits. + self.pipeline = Some(unsafe { self.building().lend_pipeline(state) }); self.last = None; self.changed(); Ok(()) } /// `setBuffer:offset:atIndex:` (`setBuffers:offsets:withRange:` is a loop of it). `None` - /// unbinds the slot. The command buffer keeps the buffer's block until it retires. + /// unbinds the slot. The command buffer keeps the buffer, and so its block, until it retires. /// /// Err: [`Refusal::BufferIndex`] for an index of 31 or more; [`Refusal::OtherDevice`] for /// another device's buffer. @@ -454,13 +460,23 @@ impl ComputeCommandEncoder { let slot = self.slot(index)?; let bound = match buffer { Some(buffer) => { + if let Slot::Buffer { + buffer: held, + offset: at, + } = &self.slots[slot] + { + if held.address() == buffer.address() && *at == offset { + return Ok(()); + } + } let building = self.building(); if !buffer.is_of(building.device.core()) { return Err(Error::Refused(Refusal::OtherDevice)); } - building.keep(buffer); Slot::Buffer { - buffer: buffer.clone(), + // SAFETY: the encoder's slot holds the borrow, and it ends before its command + // buffer commits. + buffer: unsafe { building.lend_buffer(buffer) }, offset, } } @@ -482,14 +498,23 @@ impl ComputeCommandEncoder { if index >= TEXTURE_SLOTS { return Err(Error::Refused(Refusal::TextureArgumentIndex { index })); } - if let Some(texture) = texture { - let building = self.building(); - if !texture.is_of(building.device.core()) { - return Err(Error::Refused(Refusal::OtherDevice)); - } - building.keep_texture(texture); + let held = &self.textures[index as usize]; + if held.as_deref().map(Handle::address) == texture.map(Handle::address) { + return Ok(()); } - self.textures[index as usize] = texture.cloned(); + let lent = match texture { + Some(texture) => { + let building = self.building(); + if !texture.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + // SAFETY: the encoder's slot holds the borrow, and it ends before its command + // buffer commits. + Some(unsafe { building.lend_texture(texture) }) + } + None => None, + }; + self.textures[index as usize] = lent; self.changed(); Ok(()) } @@ -508,14 +533,23 @@ impl ComputeCommandEncoder { if index >= SAMPLER_SLOTS { return Err(Error::Refused(Refusal::SamplerArgumentIndex { index })); } - if let Some(sampler) = sampler { - let building = self.building(); - if !sampler.is_of(building.device.core()) { - return Err(Error::Refused(Refusal::OtherDevice)); - } - building.keep_sampler(sampler); + let held = &self.samplers[index as usize]; + if held.as_deref().map(Handle::address) == sampler.map(Handle::address) { + return Ok(()); } - self.samplers[index as usize] = sampler.cloned(); + let lent = match sampler { + Some(sampler) => { + let building = self.building(); + if !sampler.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + // SAFETY: the encoder's slot holds the borrow, and it ends before its command + // buffer commits. + Some(unsafe { building.lend_sampler(sampler) }) + } + None => None, + }; + self.samplers[index as usize] = lent; Ok(()) } @@ -578,8 +612,8 @@ impl ComputeCommandEncoder { } /// `useResource:usage:` (`useResources:count:usage:` is a loop of it): the resource joins every - /// later dispatch's accesses. The command buffer keeps a buffer's block, or a texture, until - /// it retires. + /// later dispatch's accesses. The command buffer keeps the buffer or the texture until it + /// retires. /// /// Err: [`Refusal::OtherDevice`] for another device's resource. pub fn use_resource( @@ -624,8 +658,8 @@ impl ComputeCommandEncoder { /// `useHeap:` (`useHeaps:count:` is a loop of it), for the heap whose memory is block `heap`: /// a [`HeapRange`](crate::HeapRange)'s block, or the block a placement heap's buffers sit in. - /// The command buffer keeps the block until it retires, as it keeps a buffer's block for - /// [`use_resource`](Self::use_resource), so a heap the consumer gives back while the work + /// The command buffer keeps the block until it retires, as it keeps a buffer, and so its + /// block, for [`use_resource`](Self::use_resource), so a heap the consumer gives back while the work /// runs stays valid under it. Metal states no retention for `useHeap:`; keeping is the safe /// reading. It declares no access: a dispatch touches its bound slots and the `use_resource` /// declarations, and a kernel that reaches a heap's resources through addresses outside its @@ -892,27 +926,20 @@ impl ComputeCommandEncoder { let vk_pipeline = match self.last { Some(last) if last.module == module && last.local == local => last.pipeline, _ => { - let variant = Variant { - size: local, - threadgroup_lengths: kernel - .interface - .threadgroups - .iter() - .map(|&index| self.threadgroup_length(index)) - .collect(), - tiles: module == Module::Tiles, - }; - let length = kernel - .interface - .memory - .bytes(&variant.threadgroup_lengths, threads); + let lengths = &mut self.lengths; + lengths.clear(); + lengths.extend( + (kernel.interface.threadgroups.iter()) + .map(|&index| threadgroup_length(&self.threadgroup_lengths, index)), + ); + let length = kernel.interface.memory.bytes(lengths, threads); if length > u64::from(limits.max_shared_memory) { return Err(Error::Limit(Limit::ThreadgroupMemory { length, max: limits.max_shared_memory, })); } - kernel.pipeline(core, &variant)? + kernel.pipeline(core, (local, lengths, module == Module::Tiles))? } }; self.last = Some(Last { @@ -1073,14 +1100,13 @@ impl ComputeCommandEncoder { ) }) } +} - /// The length set for threadgroup memory index `index`, 0 where none was. - fn threadgroup_length(&self, index: u32) -> u32 { - self.threadgroup_lengths - .iter() - .find(|(set, _)| *set == index) - .map_or(0, |(_, length)| *length) - } +/// The length `set` gives threadgroup memory index `index`, 0 where it gives none. +fn threadgroup_length(set: &[(u32, u32)], index: u32) -> u32 { + (set.iter()) + .find(|(at, _)| *at == index) + .map_or(0, |(_, length)| *length) } /// The recording an open encoder holds. @@ -1111,8 +1137,8 @@ fn check_alignments(core: &Core, slots: &[Slot], interface: &Interface) -> Resul /// A compute encoder's argument tables: buffer slots, textures and samplers. type Bound<'a> = ( &'a [Slot], - &'a [Option], - &'a [Option], + &'a [Option>], + &'a [Option>], ); impl Parameters { @@ -1215,7 +1241,7 @@ fn merge(a: Access, b: Access) -> Access { /// What a dispatch touches besides its pipeline's own facts. pub(crate) struct Accesses<'a> { slots: &'a [Slot], - textures: &'a [Option], + textures: &'a [Option>], declared: &'a [(u32, Access)], indirect: Option, } diff --git a/crates/metal2vulkan-rt/src/kept.rs b/crates/metal2vulkan-rt/src/kept.rs new file mode 100644 index 000000000..815440394 --- /dev/null +++ b/crates/metal2vulkan-rt/src/kept.rs @@ -0,0 +1,162 @@ +//! What a command buffer keeps of the objects its encoders use: each buffer, texture, sampler +//! state and pipeline state once, as Metal's command buffer retains each object once, until the +//! command buffer retires. The first use of an object in a recording takes its one reference; +//! every later use, and every binding slot an encoder fills with it, borrows the kept one +//! ([`Lent`]) and changes no count. The lists and their address sets keep their capacity from +//! one recording of a queue to the next, so a recording past the first allocates for its objects +//! only where it uses more than any before it did. + +use crate::buffer::Buffer; +use crate::pipeline::ComputePipelineState; +use crate::render::RenderPipelineState; +use crate::sampler::SamplerState; +use crate::texture::Texture; +use std::collections::HashSet; +use std::hash::{BuildHasherDefault, Hasher}; +use std::mem::ManuallyDrop; +use std::ops::Deref; + +/// A handle to a shared object that is one `Arc` and nothing else: a copy of it made bit for bit +/// is the same object, and dropping no copy but one keeps the count right. +/// +/// # Safety +/// +/// The type holds exactly one `Arc` and no other state, and `address` is that `Arc`'s pointer. +pub(crate) unsafe trait Handle: Clone { + /// The object's address: the same for every handle to it, and no other object's while it + /// lives. + fn address(&self) -> usize; +} + +/// A handle borrowed from what a recording keeps: the same object, which this copy neither +/// retains nor releases. A command buffer keeps the object until it retires, and an encoder's +/// tables, which hold its borrows, end with the encoder, before its command buffer can commit. +pub(crate) struct Lent(ManuallyDrop); + +impl Lent { + /// A borrow of `object`. + /// + /// # Safety + /// + /// The recording the borrow is used in keeps `object` until after the borrow's last use. + unsafe fn of(object: &T) -> Lent { + // SAFETY: `T: Handle` is one `Arc`, so the copy is the same object; it is never dropped, + // so the count stays the kept handle's, and the caller keeps that one alive past the + // copy's last use. + Lent(ManuallyDrop::new(unsafe { std::ptr::read(object) })) + } +} + +impl Deref for Lent { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl Clone for Lent { + fn clone(&self) -> Lent { + // SAFETY: the same object as `self`, which the recording keeps as long. + unsafe { Lent::of(&self.0) } + } +} + +/// The objects of one kind a recording keeps, each once, in the order first used. +pub(crate) struct Kept { + list: Vec, + addresses: HashSet>, +} + +impl Default for Kept { + fn default() -> Kept { + Kept { + list: Vec::new(), + addresses: HashSet::default(), + } + } +} + +impl Kept { + /// Keeps `object` where it is not kept yet, taking its one reference, and lends it. + /// + /// # Safety + /// + /// The borrow is used only while this list keeps its objects: before it is cleared. + pub(crate) unsafe fn keep(&mut self, object: &T) -> Lent { + if self.addresses.insert(object.address()) { + self.list.push(object.clone()); + } + // SAFETY: the list keeps `object` now, until it is cleared, past which the caller uses no + // borrow. + unsafe { Lent::of(object) } + } + + /// Keeps `object` where it is not kept yet: whether it was not. + pub(crate) fn hold(&mut self, object: &T) -> bool { + let first = self.addresses.insert(object.address()); + if first { + self.list.push(object.clone()); + } + first + } + + /// The objects kept, in the order first used. + pub(crate) fn iter(&self) -> std::slice::Iter<'_, T> { + self.list.iter() + } + + /// The objects kept, as a slice. + pub(crate) fn as_slice(&self) -> &[T] { + &self.list + } + + /// Releases every object, keeping the list's and the set's capacity. + pub(crate) fn clear(&mut self) { + self.list.clear(); + self.addresses.clear(); + } +} + +/// Every object a recording keeps, by kind. +#[derive(Default)] +pub(crate) struct Objects { + pub(crate) buffers: Kept, + pub(crate) textures: Kept, + pub(crate) samplers: Kept, + pub(crate) pipelines: Kept, + pub(crate) render_pipelines: Kept, +} + +impl Objects { + /// Releases every object, keeping each list's capacity for the next recording. + pub(crate) fn clear(&mut self) { + self.buffers.clear(); + self.textures.clear(); + self.samplers.clear(); + self.pipelines.clear(); + self.render_pipelines.clear(); + } +} + +/// Hashes an object's address: its bits mixed so that the low bits, which an allocation's +/// alignment leaves zero, are not the set's only index. +#[derive(Default)] +pub(crate) struct AddressHasher(u64); + +impl Hasher for AddressHasher { + fn write(&mut self, bytes: &[u8]) { + for &byte in bytes { + self.0 = (self.0 << 8 | u64::from(byte)).wrapping_mul(0x9e37_79b9_7f4a_7c15); + } + } + + fn write_usize(&mut self, address: usize) { + let mixed = (address as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15); + self.0 = mixed ^ (mixed >> 29); + } + + fn finish(&self) -> u64 { + self.0 + } +} diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index fa545aaea..a87e818d6 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -28,6 +28,7 @@ mod fill; pub mod floor; mod hazard; mod instance; +mod kept; mod kernel_map; mod memory; mod over; diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 8b0409f92..d18f99c8e 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -269,9 +269,71 @@ pub(crate) struct Kernel { entry: CString, pub(crate) interface: Interface, /// The `VkPipeline`s made so far, by their specialization. - variants: Mutex>, + variants: Variants, } +/// The variants of a kernel that each have a cell of their own. +const VARIANT_CELLS: usize = 8; + +/// A kernel's `VkPipeline`s made so far, by their specialization. The first [`VARIANT_CELLS`] +/// made each fill a cell of their own, which a dispatch reads with no lock; any made past them go +/// in a list under the lock that every making takes, so that one variant is made once. +#[derive(Default)] +struct Variants { + cells: [OnceLock<(Variant, vk::Pipeline)>; VARIANT_CELLS], + more: Mutex>, +} + +impl Variants { + /// The pipeline of the variant of `size`, threadgroup memory `lengths` and `tiles`, where its + /// cell holds it, read with no lock; `more`, the list past the cells, where they are all full. + fn in_cells(&self, (size, lengths, tiles): Key<'_>) -> Result { + for cell in &self.cells { + match cell.get() { + Some((variant, pipeline)) if variant.is(size, lengths, tiles) => { + return Ok(*pipeline) + } + Some(_) => {} + // Cells fill in order, under the lock: none after an empty one is full. + None => return Err(false), + } + } + Err(true) + } + + /// Keeps `pipeline`, of `variant`, made under the lock `more` is: in the first empty cell, + /// else in `more`. + fn keep( + &self, + more: &mut Vec<(Variant, vk::Pipeline)>, + variant: Variant, + pipeline: vk::Pipeline, + ) { + match self.cells.iter().find(|cell| cell.get().is_none()) { + // Only a making fills a cell, under the lock: the empty one stays empty until this. + Some(cell) => { + let _ = cell.set((variant, pipeline)); + } + None => more.push((variant, pipeline)), + } + } + + /// Every pipeline, taken out to give back. + fn drain(&mut self) -> impl Iterator + '_ { + let more = self + .more + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (self.cells.iter_mut()) + .filter_map(|cell| cell.take().map(|(_, pipeline)| pipeline)) + .chain(more.drain(..).map(|(_, pipeline)| pipeline)) + } +} + +/// A variant's key: its threadgroup size, its threadgroup memory lengths, whether it runs a +/// kernel's grid tiles. +pub(crate) type Key<'a> = ([u32; 3], &'a [u32], bool); + /// What the runtime needs of a kernel, from the translator. pub(crate) struct Interface { /// Each buffer slot the kernel uses, with its access. @@ -423,7 +485,6 @@ pub(crate) enum FieldValue { /// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the /// order of [`Interface::threadgroups`], and whether it runs a kernel's grid tiles. -#[derive(Clone, PartialEq, Eq)] pub(crate) struct Variant { pub(crate) size: [u32; 3], pub(crate) threadgroup_lengths: Vec, @@ -431,6 +492,13 @@ pub(crate) struct Variant { pub(crate) tiles: bool, } +impl Variant { + /// Whether this is the variant of `size`, threadgroup memory `lengths` and `tiles`. + fn is(&self, size: [u32; 3], lengths: &[u32], tiles: bool) -> bool { + self.size == size && self.threadgroup_lengths == lengths && self.tiles == tiles + } +} + /// The workgroup an image-only kernel that does not observe its threadgroup partition runs a grid /// one deep in ([`Form::Square`]). pub(crate) const SQUARE: [u32; 3] = [16, 16, 1]; @@ -639,7 +707,8 @@ impl Compiled { tiles, }; let made = compiled.whole.make(&compiled.core, &variant)?; - lock(&compiled.whole.variants).push((variant, made)); + let variants = &compiled.whole.variants; + variants.keep(&mut lock(&variants.more), variant, made); } Ok(compiled) } @@ -1062,7 +1131,7 @@ impl ComputePipelineState { module, entry: c"main".to_owned(), interface, - variants: Mutex::new(Vec::new()), + variants: Variants::default(), }; let compiled = Compiled::new(core, whole, Form::Sized { partial: None }, None, Vec::new()); Ok(ComputePipelineState { @@ -1205,7 +1274,7 @@ impl Kernel { module, entry, interface, - variants: Mutex::new(Vec::new()), + variants: Variants::default(), }) } @@ -1221,18 +1290,38 @@ impl Kernel { .map_err(Error::vulkan("vkCreateShaderModule")) } - /// The `VkPipeline` of `variant`, made now where it is not yet: the calling thread waits for - /// it, a first-use wait, so what is recorded never depends on when a compile finishes. - pub(crate) fn pipeline(&self, core: &Core, variant: &Variant) -> Result { - let mut variants = lock(&self.variants); - if let Some((_, pipeline)) = variants.iter().find(|(made, _)| made == variant) { - return Ok(*pipeline); + /// The `VkPipeline` of the variant `key`, made now where it is not yet: the calling thread + /// waits for it, a first-use wait, so what is recorded never depends on when a compile + /// finishes. One of the kernel's first [`VARIANT_CELLS`] variants is found with no lock. + pub(crate) fn pipeline(&self, core: &Core, key: Key<'_>) -> Result { + let variants = &self.variants; + let full = match variants.in_cells(key) { + Ok(pipeline) => return Ok(pipeline), + Err(full) => full, + }; + let mut more = lock(&variants.more); + let (size, lengths, tiles) = key; + let found = match full { + true => (more.iter()).find(|(variant, _)| variant.is(size, lengths, tiles)), + false => None, + }; + if let Some(&(_, pipeline)) = found { + return Ok(pipeline); } + // Another thread may have made it since the cells were read. + if let Ok(pipeline) = variants.in_cells(key) { + return Ok(pipeline); + } + let variant = Variant { + size, + threadgroup_lengths: lengths.to_vec(), + tiles, + }; let began = host_time(); - let pipeline = self.make(core, variant)?; + let pipeline = self.make(core, &variant)?; core.counters .first_use_wait(host_time().saturating_sub(began)); - variants.push((variant.clone(), pipeline)); + variants.keep(&mut more, variant, pipeline); Ok(pipeline) } @@ -1289,11 +1378,7 @@ impl Kernel { /// Gives the module and its `VkPipeline`s to the reaper. fn release(&mut self, core: &Core) { - let variants = self - .variants - .get_mut() - .unwrap_or_else(std::sync::PoisonError::into_inner); - for (_, pipeline) in variants.drain(..) { + for pipeline in self.variants.drain() { core.reaper.give(Job::Free(Free::Pipeline(pipeline))); } core.reaper.give(Job::Free(Free::ShaderModule(self.module))); @@ -1323,3 +1408,10 @@ impl Drop for Compiled { } } } + +// SAFETY: the handle is its one `Arc` and nothing else, and its address is that `Arc`'s pointer. +unsafe impl crate::kept::Handle for ComputePipelineState { + fn address(&self) -> usize { + Arc::as_ptr(&self.inner) as *const () as usize + } +} diff --git a/crates/metal2vulkan-rt/src/queue.rs b/crates/metal2vulkan-rt/src/queue.rs index 30390ffd7..575bc4e12 100644 --- a/crates/metal2vulkan-rt/src/queue.rs +++ b/crates/metal2vulkan-rt/src/queue.rs @@ -4,6 +4,7 @@ use crate::command::CommandBuffer; use crate::counters::{Counters, Gauge}; use crate::device::{lock, Core, Device}; use crate::error::{Error, Refusal}; +use crate::kept::Objects; use crate::reaper::{Free, Job}; use crate::times::Stamps; use std::sync::atomic::AtomicU64; @@ -44,6 +45,9 @@ struct Slots { next: u32, /// Slots given back. free: Vec, + /// The kept-object lists of retired command buffers, empty, with their capacity + /// (`crate::kept`): at most one per slot. + objects: Vec, } impl Slots { @@ -71,6 +75,7 @@ impl Device { slots: Mutex::new(Slots { next: 0, free: Vec::new(), + objects: Vec::new(), }), room: Condvar::new(), stamps: Stamps::new(core, max_command_buffer_count)?, @@ -86,7 +91,7 @@ impl Device { impl CommandQueue { /// `commandBuffer`: waits, as Metal does, while the queue's maximum count of its command /// buffers are made and not yet completed. `commandBufferWithUnretainedReferences` is the same - /// call: what a command buffer keeps is one reference per block it uses. + /// call: what a command buffer keeps is one reference per object it uses. /// /// Err: [`Error::Quiesced`]. pub fn command_buffer(&self) -> Result { @@ -112,12 +117,14 @@ impl CommandQueue { slots.next - 1 } }; + let kept = slots.objects.pop().unwrap_or_default(); drop(slots); core.counters.rise(Gauge::CommandBuffers); Ok(CommandBuffer::new( Arc::clone(&self.inner), self.device.clone(), slot, + kept, )) } @@ -166,12 +173,16 @@ impl QueueInner { self.core.upgrade() } - /// The command buffer holding `slot` retired, or was dropped uncommitted: the slot goes back. - /// Its gauge falls first, so a command buffer made in the freed slot never reads one more - /// live than the queue holds. - pub(crate) fn release(&self, slot: u32) { + /// The command buffer holding `slot` retired, or was dropped uncommitted: the slot goes back, + /// and `kept`, its kept-object lists emptied, for the next command buffer made. Its gauge falls + /// first, so a command buffer made in the freed slot never reads one more live than the queue + /// holds. + pub(crate) fn release(&self, slot: u32, kept: Objects) { self.counters.fall(Gauge::CommandBuffers); - lock(&self.slots).free.push(slot); + let mut slots = lock(&self.slots); + slots.free.push(slot); + slots.objects.push(kept); + drop(slots); self.room.notify_one(); } } diff --git a/crates/metal2vulkan-rt/src/render.rs b/crates/metal2vulkan-rt/src/render.rs index d86a52af4..7937058d8 100644 --- a/crates/metal2vulkan-rt/src/render.rs +++ b/crates/metal2vulkan-rt/src/render.rs @@ -849,3 +849,10 @@ impl Drop for RenderCompiled { release(&self.core, &self.stages); } } + +// SAFETY: the handle is its one `Arc` and nothing else, and its address is that `Arc`'s pointer. +unsafe impl crate::kept::Handle for RenderPipelineState { + fn address(&self) -> usize { + Arc::as_ptr(&self.inner) as *const () as usize + } +} diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index fa6d1d4a0..db1c24baf 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -71,6 +71,7 @@ use crate::encoder::{check_alignment, BUFFER_SLOTS, SAMPLER_SLOTS, TEXTURE_SLOTS use crate::error::{DrawKind, Error, Gap, Limit, Refusal}; use crate::fence::Fence; use crate::hazard::Access; +use crate::kept::{Handle, Lent}; use crate::over; use crate::pass::{layout_barrier, Pass, RenderPassDescriptor}; use crate::pipeline::{FieldValue, PUSH_STAGES}; @@ -288,18 +289,19 @@ enum Bound { #[default] Empty, Buffer { - buffer: Buffer, + buffer: Lent, offset: u64, }, /// A `set_*_bytes` copy in the parameter ring. Bytes(Placed), } -/// One function's argument tables. +/// One function's argument tables: their objects borrowed from what the command buffer keeps +/// (`crate::kept`). struct Tables { buffers: Vec, - textures: Vec>, - samplers: Vec>, + textures: Vec>>, + samplers: Vec>>, } impl Tables { @@ -321,7 +323,7 @@ impl Tables { /// The texture bound at `slot`, where one is. fn texture(&self, slot: u32) -> Option<&Texture> { - self.textures.get(slot as usize)?.as_ref() + self.textures.get(slot as usize)?.as_deref() } /// The address of buffer slot `slot`: the buffer's plus its offset, or the bytes' copy; `nil` @@ -382,7 +384,8 @@ pub struct RenderCommandEncoder { command: vk::CommandBuffer, /// The vertex function's argument tables, then the fragment function's. tables: [Tables; 2], - pipeline: Option, + /// The state set, borrowed from what the command buffer keeps (`crate::kept`). + pipeline: Option>, /// Whether the pipeline state renders into the pass's attachments' formats. renders_into: bool, /// The depth-stencil state's tests, Metal's default state's where none is set. @@ -573,17 +576,17 @@ impl RenderCommandEncoder { if self.pipeline.as_ref().is_some_and(|set| set.is(state)) { return Ok(()); } - self.building().keep_render_pipeline(state); self.renders_into = state.inner.compiled.renders_into(&self.pass); - self.pipeline = Some(state.clone()); + // SAFETY: the encoder holds the borrow, and it ends before its command buffer commits. + self.pipeline = Some(unsafe { self.building().lend_render_pipeline(state) }); self.changed(); Ok(()) } /// `setVertexBuffer:offset:atIndex:` (`setVertexBuffers:offsets:withRange:` is a loop of it). /// `None` unbinds the slot. The slot serves the vertex function's buffer argument of its index - /// and the vertex descriptor's layout of its index alike. The command buffer keeps the buffer's - /// block until it retires. + /// and the vertex descriptor's layout of its index alike. The command buffer keeps the buffer, + /// and so its block, until it retires. /// /// Err: [`Refusal::BufferIndex`] for an index of 31 or more; [`Refusal::OtherDevice`] for /// another device's buffer. @@ -619,13 +622,23 @@ impl RenderCommandEncoder { let slot = slot(index)?; let bound = match buffer { Some(buffer) => { + if let Bound::Buffer { + buffer: held, + offset: at, + } = &self.tables[table].buffers[slot] + { + if held.address() == buffer.address() && *at == offset { + return Ok(()); + } + } let building = self.building(); if !buffer.is_of(building.device.core()) { return Err(Error::Refused(Refusal::OtherDevice)); } - building.keep(buffer); Bound::Buffer { - buffer: buffer.clone(), + // SAFETY: the encoder's table holds the borrow, and it ends before its command + // buffer commits. + buffer: unsafe { building.lend_buffer(buffer) }, offset, } } @@ -732,14 +745,23 @@ impl RenderCommandEncoder { if index >= TEXTURE_SLOTS { return Err(Error::Refused(Refusal::TextureArgumentIndex { index })); } - if let Some(texture) = texture { - let building = self.building(); - if !texture.is_of(building.device.core()) { - return Err(Error::Refused(Refusal::OtherDevice)); - } - building.keep_texture(texture); + let held = &self.tables[table].textures[index as usize]; + if held.as_deref().map(Handle::address) == texture.map(Handle::address) { + return Ok(()); } - self.tables[table].textures[index as usize] = texture.cloned(); + let lent = match texture { + Some(texture) => { + let building = self.building(); + if !texture.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + // SAFETY: the encoder's table holds the borrow, and it ends before its command + // buffer commits. + Some(unsafe { building.lend_texture(texture) }) + } + None => None, + }; + self.tables[table].textures[index as usize] = lent; self.changed(); Ok(()) } @@ -780,14 +802,23 @@ impl RenderCommandEncoder { if index >= SAMPLER_SLOTS { return Err(Error::Refused(Refusal::SamplerArgumentIndex { index })); } - if let Some(sampler) = sampler { - let building = self.building(); - if !sampler.is_of(building.device.core()) { - return Err(Error::Refused(Refusal::OtherDevice)); - } - building.keep_sampler(sampler); + let held = &self.tables[table].samplers[index as usize]; + if held.as_deref().map(Handle::address) == sampler.map(Handle::address) { + return Ok(()); } - self.tables[table].samplers[index as usize] = sampler.cloned(); + let lent = match sampler { + Some(sampler) => { + let building = self.building(); + if !sampler.is_of(building.device.core()) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + // SAFETY: the encoder's table holds the borrow, and it ends before its command + // buffer commits. + Some(unsafe { building.lend_sampler(sampler) }) + } + None => None, + }; + self.tables[table].samplers[index as usize] = lent; self.push_filled = false; Ok(()) } diff --git a/crates/metal2vulkan-rt/src/sampler.rs b/crates/metal2vulkan-rt/src/sampler.rs index 6ffbb5460..770218dca 100644 --- a/crates/metal2vulkan-rt/src/sampler.rs +++ b/crates/metal2vulkan-rt/src/sampler.rs @@ -396,3 +396,10 @@ impl SamplerState { &self.inner.descriptor } } + +// SAFETY: the handle is its one `Arc` and nothing else, and its address is that `Arc`'s pointer. +unsafe impl crate::kept::Handle for SamplerState { + fn address(&self) -> usize { + Arc::as_ptr(&self.inner) as *const () as usize + } +} diff --git a/crates/metal2vulkan-rt/src/submit.rs b/crates/metal2vulkan-rt/src/submit.rs index 76fac6d2b..4b9ee827f 100644 --- a/crates/metal2vulkan-rt/src/submit.rs +++ b/crates/metal2vulkan-rt/src/submit.rs @@ -1407,7 +1407,7 @@ impl WorkState { // Each texture over a Managed buffer's device copy the command buffer keeps that an event // owes its copy in (`crate::over::ManagedOvers`). if pending.gpu.managed { - for texture in &pending.gpu.textures { + for texture in pending.gpu.kept.textures.iter() { let Some(buffer) = texture.managed_over() else { continue; }; diff --git a/crates/metal2vulkan-rt/src/tests/kept.rs b/crates/metal2vulkan-rt/src/tests/kept.rs new file mode 100644 index 000000000..3103c5e64 --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/kept.rs @@ -0,0 +1,71 @@ +//! What a recording keeps (`crate::kept`): each object once, its first use the one reference +//! taken; a later use and every borrow of it change no count; clearing releases every object. + +use crate::kept::{Handle, Kept}; +use std::sync::Arc; + +/// A handle of one `Arc`, as the runtime's objects are. +#[derive(Clone)] +struct Probe { + inner: Arc, +} + +// SAFETY: the handle is its one `Arc` and nothing else, and its address is that `Arc`'s pointer. +unsafe impl Handle for Probe { + fn address(&self) -> usize { + Arc::as_ptr(&self.inner) as usize + } +} + +/// An object kept, then used again, held again and borrowed many times, has one reference of the +/// list's; the borrows read it; clearing the list gives the reference back, and the next +/// recording keeps the object again. +#[test] +fn a_recording_keeps_an_object_once_and_its_borrows_change_no_count() { + let (a, b) = (Probe { inner: Arc::new(1) }, Probe { inner: Arc::new(2) }); + let mut kept = Kept::default(); + // SAFETY: every borrow ends before the list is cleared. + let lent = unsafe { kept.keep(&a) }; + assert_eq!( + Arc::strong_count(&a.inner), + 2, + "the first use takes one reference" + ); + let borrows: Vec<_> = (0..1_000) + .map(|_| { + // SAFETY: as above. + unsafe { kept.keep(&a) } + }) + .collect(); + assert!(!kept.hold(&a), "a kept object is not kept again"); + let copies: Vec<_> = (0..1_000).map(|_| lent.clone()).collect(); + assert_eq!( + Arc::strong_count(&a.inner), + 2, + "1,000 uses and 1,000 borrows' copies change no count" + ); + assert!(borrows + .iter() + .chain(&copies) + .all(|borrow| *borrow.inner == 1)); + assert!(kept.hold(&b), "another object is kept"); + assert_eq!( + kept.iter().map(|probe| *probe.inner).collect::>(), + [1, 2] + ); + drop((lent, borrows, copies)); + assert_eq!( + Arc::strong_count(&a.inner), + 2, + "dropping borrows releases nothing" + ); + kept.clear(); + assert_eq!( + (Arc::strong_count(&a.inner), Arc::strong_count(&b.inner)), + (1, 1), + "clearing releases each object's one reference" + ); + assert!(kept.as_slice().is_empty()); + assert!(kept.hold(&a), "a cleared list keeps the object again"); + assert_eq!(Arc::strong_count(&a.inner), 2); +} diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index ebd0d437e..521e4be29 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -11,6 +11,7 @@ mod fence; mod floor; mod hazard; mod heap; +mod kept; mod kernel_map; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod kernels; diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index 5fe8910d9..2b54e7fc3 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -3110,3 +3110,10 @@ pub(crate) struct OverCopy { /// The buffer is Shared: the host reads what a copy back writes. pub(crate) shared: bool, } + +// SAFETY: the handle is its one `Arc` and nothing else, and its address is that `Arc`'s pointer. +unsafe impl crate::kept::Handle for Texture { + fn address(&self) -> usize { + Arc::as_ptr(&self.inner) as *const () as usize + } +}