From 1d9ceb87c86cb6741f4f70082dcc5c4b5abd9f21 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 23:51:47 -0800 Subject: [PATCH] rt: the compute encoder's use_heap keeps the heap's block for its command buffer, and the new-runtime player plays useHeap Metal's useHeap: names a heap the encoder's work may reach. rt had no such call, so the player skipped and counted each one. ComputeCommandEncoder::use_heap takes the heap's block number (a HeapRange's block, or the block a placement heap's buffers sit in) and keeps that block in the command buffer until it retires, exactly as use_resource keeps a buffer's block (keep and the new keep_block share one list). Metal states no retention for useHeap:, so keeping is the safe reading. The call declares no access: a kernel that reaches a heap's resources through addresses outside its slots already orders against every write since the last barrier. A number no handle names answers Error::NoSuchBlock, as new_buffer's does. The player's compute encoders now call use_heap with the heap's block, and still skip and count a useHeap: of a skipped object. REPLAY-STREAM.md's skip list and the rt README say so. Test: heap::every_device_holds_a_used_heap_until_its_command_buffer_retires takes a Private block, uses it twice in one encoder (the command buffer holds it once), releases it while the encoder is open (the command buffer still holds it, and a new use of its number answers NoSuchBlock), commits, and waits for the block's last holder to go once the command buffer retires. api_signatures.tsv regenerated (one new method); REFUSALS.md unchanged. --- crates/metal2vulkan-rt/README.md | 4 ++ crates/metal2vulkan-rt/src/command.rs | 13 +++-- crates/metal2vulkan-rt/src/encoder.rs | 18 +++++++ crates/metal2vulkan-rt/src/tests/heap.rs | 54 +++++++++++++++++-- .../src/replay/new_runtime/encoders.rs | 12 +++-- .../src/replay/new_runtime/mod.rs | 10 ++++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/REPLAY-STREAM.md | 2 +- 8 files changed, 101 insertions(+), 13 deletions(-) diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 0a85225c0..7e2cac054 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -665,6 +665,10 @@ that touch blocks first. texture's format (`metal::format::integer_channels_word`); and for each constexpr sampler it samples through, the index the consumer gave it at the state's creation. Nothing is written into set 1 at bind or dispatch time, and every texture stays in its home layout. +- `use_heap` is `useHeap:`, for the block a heap's memory is: the command buffer keeps the block + until it retires, as it keeps a used buffer's block, so a heap given back while the work runs + stays valid under it. It declares no access (Metal states no retention for it; keeping is the + safe reading). - A dispatch of a kernel that writes no memory (the translator's `PipelineInterface::writes_memory`: no store to a buffer or through a device address, no texture write and no atomic update, in the kernel or any function it calls) records nothing, binds nothing and reads no indirect buffer, diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index 6510f9302..b032efab6 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -807,10 +807,7 @@ impl Building { /// 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)); - } + 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)) { @@ -819,6 +816,14 @@ impl Building { } } + /// Keeps `block` until the command buffer retires. + pub(crate) fn keep_block(&mut self, block: &Arc) { + let blocks = &mut self.gpu.blocks; + if !blocks.iter().rev().any(|kept| Arc::ptr_eq(kept, block)) { + blocks.push(Arc::clone(block)); + } + } + /// Keeps `state` until the command buffer retires. pub(crate) fn keep_pipeline(&mut self, state: &ComputePipelineState) { let pipelines = &mut self.gpu.pipelines; diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index b6611c956..aaa1700f2 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -6,6 +6,7 @@ use crate::counters::Metric; use crate::error::{Error, Gap, Limit, Refusal}; use crate::fence::Fence; use crate::hazard::Access; +use crate::memory::BlockId; use crate::over; use crate::pipeline::{ ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Variant, PUSH_BYTES, SQUARE, @@ -508,6 +509,23 @@ impl ComputeCommandEncoder { Ok(()) } + /// `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 + /// 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 + /// slots already orders against every write since the last barrier. + /// + /// Err: [`Error::NoSuchBlock`] for a number no handle names. + pub fn use_heap(&mut self, heap: BlockId) -> Result<(), Error> { + let building = self.building(); + let block = building.device.block(heap)?; + building.keep_block(&block); + Ok(()) + } + /// `memoryBarrierWithScope:` and `memoryBarrierWithResources:count:`: one global memory /// barrier either way, before the next dispatch. pub fn memory_barrier(&mut self) { diff --git a/crates/metal2vulkan-rt/src/tests/heap.rs b/crates/metal2vulkan-rt/src/tests/heap.rs index bdb528e8d..e9a88583f 100644 --- a/crates/metal2vulkan-rt/src/tests/heap.rs +++ b/crates/metal2vulkan-rt/src/tests/heap.rs @@ -3,15 +3,18 @@ //! placed first-fit by that answer in one heap range of a Private block take no allocation and no //! texture block, and each keeps its own bytes; a texture may alias another; a placement past the //! heap's end, one off the image's alignment, a heap range past its block and a heap in a Shared -//! block are refused; and every gauge reads zero after teardown. +//! block are refused; and every gauge reads zero after teardown. A compute encoder's `use_heap` +//! holds the heap's block for its command buffer once, past the consumer's release, until the +//! command buffer retires, and a released block's number names nothing. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { use crate::tests::command::on_device::each_device; use crate::{ - Error, Gap, HeapRange, MemoryClass, PixelFormat, Refusal, Region, StorageMode, - TextureDescriptor, TextureType, TextureUsage, + DispatchType, Error, Gap, HeapRange, MemoryClass, PixelFormat, Refusal, Region, + StorageMode, TextureDescriptor, TextureType, TextureUsage, }; + use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; @@ -156,4 +159,49 @@ mod on_device { } }); } + + #[test] + fn every_device_holds_a_used_heap_until_its_command_buffer_retires() { + each_device("use_heap", |name, _, device| { + let block = (device.take_block(MemoryClass::Private, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let id = block.id; + let memory = Arc::downgrade(&device.block(id).expect("the claimed block")); + assert_eq!( + memory.strong_count(), + 1, + "{name}: the claim alone holds the block" + ); + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = + (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + for _ in 0..2 { + (encoder.use_heap(id)).unwrap_or_else(|error| panic!("{name}: {error}")); + } + assert_eq!( + memory.strong_count(), + 2, + "{name}: the command buffer holds the block once" + ); + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!( + memory.strong_count(), + 1, + "{name}: the command buffer holds the block past the consumer's release" + ); + assert!( + matches!(encoder.use_heap(id), Err(Error::NoSuchBlock(at)) if at == id), + "{name}: a released block's number names nothing" + ); + encoder.end_encoding(); + (command_buffer.commit()).unwrap_or_else(|error| panic!("{name}: {error}")); + command_buffer.wait_until_completed(); + wait_until("the command buffer to retire", || { + memory.strong_count() == 0 + }); + assert_eq!(command_buffer.error(), None, "{name}"); + drop((command_buffer, queue)); + }); + } } diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs index b8ef64e0a..ea15a9ae8 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/encoders.rs @@ -331,11 +331,13 @@ impl NewRuntime { let fence = self.fence_of(call, 0)?; self.compute(id).encoder.wait_for_fence(&fence) } - // The runtime makes no heap residency calls. - "useHeap:" => { - self.skips.calls += 1; - Ok(()) - } + "useHeap:" => match self.heap_of(call, 0)? { + Some(heap) => self.compute(id).encoder.use_heap(heap), + None => { + self.skips.calls += 1; + Ok(()) + } + }, _ => return Err(refuse(call, "not played on a compute encoder")), }; result.map_err(failed(call)) diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index 61f0d5dad..ec7839259 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -479,6 +479,16 @@ impl NewRuntime { } } + /// The block of the heap argument `at` names; none for a skipped object. + fn heap_of(&self, call: &Call, at: usize) -> Result, PlayError> { + let id = Self::id(call, at)?; + match self.get(call, id)? { + Object::Block(range, _, _) => Ok(Some(range.block)), + Object::Skipped => Ok(None), + _ => Err(refuse(call, format!("#{id} is no heap"))), + } + } + fn buffer_of(&self, call: &Call, id: u64) -> Result { match self.get(call, id)? { Object::Buffer(buffer, _) => Ok(buffer.clone()), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 21652fd9e..5376f68fe 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9382,6 +9382,7 @@ method metal2vulkan-rt::ComputeCommandEncoder::set_sampler_state pub fn set_samp method metal2vulkan-rt::ComputeCommandEncoder::set_texture pub fn set_texture(&mut self, texture: Option<&Texture>, index: u32) -> Result<(), Error> method metal2vulkan-rt::ComputeCommandEncoder::set_threadgroup_memory_length pub fn set_threadgroup_memory_length(&mut self, length: u32, index: u32) -> Result<(), Error> method metal2vulkan-rt::ComputeCommandEncoder::update_fence pub fn update_fence(&mut self, fence: &Fence) -> Result<(), Error> +method metal2vulkan-rt::ComputeCommandEncoder::use_heap pub fn use_heap(&mut self, heap: BlockId) -> Result<(), Error> method metal2vulkan-rt::ComputeCommandEncoder::use_resource pub fn use_resource(&mut self, resource: Resource<'_>, usage: ResourceUsage) -> Result<(), Error> method metal2vulkan-rt::ComputeCommandEncoder::wait_for_fence pub fn wait_for_fence(&mut self, fence: &Fence) -> Result<(), Error> method metal2vulkan-rt::ComputePipelineDescriptor::lowering_inputs pub fn lowering_inputs(&self) -> LoweringInputs diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 36472d984..0e0656458 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -461,7 +461,7 @@ counted from 0), completes the work committed so far, reports as at the stream's - objects: render pipelines, depth-stencil states, render pass descriptors, libraries from source, and whatever a call makes of a skipped object (`skipped_objects`); - render and parallel render encoders (`skipped_encoders`), and every call of a skipped object - (`skipped_calls`, with `useResource:usage:` of one and a compute encoder's `useHeap:`); + (`skipped_calls`, with `useResource:usage:` and `useHeap:` of one); - dispatches whose pipeline state or bound buffer or texture is a skipped object (`skipped_dispatches`); - blit commands that name a skipped object (`skipped_blits`), and by kind: the host's copies