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.
This commit is contained in:
Anees Iqbal committed 2026-11-18 00:37:03 -08:00
1 parent c3e10e5ba9
commit 1d9ceb87c8
8 files changed
+101 -13

No files matched your search

+4
View File
@@ -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,
+9 -4
View File
@@ -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<Block>) {
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;
+18
View File
@@ -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) {
+51 -3
View File
@@ -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));
});
}
}
@@ -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))
@@ -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<Option<rt::BlockId>, 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<rt::Buffer, PlayError> {
match self.get(call, id)? {
Object::Buffer(buffer, _) => Ok(buffer.clone()),
@@ -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
Can't render this file because it is too large.
+1 -1
View File
@@ -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