Say what an indirect command holds of the pipeline state set on it

The steps this packet landed as, in order:
- Time indirect commands' CPU setters and getters in host_ab
- Read and write one field of an indirect command's record
- Set and read an indirect command's fields one at a time
- Call an indirect execution's check where it may see something, and run the CPU's later writes
- Load vkGetDescriptorSetLayoutSupport inside the exit guard's sections
- Hand out indirect command buffer IDs to 2^31 - 1 and place every one's records, as an M3 Max does
- Refuse an indirect command buffer reservation Metal hangs at as such
- Place an indirect command buffer's records at any length, found only at their start
- Leave a resource ID pool made after a reservation of 0 alone, as Metal does
- Ignore a late reservation call before looking at what it holds, as Metal does
- Expect the merged-draw tests' pipeline makings' notices on every device
- Keep an indirect compute command's threadgroup lengths where Metal keeps them
- Take the pieces of the ICB identifier range Metal's encoders take
- Answer a GPU-written command's state identifier as the state its ID named then
- Run a GPU-written record's released state as Metal does, from the buffer's kept programs
- State and test the bound on the programs a GPU-writable buffer keeps
- Record the earlier-window record of a re-held ID as a known gap

Content: the tree of `development` at 7d31ebb207, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:05 +02:00
1 parent c83dcdd384
commit 9516e41497
65 files changed
+5357 -1307

No files matched your search

+5 -5
View File
@@ -247,11 +247,11 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
- Resource ID reservations, placements and counts (`Device::reserve_resource_ids`,
`IdPlacement`, `Device::sampler_ids_live`), and the private getters of indirect commands.
- `execute_commands_in_buffer_checked` and `execute_commands_in_buffer_indirect_checked` (render and
compute encoders) take an `IndirectCommandCheck`, which the host step that records an execution
from records the GPU may have written calls with each command it will record, before it records
any. `execute_commands_in_buffer_checked` takes what the check looks for too
(`IndirectCommandCheckNeeds`): a render execution whose records cannot hold any of it runs on
the GPU alone where it can, and never calls the check.
compute encoders) take an `IndirectCommandCheck` and what it looks for
(`IndirectCommandCheckNeeds`). Wherever the runtime reads an execution's records, at `commit` for
the CPU's or in the host step for records the GPU may have written, it calls the check with each
command it will record, before it records any; an execution whose records cannot hold what the
check looks for never calls it, and runs on the GPU alone where it can.
- `HostMemory::with_dma_buf` and its `DmaBufSource`: dma-bufs of a no-copy object's pages, for a
device that refuses their pointer.
@@ -87,6 +87,65 @@ pub trait Gpu {
fn commands_id(&self, commands: &Self::IndirectCommands) -> u64;
/// The `gpuResourceID` of `state`, made with `supportIndirectCommandBuffers`.
fn pipeline_id(&self, state: &Self::ComputePipeline) -> u64;
/// `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:` of `count` concurrent
/// dispatches of `Shared` storage that inherit nothing and bind one kernel buffer, for the
/// CPU to encode.
fn cpu_indirect_commands(&self, count: usize) -> Self::IndirectCommands;
/// As `cpu_indirect_commands`, of draws of primitives binding one vertex and one fragment
/// buffer.
fn cpu_indirect_draws(&self, count: usize) -> Self::IndirectCommands;
/// `indirectComputeCommandAtIndex:`, then the command's `setComputePipelineState:`.
fn command_pipeline(
&self,
commands: &Self::IndirectCommands,
index: usize,
state: &Self::ComputePipeline,
);
/// `indirectComputeCommandAtIndex:`, then `setKernelBuffer:offset:atIndex:` at index 0.
fn command_kernel_buffer(
&self,
commands: &Self::IndirectCommands,
index: usize,
buffer: &Self::Buffer,
offset: usize,
);
/// `indirectComputeCommandAtIndex:`, then
/// `concurrentDispatchThreadgroups:threadsPerThreadgroup:` of `groups` of 64 threads.
fn command_dispatch(&self, commands: &Self::IndirectCommands, index: usize, groups: usize);
/// `indirectComputeCommandAtIndex:`, then `setBarrier`.
fn command_barrier(&self, commands: &Self::IndirectCommands, index: usize);
/// `indirectComputeCommandAtIndex:`, then Apple's private `getKernelBufferAddressAtIndex:` of
/// index 0 (the runtime's read-back of it).
fn command_kernel_buffer_address(&self, commands: &Self::IndirectCommands, index: usize)
-> u64;
/// `indirectComputeCommandAtIndex:`, then Apple's private `hasBarrier`.
fn command_has_barrier(&self, commands: &Self::IndirectCommands, index: usize) -> bool;
/// `indirectRenderCommandAtIndex:`, then `setRenderPipelineState:`.
fn draw_command_pipeline(
&self,
commands: &Self::IndirectCommands,
index: usize,
state: &Self::RenderPipeline,
);
/// `indirectRenderCommandAtIndex:`, then `setVertexBuffer:offset:atIndex:` at index 0.
fn draw_command_vertex_buffer(
&self,
commands: &Self::IndirectCommands,
index: usize,
buffer: &Self::Buffer,
offset: usize,
);
/// `indirectRenderCommandAtIndex:`, then
/// `drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:` of a triangle strip of
/// four vertices, one instance.
fn draw_command_draw(&self, commands: &Self::IndirectCommands, index: usize);
/// `indirectRenderCommandAtIndex:`, then Apple's private `getVertexBufferAddressAtIndex:` of
/// index 0 (the runtime's read-back of it).
fn draw_command_vertex_buffer_address(
&self,
commands: &Self::IndirectCommands,
index: usize,
) -> u64;
/// `newBufferWithLength:options:` of `Shared` storage.
fn buffer(&self, length: usize) -> Self::Buffer;
@@ -167,6 +167,11 @@
//! the kernel's code and so reads the records on the host. On the runtime's side, the commands
//! drawn on the GPU alone, the records read on the host, and the draws and pipeline barriers
//! recorded per frame (`rt_*`).
//! - `icb_cpu`: the CPU's encoding of indirect commands, each call's time: of 4096 commands of a
//! buffer of dispatches and one of draws, each setter (pipeline state, buffer, dispatch or draw,
//! barrier) on every command in turn, then Apple's private getters of a buffer's address and of
//! the barrier (the runtime's read-back of them), each call taking its command first
//! (`workloads::icb_cpu`).
//!
//! - `provoking`: an OpenGL guest's flat-shaded draws, which Apple's GL draws at
//! `setProvokingVertexMode:` 1 (the last vertex): one render pass into a 512x512 `BGRA8Unorm`
@@ -211,7 +216,7 @@ use std::process::{Command, Stdio};
use std::time::Instant;
use workloads::Sizes;
const WORKLOADS: [&str; 18] = [
const WORKLOADS: [&str; 19] = [
"encode",
"fixed",
"calls",
@@ -230,6 +235,7 @@ const WORKLOADS: [&str; 18] = [
"icb_draws",
"signals",
"provoking",
"icb_cpu",
];
struct Options {
@@ -500,6 +506,7 @@ fn run<G: Gpu>(g: &G, opened: Instant, metallib: &Path, options: &Options) {
"icb_draws" => workloads::icb_draws(g, &library, sizes),
"signals" => workloads::signals(g, &scene, sizes),
"provoking" => workloads::provoking(g, &library, sizes),
"icb_cpu" => workloads::icb_cpu(g, &library, sizes),
_ => unreachable!(),
}
}
@@ -2,6 +2,7 @@
use crate::gpu::{Format, Gpu};
use block2::RcBlock;
use objc2::msg_send;
use objc2::rc::{autoreleasepool, Retained};
use objc2::runtime::ProtocolObject;
use objc2_foundation::{NSString, NSURL};
@@ -12,11 +13,7 @@ use objc2_metal::{
MTLCreateSystemDefaultDevice, MTLCullMode, MTLDepthStencilDescriptor, MTLDepthStencilState,
MTLDevice, MTLDispatchType, MTLHazardTrackingMode, MTLHeap, MTLHeapDescriptor, MTLHeapType,
MTLIndexType, MTLIndirectCommandBuffer, MTLIndirectCommandBufferDescriptor,
MTLIndirectCommandType, MTLLibrary, MTLLoadAction, MTLOrigin, MTLPipelineOption,
MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor,
MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLRenderStages, MTLResource,
MTLResourceOptions, MTLResourceUsage, MTLSamplerDescriptor, MTLSamplerMinMagFilter,
MTLSamplerState, MTLSharedEvent, MTLSharedEventListener, MTLSize, MTLStorageMode,
MTLIndirectCommandType, MTLIndirectComputeCommand, MTLIndirectRenderCommand, MTLLibrary, MTLLoadAction, MTLOrigin, MTLPipelineOption, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLRenderStages, MTLResource, MTLResourceOptions, MTLResourceUsage, MTLSamplerDescriptor, MTLSamplerMinMagFilter, MTLSamplerState, MTLSharedEvent, MTLSharedEventListener, MTLSize, MTLStorageMode,
MTLStoreAction, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLWinding,
};
use std::ffi::c_void;
@@ -242,6 +239,159 @@ impl Gpu for Native {
state.gpuResourceID().to_raw()
}
fn cpu_indirect_commands(&self, count: usize) -> Self::IndirectCommands {
let descriptor = MTLIndirectCommandBufferDescriptor::new();
descriptor.setCommandTypes(MTLIndirectCommandType::ConcurrentDispatch);
descriptor.setInheritPipelineState(false);
descriptor.setInheritBuffers(false);
descriptor.setMaxKernelBufferBindCount(1);
// SAFETY: `count` is within Metal's most commands (16,384), which the workload keeps.
unsafe {
self.device
.newIndirectCommandBufferWithDescriptor_maxCommandCount_options(
&descriptor,
count,
MTLResourceOptions::StorageModeShared,
)
}
.expect("newIndirectCommandBufferWithDescriptor")
}
fn cpu_indirect_draws(&self, count: usize) -> Self::IndirectCommands {
let descriptor = MTLIndirectCommandBufferDescriptor::new();
descriptor.setCommandTypes(MTLIndirectCommandType::Draw);
descriptor.setInheritPipelineState(false);
descriptor.setInheritBuffers(false);
descriptor.setMaxVertexBufferBindCount(1);
descriptor.setMaxFragmentBufferBindCount(1);
// SAFETY: the descriptor is a draw buffer's, of a count within Metal's most.
unsafe {
self.device
.newIndirectCommandBufferWithDescriptor_maxCommandCount_options(
&descriptor,
count,
MTLResourceOptions::StorageModeShared,
)
}
.expect("newIndirectCommandBufferWithDescriptor")
}
fn command_pipeline(
&self,
commands: &Self::IndirectCommands,
index: usize,
state: &Self::ComputePipeline,
) {
// SAFETY: `index` is below the buffer's count (the workload's).
let command = unsafe { commands.indirectComputeCommandAtIndex(index) };
command.setComputePipelineState(state);
}
fn command_kernel_buffer(
&self,
commands: &Self::IndirectCommands,
index: usize,
buffer: &Self::Buffer,
offset: usize,
) {
// SAFETY: `index` is below the buffer's count, the buffer binds index 0, and `offset`
// lies inside `buffer` (the workload's).
unsafe {
let command = commands.indirectComputeCommandAtIndex(index);
command.setKernelBuffer_offset_atIndex(buffer, offset, 0);
}
}
fn command_dispatch(&self, commands: &Self::IndirectCommands, index: usize, groups: usize) {
let size = |width| MTLSize {
width,
height: 1,
depth: 1,
};
// SAFETY: `index` is below the buffer's count (the workload's).
let command = unsafe { commands.indirectComputeCommandAtIndex(index) };
command.concurrentDispatchThreadgroups_threadsPerThreadgroup(size(groups), size(64));
}
fn command_barrier(&self, commands: &Self::IndirectCommands, index: usize) {
// SAFETY: `index` is below the buffer's count (the workload's).
let command = unsafe { commands.indirectComputeCommandAtIndex(index) };
command.setBarrier();
}
fn command_kernel_buffer_address(
&self,
commands: &Self::IndirectCommands,
index: usize,
) -> u64 {
// SAFETY: `index` is below the buffer's count; Apple's private getter takes an index the
// descriptor binds and answers a `uint64_t` (measured by the consumer on an M3 Max).
unsafe {
let command = commands.indirectComputeCommandAtIndex(index);
msg_send![&*command, getKernelBufferAddressAtIndex: 0usize]
}
}
fn command_has_barrier(&self, commands: &Self::IndirectCommands, index: usize) -> bool {
// SAFETY: `index` is below the buffer's count; Apple's private getter answers a `BOOL`.
unsafe {
let command = commands.indirectComputeCommandAtIndex(index);
msg_send![&*command, hasBarrier]
}
}
fn draw_command_pipeline(
&self,
commands: &Self::IndirectCommands,
index: usize,
state: &Self::RenderPipeline,
) {
// SAFETY: `index` is below the buffer's count (the workload's).
let command = unsafe { commands.indirectRenderCommandAtIndex(index) };
command.setRenderPipelineState(state);
}
fn draw_command_vertex_buffer(
&self,
commands: &Self::IndirectCommands,
index: usize,
buffer: &Self::Buffer,
offset: usize,
) {
// SAFETY: `index` is below the buffer's count, the buffer binds vertex index 0, and
// `offset` lies inside `buffer` (the workload's).
unsafe {
let command = commands.indirectRenderCommandAtIndex(index);
command.setVertexBuffer_offset_atIndex(buffer, offset, 0);
}
}
fn draw_command_draw(&self, commands: &Self::IndirectCommands, index: usize) {
// SAFETY: `index` is below the buffer's count; a strip of four vertices, one instance.
unsafe {
let command = commands.indirectRenderCommandAtIndex(index);
command.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance(
MTLPrimitiveType::TriangleStrip,
0,
4,
1,
0,
);
}
}
fn draw_command_vertex_buffer_address(
&self,
commands: &Self::IndirectCommands,
index: usize,
) -> u64 {
// SAFETY: as `command_kernel_buffer_address`'s, of Apple's private vertex getter.
unsafe {
let command = commands.indirectRenderCommandAtIndex(index);
msg_send![&*command, getVertexBufferAddressAtIndex: 0usize]
}
}
fn buffer(&self, length: usize) -> Self::Buffer {
self.device
.newBufferWithLength_options(length, MTLResourceOptions::StorageModeShared)
@@ -64,6 +64,23 @@ impl Runtime {
}
}
/// Command `index` of `commands`' setters (`indirectComputeCommandAtIndex:`).
fn compute_command(
commands: &rt::IndirectCommandBuffer,
index: usize,
) -> rt::IndirectComputeCommand {
commands
.indirect_compute_command_at(index as u64)
.expect("indirect_compute_command_at")
}
/// Command `index` of `commands`' setters (`indirectRenderCommandAtIndex:`).
fn render_command(commands: &rt::IndirectCommandBuffer, index: usize) -> rt::IndirectRenderCommand {
commands
.indirect_render_command_at(index as u64)
.expect("indirect_render_command_at")
}
fn pixel_format(format: Format) -> PixelFormat {
match format {
Format::Bgra8 => PixelFormat::BGRA8Unorm,
@@ -247,6 +264,128 @@ impl Gpu for Runtime {
state.gpu_resource_id().0
}
fn cpu_indirect_commands(&self, count: usize) -> rt::IndirectCommandBuffer {
let mut descriptor = rt::IndirectCommandBufferDescriptor::new();
descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH;
descriptor.inherit_pipeline_state = false;
descriptor.inherit_buffers = false;
descriptor.max_kernel_buffer_bind_count = 1;
self.device
.new_indirect_command_buffer(&descriptor, count as u64, rt::ResourceOptions::shared())
.expect("new_indirect_command_buffer")
}
fn cpu_indirect_draws(&self, count: usize) -> rt::IndirectCommandBuffer {
let mut descriptor = rt::IndirectCommandBufferDescriptor::new();
descriptor.command_types = IndirectCommandType::DRAW;
descriptor.inherit_pipeline_state = false;
descriptor.inherit_buffers = false;
descriptor.max_vertex_buffer_bind_count = 1;
descriptor.max_fragment_buffer_bind_count = 1;
self.device
.new_indirect_command_buffer(&descriptor, count as u64, rt::ResourceOptions::shared())
.expect("new_indirect_command_buffer")
}
fn command_pipeline(
&self,
commands: &rt::IndirectCommandBuffer,
index: usize,
state: &rt::ComputePipelineState,
) {
compute_command(commands, index)
.set_compute_pipeline_state(state)
.expect("set_compute_pipeline_state");
}
fn command_kernel_buffer(
&self,
commands: &rt::IndirectCommandBuffer,
index: usize,
buffer: &rt::Buffer,
offset: usize,
) {
compute_command(commands, index)
.set_kernel_buffer(Some(buffer), offset as u64, 0)
.expect("set_kernel_buffer");
}
fn command_dispatch(&self, commands: &rt::IndirectCommandBuffer, index: usize, groups: usize) {
compute_command(commands, index)
.concurrent_dispatch_threadgroups(
rt::Size::new(groups as u64, 1, 1),
rt::Size::new(64, 1, 1),
)
.expect("concurrent_dispatch_threadgroups");
}
fn command_barrier(&self, commands: &rt::IndirectCommandBuffer, index: usize) {
compute_command(commands, index)
.set_barrier()
.expect("set_barrier");
}
fn command_kernel_buffer_address(
&self,
commands: &rt::IndirectCommandBuffer,
index: usize,
) -> u64 {
compute_command(commands, index)
.kernel_buffer(0)
.expect("kernel_buffer")
.expect("a kernel buffer")
.address
.0
}
fn command_has_barrier(&self, commands: &rt::IndirectCommandBuffer, index: usize) -> bool {
compute_command(commands, index)
.has_barrier()
.expect("has_barrier")
}
fn draw_command_pipeline(
&self,
commands: &rt::IndirectCommandBuffer,
index: usize,
state: &rt::RenderPipelineState,
) {
render_command(commands, index)
.set_render_pipeline_state(state)
.expect("set_render_pipeline_state");
}
fn draw_command_vertex_buffer(
&self,
commands: &rt::IndirectCommandBuffer,
index: usize,
buffer: &rt::Buffer,
offset: usize,
) {
render_command(commands, index)
.set_vertex_buffer(Some(buffer), offset as u64, 0)
.expect("set_vertex_buffer");
}
fn draw_command_draw(&self, commands: &rt::IndirectCommandBuffer, index: usize) {
render_command(commands, index)
.draw_primitives(PrimitiveType::TriangleStrip, 0, 4, 1, 0)
.expect("draw_primitives");
}
fn draw_command_vertex_buffer_address(
&self,
commands: &rt::IndirectCommandBuffer,
index: usize,
) -> u64 {
render_command(commands, index)
.vertex_buffer(0)
.expect("vertex_buffer")
.expect("a vertex buffer")
.address
.0
}
fn buffer(&self, length: usize) -> rt::Buffer {
self.device
.new_buffer(length as u64, rt::ResourceOptions::shared())
@@ -2450,6 +2450,75 @@ pub fn icb<G: Gpu>(g: &G, library: &G::Library, sizes: &Sizes) {
}
}
/// The commands of each of the icb_cpu workload's buffers.
const ICB_CPU_COMMANDS: usize = 4096;
/// The icb_cpu workload (main.rs): the CPU's encoding of indirect commands and their read-back,
/// each call's time. Per pass, over [`ICB_CPU_COMMANDS`] commands of a buffer of dispatches and
/// one of draws (`Shared`, inheriting nothing), each setter on every command in turn, then each
/// getter; each call takes the command (`indirectComputeCommandAtIndex:` or
/// `indirectRenderCommandAtIndex:`) first, as a program that encodes once per command does. The
/// medians over the passes, in nanoseconds a call; [`ICB_WARM`] untimed passes first.
pub fn icb_cpu<G: Gpu>(g: &G, library: &G::Library, sizes: &Sizes) {
let state = g.indirect_compute_pipeline(library, "icb_step0");
let draw = g.indirect_render_pipeline(library, "icb_draw_vertex", "icb_draw_fragment");
let buffer = g.buffer(ICB_CPU_COMMANDS * 256);
let dispatches = g.cpu_indirect_commands(ICB_CPU_COMMANDS);
let draws = g.cpu_indirect_draws(ICB_CPU_COMMANDS);
let names = [
"set_compute_pipeline",
"set_kernel_buffer",
"dispatch_threadgroups",
"set_barrier",
"kernel_buffer_address",
"has_barrier",
"set_render_pipeline",
"set_vertex_buffer",
"draw_primitives",
"vertex_buffer_address",
];
let mut times: Vec<Vec<f64>> = vec![Vec::new(); names.len()];
let mut sink = 0u64;
for pass in 0..ICB_WARM + sizes.timed {
g.pool(|| {
let mut timed = |at: usize, call: &mut dyn FnMut(usize)| {
let t = Instant::now();
for index in 0..ICB_CPU_COMMANDS {
call(index);
}
if pass >= ICB_WARM {
let each = t.elapsed().as_secs_f64() * 1e9 / ICB_CPU_COMMANDS as f64;
times[at].push(each);
}
};
timed(0, &mut |i| g.command_pipeline(&dispatches, i, &state));
timed(1, &mut |i| {
g.command_kernel_buffer(&dispatches, i, &buffer, i * 256)
});
timed(2, &mut |i| g.command_dispatch(&dispatches, i, 1 + i % 4));
timed(3, &mut |i| g.command_barrier(&dispatches, i));
timed(4, &mut |i| {
sink = sink.wrapping_add(g.command_kernel_buffer_address(&dispatches, i))
});
timed(5, &mut |i| {
sink = sink.wrapping_add(u64::from(g.command_has_barrier(&dispatches, i)))
});
timed(6, &mut |i| g.draw_command_pipeline(&draws, i, &draw));
timed(7, &mut |i| {
g.draw_command_vertex_buffer(&draws, i, &buffer, i * 256)
});
timed(8, &mut |i| g.draw_command_draw(&draws, i));
timed(9, &mut |i| {
sink = sink.wrapping_add(g.draw_command_vertex_buffer_address(&draws, i))
});
});
}
std::hint::black_box(sink);
for (name, times) in names.iter().zip(&mut times) {
emit("icb_cpu", name, "ns", times);
}
}
/// The icb_draws workload's objects, as many as Apple's "Encoding Indirect Command Buffers on the GPU"
/// draws (`AAPLNumObjects`), on a grid of `ICB_DRAW_GRID` columns.
const ICB_DRAW_OBJECTS: usize = 65536;
+16 -9
View File
@@ -50,9 +50,11 @@
//! - **Indirect command buffers' records**: an indirect command buffer's ID is the one Metal's pool
//! of their own space hands out, from 1, as Metal's `gpuResourceID` is (an M3 Max and an M4; the
//! pool's rule, first 32 IDs, is `resource_ids.rs`'), or the one it is placed at, and its records
//! lie at `records_address` of it, `2^63 + id * 2^40`, the address a translated kernel encoding
//! through the ID reaches. So the records take no Metal address, as Metal's indirect command
//! buffers take none of its buffers' (four of 1024 commands moved no buffer made after them).
//! start at `records_address` of it, `2^63 + id * 2^31`, the address a translated kernel
//! encoding through the ID reaches: records of more than 2^31 bytes run past later IDs' starts,
//! which the kernel's search tells apart, as it finds records only at their start. So the
//! records take no Metal address, as Metal's indirect command buffers take none of its buffers'
//! (four of 1024 commands moved no buffer made after them).
//! - **Records IDs** (the M4 probe, plain Metal). The buffer holds its ID
//! ([`RecordsId`]), not its records' memory: the ID is free again once the buffer and every
//! command that holds it are gone, a compute or render execution and a `useResource` until their
@@ -70,9 +72,7 @@ use super::exit_guard;
use super::program_objects::ProgramObject;
use super::range::RangeAllocator;
use super::resource_ids::Pool;
use metal2vulkan::bind::indirect_commands::{
records_address, RECORDS_ADDRESS_SHIFT, RECORDS_ID_LIMIT,
};
use metal2vulkan::bind::indirect_commands::{records_address, RECORDS_ID_LIMIT};
use std::collections::BTreeMap;
use std::mem::ManuallyDrop;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -476,6 +476,12 @@ impl AddressSpace {
self.records.pool.reserve(ids.iter().copied())
}
/// Whether the records' pool handed out an ID or took a reservation: a reservation is
/// ignored then (`Pool::started`).
pub(super) fn records_started(&self) -> bool {
self.records.pool.started()
}
/// A new indirect command buffer's records ID, now held and its slot's (module docs):
/// `placed`, or the one Metal hands out next; `None` when that is [`RECORDS_ID_LIMIT`] or
/// more. The buffer gives it back with [`give_records_id`](Self::give_records_id).
@@ -494,11 +500,12 @@ impl AddressSpace {
self.records.slots.get(&held.id) == Some(&held.serial)
}
/// The records of an indirect command buffer of `length` bytes (at most 2^40) holding
/// records ID `id`: at `records_address` of it. `None` past either bound.
/// The records of an indirect command buffer of `length` bytes holding records ID `id`: from
/// `records_address` of it, of any length that ends below 2^64 (2^62 bytes past the last
/// ID's start). `None` for an ID of [`RECORDS_ID_LIMIT`] or more, or a longer length.
fn records(id: u64, length: u64) -> Option<(GpuAddress, Held)> {
let size = Self::span(length)?;
if size > 1 << RECORDS_ADDRESS_SHIFT || id >= RECORDS_ID_LIMIT {
if id >= RECORDS_ID_LIMIT || records_address(id).checked_add(size).is_none() {
return None;
}
let start = records_address(id);
+1 -1
View File
@@ -177,7 +177,7 @@ impl CommandBuffer {
/// after one was abandoned, and after commit.
pub fn blit_command_encoder(&self) -> Result<BlitCommandEncoder, Error> {
Ok(BlitCommandEncoder {
core: EncoderCore::open(self, "blit_command_encoder", true)?,
core: EncoderCore::open(self, "blit_command_encoder", EncoderKind::Blit, true)?,
pattern: None,
shadows: Vec::new(),
log: (self.device().shared().rebinds.any())
@@ -76,6 +76,8 @@ impl BlitCommandEncoder {
return Ok(());
}
destination.written_by_gpu();
self.core().retain(destination.gpu_write());
destination.keep_copied(source, from.clone());
destination.written().copied_from(source.written());
// The slots past the records', carried as Metal's copy carries every slot below the count.
self.copy_overflow(source, from.clone(), destination, to.start)?;
@@ -118,6 +120,7 @@ impl BlitCommandEncoder {
.encode_into(&mut reset)
.map_err(|_| internal("a reset record does not encode"))?;
buffer.written_by_gpu();
self.core().retain(buffer.gpu_write());
let bytes = IndirectCommandBuffer::record_bytes(range.clone());
let overflow = buffer
.overflow()
@@ -91,6 +91,7 @@ use super::sparse::indirect::{self, ReadFailure};
use super::texture::storage_form::Riding;
use super::texture::Texture;
use super::tracker::Footprint;
use super::unique_identifier::ScheduledWork;
use super::upload::{Upload, Uploads};
use super::used_resources::{names_any, EncoderKind, EncoderRecord, Reached, ReadRecord};
use super::values::CommandBufferStatus;
@@ -529,6 +530,9 @@ pub(super) struct State {
/// Its scheduled handlers ran: `wait_until_scheduled` returns, as Metal's does only once
/// they ran.
scheduled_ran: bool,
/// What its encoders did that Metal's identifier allocations follow as it is scheduled
/// (`unique_identifier.rs`).
scheduled_work: ScheduledWork,
/// The threads sleeping on its `changed` condition variable: a change wakes it only where
/// one does ([`CommandBufferShared::wake_parked`]).
parked: usize,
@@ -1610,6 +1614,7 @@ impl CommandBuffer {
submission: VecDeque::new(),
submitting: false,
scheduled_ran: false,
scheduled_work: ScheduledWork::default(),
parked: 0,
failure: None,
completed: VecDeque::new(),
@@ -1699,6 +1704,14 @@ impl CommandBuffer {
}
/// The state, locked.
/// Note `work` of an encoder it ended, which its scheduling hands to the device's identifier
/// allocations ([`UniqueIdentifiers::scheduled`](crate::unique_identifier::UniqueIdentifiers::scheduled)).
pub(super) fn note_scheduled_work(&self, work: ScheduledWork) {
let mut state = self.state();
state.scheduled_work.dispatch |= work.dispatch;
state.scheduled_work.render |= work.render;
}
pub(super) fn state(&self) -> MutexGuard<'_, State> {
lock(&self.0.state)
}
@@ -3042,8 +3055,12 @@ impl CommandBufferShared {
summaries.push(&encoder.summary);
for segment in &encoder.segments {
match &segment.recorded {
// One recorded again on the GPU alone uses what its recording does.
Some(recording) if !segment.needs_step() || segment.rerecords() => {
// One recorded again on the GPU alone uses what its recording does; one a
// route outgrew, what its host step finds.
Some(recording)
if !segment.needs_step()
|| (segment.rerecords() && !segment.work.outgrown()) =>
{
summaries.push(&recording.summary)
}
_ => known.push(segment.known_summary(&self.device)?),
@@ -3102,11 +3119,17 @@ impl CommandBufferShared {
if steps.is_empty() {
return;
}
// The first segment a host step records, which the device announces: a recording on the
// GPU alone made again announces nothing (`gpu_execute::Rerecord`).
// The first segment a host step records for what the GPU may write, which the device
// announces: a recording on the GPU alone made again announces nothing
// (`gpu_execute::Rerecord`), unless a route outgrew it (`Deferred::outgrown`), which the
// step records from the records; nor does work recorded again for the CPU's writes since
// the commit alone (`Deferred::rewritten`), or for its pipelines alone.
let announced = steps
.iter()
.find(|(_, _, inputs)| !matches!(inputs, Some(StepInputs::Rerecord(_))))
.find(|(_, work, inputs)| {
work.gpu_written()
&& (!matches!(inputs, Some(StepInputs::Rerecord(_))) || work.outgrown())
})
.map(|(_, work, _)| work.clone());
let buffer = CommandBuffer(Arc::clone(self));
for ((encoder, at), work, inputs) in steps {
@@ -3648,6 +3671,12 @@ impl CommandBufferShared {
}
state = lock(&self.state);
}
// Metal's dispatch and render work take their identifier allocations as the command
// buffer is scheduled, before its status reads so (`unique_identifier.rs`).
self.device
.shared()
.identifiers
.scheduled(state.scheduled_work);
state.status = CommandBufferStatus::Scheduled;
self.answer(&state);
}
+29 -19
View File
@@ -95,6 +95,7 @@ use metal2vulkan::metal::{BarrierScope, DispatchType, RenderStages, ResourceUsag
use metal2vulkan::pipeline::Stage;
use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex, OnceLock};
/// Entries of a compute encoder's threadgroup memory table.
@@ -226,7 +227,12 @@ impl CommandBuffer {
call: &'static str,
dispatch_type: DispatchType,
) -> Result<ComputeCommandEncoder, Error> {
let core = EncoderCore::open(self, call, dispatch_type == DispatchType::Serial)?;
let core = EncoderCore::open(
self,
call,
EncoderKind::Compute,
dispatch_type == DispatchType::Serial,
)?;
// It joins its command buffer's unit of command predication, carrying on the loops open
// across its start, or starts the next.
let carried = self.state().enter_predication(dispatch_type);
@@ -1005,6 +1011,7 @@ impl ComputeCommandEncoder {
if let ResourceRef::IndirectCommandBuffer(icb) = resource {
if usage.contains(ResourceUsage::WRITE) {
self.writers.made_writable(icb.written());
self.core.retain(icb.gpu_write());
}
}
}
@@ -1073,16 +1080,16 @@ impl ComputeCommandEncoder {
}
/// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) with a check of the
/// commands its host step runs (a runtime extension; Metal has none): where a host step
/// records the execution from the records as the GPU and the CPU left them (an encoder made
/// `icb` resident for writing, or the execution lies inside a block of command predication),
/// the step first calls `check` with each command it will record, in order, before it records
/// any of them ([`IndirectCommandCheck`]); `needs` is what it looks for
/// ([`IndirectCommandCheckNeeds`], the render encoder's shape). An execution recorded at the
/// commit from the CPU's records never calls it, and one with a check never runs on the GPU
/// alone (`VK_EXT_device_generated_commands`), whatever its `needs`, so the step always reads
/// the records. Refused as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer)
/// refuses.
/// commands it runs (a runtime extension; Metal has none), which looks for what `needs` names
/// ([`IndirectCommandCheckNeeds`]; a compute command draws no points): where the commit records
/// the execution from the CPU's records, or a host step from the records as the GPU and the CPU
/// left them (an encoder made `icb` resident for writing, or the execution lies inside a block
/// of command predication), it first calls `check` with each command it will record, in order,
/// before it records any of them ([`IndirectCommandCheck`]). Where what the records may hold
/// leaves the check nothing to see, neither calls it, and an execution a host step would record
/// may run on the GPU alone, as an unchecked one may; a route encoded after the commit that
/// gives the check something to see before the batch is submitted sends it to the host step.
/// Refused as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) refuses.
pub fn execute_commands_in_buffer_checked(
&mut self,
icb: &IndirectCommandBuffer,
@@ -1154,11 +1161,12 @@ impl ComputeCommandEncoder {
}
/// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect) with a
/// check of the commands its host step runs, which always records it: the step first calls
/// `check` with each command of the range it read that it will record, in order, before it
/// records any of them, as
/// check of the commands its host step runs, which always records it, looking for what `needs`
/// names: the step first calls `check` with each command of the range it read that it will
/// record, in order, before it records any of them, as
/// [`execute_commands_in_buffer_checked`](Self::execute_commands_in_buffer_checked)'s does
/// ([`IndirectCommandCheck`]). Refused as
/// ([`IndirectCommandCheck`]), unless what the records may hold then leaves the check nothing
/// to see ([`IndirectCommandCheckNeeds`]). Refused as
/// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect) refuses.
pub fn execute_commands_in_buffer_indirect_checked(
&mut self,
@@ -1166,9 +1174,9 @@ impl ComputeCommandEncoder {
range_buffer: &Buffer,
offset: u64,
check: IndirectCommandCheck,
needs: IndirectCommandCheckNeeds,
) -> Result<(), Error> {
let check = (check, IndirectCommandCheckNeeds::ALL);
self.execute_indirect_range(icb, range_buffer, offset, Some(check))
self.execute_indirect_range(icb, range_buffer, offset, Some((check, needs)))
}
/// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect), with
@@ -1247,8 +1255,8 @@ impl ComputeCommandEncoder {
let mut state = self.core.command_buffer().state();
let held = &mut *state;
let gate = held.predication.host_gate();
let (further, preprocess_gate) = match (&gate, &range, &check) {
(Some(_), ExecutionRange::Fixed(range), None) if !range.is_empty() => {
let (further, preprocess_gate) = match (&gate, &range) {
(Some(_), ExecutionRange::Fixed(range)) if !range.is_empty() => {
let count = [range.len() as u32, 1, 1];
let (further, mut gates) =
held.predication
@@ -1271,6 +1279,8 @@ impl ComputeCommandEncoder {
gate,
preprocess_gate,
check: check.map(|(check, needs)| (Mutex::new(check), needs)),
unchecked: Mutex::new(None),
read_at: AtomicU64::new(indirect_execute::NOT_READ),
})))?;
// Its commands may name any pipeline state.
self.command_encoded(true);
+41 -10
View File
@@ -5,6 +5,7 @@
//! (`command_buffer`).
use super::command_buffer::CommandBuffer;
use super::device::lock;
use super::encoder::RecordedSegment;
use super::error::{internal, Error};
use super::gpu_execute::{self, Rerecord};
@@ -138,15 +139,27 @@ impl Deferred {
let device = command_buffer.device();
match self {
Deferred::Execute(execute) if step => {
// On the GPU alone where it is total (`gpu_execute.rs`): not a checked execution,
// whose step reads its records for the caller's check, nor one inside a block of
// command predication without its preprocess's gate, whose step reads the counter.
// On the GPU alone where it is total (`gpu_execute.rs`): not a checked execution
// whose check may see something, whose step reads its records for the check, nor
// one inside a block of command predication without its preprocess's gate, whose
// step reads the counter. A checked one's host step, where a route encoded since
// gives its check something to see (`Execute::outgrown`), is settled now.
if let Some((recorded, inputs)) = self.record_on_gpu(command_buffer)? {
let retained: Option<Box<dyn Any + Send + Sync>> = match &execute.check {
Some(_) => {
let residency = command_buffer.residency()?.kernel();
let Settled { states, variants } =
execute.settle(device, execute.states(device), &residency);
*lock(&execute.unchecked) = Some(states);
Some(Box::new(variants))
}
None => None,
};
return Ok(Prepared {
recorded: Some(recorded),
for_good: true,
inputs,
retained: None,
retained,
pipelines: false,
});
}
@@ -307,6 +320,12 @@ impl Deferred {
) -> Result<RecordedSegment, Error> {
match self {
Deferred::Execute(execute) => {
// Recorded on the GPU alone with a check a route encoded since gave something to
// see: recorded from the records as the GPU and the CPU left them, naming states
// among those `commit` settled, for good.
if let Some(states) = execute.take_outgrown() {
return execute.record(command_buffer, Some(&states));
}
let states = match inputs {
StepInputs::Settled(states) => states.clone(),
StepInputs::Unforeseen(unforeseen) => {
@@ -332,15 +351,27 @@ impl Deferred {
}
/// Whether a route encoded since `commit` recorded the work for good on the GPU may write
/// more than `commit` decided on (`DeferredPass::outgrown`): its host step records it
/// instead, before its batch is submitted. A render pass's executions' GPU form alone.
/// more than `commit` decided on (`DeferredPass::outgrown`), or gives the check of an
/// execution recorded there something to see (`Execute::outgrown`): its host step records it
/// instead, before its batch is submitted. A render pass's executions' GPU form, and an
/// execution's on the GPU alone with a check.
pub(super) fn outgrown(&self) -> bool {
match self {
Deferred::RenderPass(pass) => pass.outgrown(),
Deferred::Execute(_)
| Deferred::Dispatch(_)
| Deferred::SparseScrub(_)
| Deferred::Pending(_) => false,
Deferred::Execute(execute) => execute.outgrown(),
Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Pending(_) => false,
}
}
/// Whether `commit` recorded it from the CPU's records of an indirect command buffer the CPU
/// wrote since (`Execute::rewritten`, `DeferredPass::rewritten`): its host step records it
/// again from the records as they stand then, before its batch is submitted, waiting for no
/// work on the GPU.
pub(super) fn rewritten(&self) -> bool {
match self {
Deferred::Execute(execute) => execute.rewritten(),
Deferred::RenderPass(pass) => pass.rewritten(),
Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Pending(_) => false,
}
}
+41 -41
View File
@@ -654,9 +654,11 @@ degradations! {
/// its records may hold, at the commit or as its batch is ready, more than draws of one
/// primitive type under the encoder's state, or what its check looks for
/// (`render/executions/gpu.rs`); its notice names the first rule that kept it from the GPU
/// alone. A compute execution: with the caller's check
/// (`execute_commands_in_buffer_checked`); with its range read from a buffer; of a buffer
/// that inherits the encoder's buffers; where its records may name a pipeline state whose
/// alone. A compute execution: with a caller's check (`execute_commands_in_buffer_checked`)
/// that may see what it looks for (`IndirectCommandCheckNeeds`: a state that may encode
/// indirect commands, the encoder's where the buffer inherits it, else one its records may
/// name), at the commit or as its batch is ready; with its range read from a buffer; of a
/// buffer that inherits the encoder's buffers; where its records may name a pipeline state whose
/// kernel observes its threadgroup partition or fetches `[[stage_in]]` attributes, or a
/// state the CPU set that the program released since; and, on a device without
/// `VK_EXT_device_generated_commands`, where the host step is faster: where its commands
@@ -1256,27 +1258,33 @@ degradations! {
driver's vkGetDescriptorSetLayoutSupport refuses the layout, so Vulkan's validation \
layer reports each such layout (VUID-vkCreateDescriptorSetLayout-support-09582)";
/// An indirect command naming the ID of a pipeline state the program released is
/// executed where the runtime cannot run what Metal runs (`indirect_command_buffer.rs`). A
/// command holds the program of the state the CPU set on it, and runs it while its record
/// names the state's ID, whoever took the ID since, as Metal's command the CPU encoded
/// does: that is announced nowhere. Announced: a record naming another ID (the GPU wrote
/// it) that no state took since the program released a state of the command's kind holding
/// it, whose program Metal runs and the runtime does not hold, so the command runs nothing;
/// and in a host step of records the GPU may write, a record naming the ID of the state the
/// CPU set, which the program released and which was not the ID's last holder, as the step
/// cannot tell the GPU's write of that ID from the CPU's, where Metal runs the ID's holder
/// since for the GPU's. A state of the other kind holding the ID runs nothing, as on Metal,
/// unannounced. Announced by the execution alone, where the runtime records it: in `commit`
/// of its command buffer, on the committing thread, for one recorded from the CPU's
/// records; in the host step, on the scheduler's thread, for one recorded there (records
/// the GPU may write, a range a buffer holds, or a render pass whose pipelines were still
/// being made at the commit). Reading the commands (`IndirectCommandBuffer::commands`)
/// announces nothing.
/// executed where the runtime cannot run what Metal runs (`indirect_command_buffer.rs`,
/// `released_programs.rs`). A command holds the program of the state the CPU set on it,
/// and runs it while its record names the state's ID, whoever took the ID since, as
/// Metal's command the CPU encoded does; a record the GPU wrote runs the state that held
/// the ID as the GPU last could write the buffer's records, released since or not, as
/// Metal's GPU write resolves the ID to the state that took it last and its record runs
/// that state after: those are announced nowhere. Announced: a record the GPU wrote whose
/// ID's holder then was a state of the command's kind the program released, whose program
/// the buffer does not keep (released before any command buffer that may write the
/// buffer's records was encoded, or past the ID's last four holders), which Metal runs, so
/// the command runs nothing; and in a host step of records the GPU may write, a record
/// naming the ID of the state the CPU set, which the program released, where the GPU could
/// write the records while another state held the ID, as the step cannot tell the GPU's
/// write of that ID from the CPU's, where Metal runs the other state for the GPU's. A
/// state of the other kind holding the ID runs nothing, as on Metal, unannounced.
/// Announced by the execution alone, where the runtime records it: in `commit` of its
/// command buffer, on the committing thread, for one recorded from the CPU's records; in
/// the host step, on the scheduler's thread, for one recorded there (records the GPU may
/// write, a range a buffer holds, or a render pass whose pipelines were still being made
/// at the commit). Reading the commands (`IndirectCommandBuffer::commands`) announces
/// nothing.
ReleasedCommandState = "released-command-state", Precision,
"a command naming another ID than the state set on it runs nothing, where Metal runs \
the released state's program; one naming that state's ID runs its program, as \
Metal runs a command the CPU encoded, where for a record the GPU wrote Metal runs \
the ID's holder since (nothing, for a state of the other kind)";
"a command whose record the GPU wrote naming a state released before its buffer \
could be written runs nothing, where Metal runs that state's program; one naming the \
ID of the state set on it runs its program, as Metal runs a command the CPU encoded, \
where for a record the GPU wrote while another state held the ID Metal runs that \
state (nothing, for a state of the other kind)";
/// A pipeline stage's filtered sample of a texture slot bound to a two-plane YCbCr
/// texture does not take Metal's exact filter of the format: the stage records
/// `PrecisionNote::HalfSampleFilter` or `FloatSampleFilter` under the slot's bound format
@@ -1509,29 +1517,21 @@ degradations! {
/// to be: a pipeline state's made with `supportIndirectCommandBuffers`
/// (`ComputePipelineState::unique_identifier`, `RenderPipelineState::unique_identifier`,
/// an indirect command's state identifier other than 0), or an indirect command buffer's
/// made after its device opened a command encoder
/// (`IndirectCommandBuffer::unique_identifier`). Metal's is an address of its own
/// allocation: a state's follows how the process was started (an M3 Max's first such
/// compute state answered `0x1000000280` from a test binary, `0x100` more from a shell),
/// the states' functions and what the process made; a buffer's lies past the ranges
/// Metal's own encoders took. The runtime's keeps the relations a program can rely on
/// (a compute state's from one step into Metal's range, no workload's first). A buffer made
/// before any encoder answers Metal's number, quietly.
/// made after a command buffer of its device that encoded a render encoder was scheduled,
/// or after a resource state encoder opened (`IndirectCommandBuffer::unique_identifier`).
/// Metal's is an address of its own allocation: a state's follows how the process was
/// started (an M3 Max's first such compute state answered `0x1000000280` from a test
/// binary, `0x100` more from a shell), the states' functions and what the process made; a
/// buffer's lies past the ranges Metal's own encoders took, a render pass's run by its
/// targets' sizes and what the device drew before. The runtime's keeps the relations a
/// program can rely on (a compute state's from one step into Metal's range, no workload's
/// first). A buffer made before answers Metal's number, quietly, past the pieces Metal's
/// blit, compute and render encoders took.
UnmeasuredUniqueIdentifier = "unmeasured-unique-identifier", Precision,
"the identifier is unique and fixed for its holder's life, and a released one is \
reused as Metal reuses it, but it is not the number Metal answers there, which \
follows how the process was started, what it made and Metal's own encoders' \
allocations";
/// A program set a buffer at a slot past 31, or a threadgroup memory length at an index
/// past 30, of a command of an indirect command buffer whose descriptor counts more:
/// Metal's validation stops such a descriptor, and plain Metal keeps the value for its
/// private getters alone, as no function binds past index 30. The runtime's records hold
/// 32 buffers of each stage and 31 lengths a command, so the value is not kept: the
/// read-back answers a fresh command's value there.
IndirectValuePastRecord = "indirect-value-past-record", Precision,
"the command's read-back (Metal's private getters) answers a fresh command's value \
for a buffer slot past 31 or a threadgroup length past 30, where Metal answers the \
value set; no command runs otherwise";
/// A draw or dispatch that binds, at a texture slot, a texture whose format's numeric
/// class (float, signed or unsigned integer) is not the class the function declares there
/// and that its plan has no exact answer for (`PlanDiagnostic::CrossClassNeutral`): a
@@ -66,6 +66,7 @@ use super::memory_log::MemoryLog;
use super::mipmap_scratch::MipmapScratch;
use super::owned_kernel::OwnedKernels;
use super::recycle::{self, BufferMaking, Recycler};
use super::released_programs::Keepers;
use super::render_state::{depth_bias_command, DepthBiasCommand, DepthRanges};
use super::render_target::KeptRenderPasses;
use super::resource_ids::{ResourceIds, SamplerIdReads};
@@ -223,6 +224,9 @@ pub(super) struct DeviceShared {
pub(super) recycled_buffers: Mutex<Recycler<vk::Buffer, BufferMaking>>,
/// The resource IDs of textures and sampler states (`resource_ids.rs`).
pub(super) resource_ids: Arc<Mutex<ResourceIds>>,
/// The buffers whose records the GPU may write, which keep the programs of the pipeline
/// states the program releases (`released_programs.rs`).
pub(super) keepers: Keepers,
/// The `uniqueIdentifier`s the device allocates from 2^36 (`unique_identifier.rs`).
pub(super) identifiers: Arc<UniqueIdentifiers>,
/// How many holders hold a sampler ID now and the sampler pool's size (`resource_ids.rs`),
@@ -1631,6 +1635,7 @@ impl Device {
addresses: Mutex::new(AddressSpace::new()),
recycled_buffers: Mutex::new(Recycler::new(recycle::BUFFERS)),
resource_ids,
keepers: Keepers::default(),
identifiers: Arc::default(),
sampler_ids,
samplers: Mutex::default(),
@@ -1089,6 +1089,9 @@ impl Primer<'_> {
.descriptor_count(1)
.stage_flags(vk::ShaderStageFlags::COMPUTE)];
let info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings);
let mut support = vk::DescriptorSetLayoutSupport::default();
device.get_descriptor_set_layout_support(&info, &mut support);
self.made(Call::GetDescriptorSetLayoutSupport);
let set_layout = device
.create_descriptor_set_layout(&info, None)
.map_err(vulkan)?;
+18 -5
View File
@@ -54,6 +54,7 @@ use super::sparse::encoder::SparseUpdate;
use super::texture::decoded_twin::TwinWrite;
use super::texture::kept_image::KeptLease;
use super::tracker::{Barrier, EncoderUses, Reach, Summary, Use, UseRange};
use super::unique_identifier::ScheduledWork;
use super::used_resources::EncoderKind;
use super::Device;
use crate::device::functions::Vk;
@@ -123,12 +124,14 @@ pub(super) struct Segment {
impl Segment {
/// Whether the host step records it before its batch is submitted: the GPU may write what
/// its work reads, whether it could at the call or only since (`Deferred::gpu_written` is
/// for good), or `commit` left it for the pipelines it records; or `commit`'s recording on the
/// for good), or `commit` left it for the pipelines it records, or recorded it from records
/// the CPU wrote since (`Deferred::rewritten`); or `commit`'s recording on the
/// GPU alone must be made again ([`rerecords`](Self::rerecords)); or `commit` recorded it on
/// the GPU for good, and a route encoded since may write more than it decided on
/// (`Deferred::outgrown`).
/// the GPU for good, and a route encoded since may write more than it decided on, or gives an
/// execution's check something to see (`Deferred::outgrown`).
pub(super) fn needs_step(&self) -> bool {
(!self.stepped && (self.host || self.pipelines || self.work.gpu_written()))
(!self.stepped
&& (self.host || self.pipelines || self.work.gpu_written() || self.work.rewritten()))
|| self.rerecords()
|| self.work.outgrown()
}
@@ -385,6 +388,7 @@ impl EncoderCore {
pub(super) fn open(
command_buffer: &CommandBuffer,
call: &'static str,
kind: EncoderKind,
ordered: bool,
) -> Result<EncoderCore, Error> {
// The last render encoder's end, where its call left it to the device's lowering thread.
@@ -414,7 +418,7 @@ impl EncoderCore {
.device()
.shared()
.identifiers
.encoder_opened();
.encoder_opened(kind);
Ok(EncoderCore {
open: OpenGuard {
command_buffer: command_buffer.clone(),
@@ -1627,6 +1631,15 @@ impl EncoderCore {
) -> Result<(), Error> {
// A pass ended holds no command buffer (`render.rs`); this one ends here if one did.
self.release_pass()?;
// What Metal's identifier allocations follow as the command buffer is scheduled
// (`unique_identifier.rs`): a compute or blit encoder that encoded a command, and any
// render encoder.
let worked = self.recorded || !self.executions.is_empty() || !self.segments.is_empty();
let work = ScheduledWork {
dispatch: worked && matches!(kind, EncoderKind::Compute | EncoderKind::Blit),
render: kind == EncoderKind::Render,
};
self.open.command_buffer.note_scheduled_work(work);
let sharing = self.shadows.sharing_truth();
if sharing > 0 {
self.device().shared().counts.shadows_sharing_truth(sharing);
+10
View File
@@ -672,6 +672,16 @@ pub enum Problem {
/// The first ID past the kind's range.
limit: u64,
},
/// An indirect command buffer ID of `limit` (2^31) to 2^32 - 1 in a reservation
/// (`Device::reserve_resource_ids`): Metal's call never returns there, its pool spinning
/// (an M3 Max, macOS 27.0.1), so nothing is reserved. A caller matching Metal treats this as
/// that hang, not as an invalid argument.
ReservationHangs {
/// The first such ID in the call.
id: u64,
/// The first ID at which Metal's reservation hangs.
limit: u64,
},
/// [`IdPlacement::Outside`](crate::IdPlacement::Outside) for anything but a texture
/// `Device::new_texture` makes: a sampler state, a pipeline state, an indirect command
/// buffer, a view, or a heap's, a buffer's, a shared or a caller's texture. A runtime
@@ -417,6 +417,9 @@ calls! {
CreateSampler => c"vkCreateSampler",
CreateShaderModule => c"vkCreateShaderModule",
CreateDescriptorSetLayout => c"vkCreateDescriptorSetLayout",
// Asked before a heap's set layout past `maxPerSetDescriptors` is made
// (`pipeline::objects::layout_support`).
GetDescriptorSetLayoutSupport => c"vkGetDescriptorSetLayoutSupport",
CreatePipelineLayout => c"vkCreatePipelineLayout",
CreateComputePipelines => c"vkCreateComputePipelines",
// A render host step's ([`HOST_STEP`]): an executed render command's draw into a secondary
@@ -540,6 +543,7 @@ pub(crate) const HOST_STEP: &[Call] = &[
Call::CreateSampler,
Call::CreateShaderModule,
Call::CreateDescriptorSetLayout,
Call::GetDescriptorSetLayoutSupport,
Call::CreatePipelineLayout,
Call::CreateComputePipelines,
// A making's own pipeline cache, seeded from its record and read for its save
+35 -14
View File
@@ -5,8 +5,9 @@
//! - **Totality, decided at commit.** An execution a host step would record (`indirect_execute.rs`:
//! its buffer an encoder made resident for writing, or it lies inside a block of command
//! predication) runs here where every record it may hold is covered: its range is given as
//! such, not read from a buffer; no caller's check is given (`execute_commands_in_buffer_checked`
//! runs its check in the host step, before the commands reach the device); the buffer does not
//! such, not read from a buffer; a caller's check (`execute_commands_in_buffer_checked`) has
//! nothing to see (`Execute::check_sees`), else the host step runs it before the commands reach
//! the device; the buffer does not
//! inherit the encoder's buffers; every pipeline state its records may name (the encoder's where
//! the buffer inherits it, else every state made with `supportIndirectCommandBuffers` alive at
//! the commit) compiles as a flat device-replay variant (`ComputePipelineState::replay_variant`:
@@ -15,11 +16,17 @@
//! (`fetch_reach.rs`); no command of the range has a state the CPU set that the program released
//! since, whose program the command runs while its record names the ID
//! (`IndirectCommandBuffer::name_state`), and the variants of the states alive run the ID's
//! holder instead; and one of the two recordings below takes the variants. Each flat variant runs
//! holder instead; where the ID's holder as the GPU last could write the records is a state the
//! program released since, whose program the buffer keeps (`released_programs.rs`), the ID names
//! that program's variant, as Metal's record the GPU wrote runs it, unless the CPU set the state
//! that took the ID since on a command of the range (`IndirectCommandBuffer::gpu_states`); and
//! one of the two recordings below takes the variants. Each flat variant runs
//! every grid and threadgroup size of its state, so the records' contents cannot leave a command
//! uncovered. Otherwise the execution takes the host step (`indirect_execute.rs`, part 3a), which
//! the device announces once (`Degradation::HostReplayedIndirectCommands`). Nothing is decided at
//! run time.
//! run time, but for a checked execution whose check a route encoded since the commit gives
//! something to see before its batch is submitted: its host step records it then
//! (`Execute::outgrown`), from the states `commit` settled for it.
//! - **What runs.** One segment: the replay's preprocess (`bind::replay_preprocess_module`, an
//! owned kernel) over the range, reading the records where the GPU and the CPU left them and
//! writing each command's slot table, region record, and what the recording reads; a barrier;
@@ -252,9 +259,9 @@ pub(super) fn record(
command_buffer: &CommandBuffer,
execute: &Execute,
) -> Result<Option<(RecordedSegment, Option<Arc<Rerecord>>)>, Error> {
// A checked execution's host step runs the caller's check first; one inside a block of
// command predication runs here only from its preprocess's gate.
if execute.check.is_some() || (execute.predicated() && execute.preprocess_gate.is_none()) {
// A checked execution's host step runs the caller's check first, where it may see something;
// one inside a block of command predication runs here only from its preprocess's gate.
if execute.check_sees() || (execute.predicated() && execute.preprocess_gate.is_none()) {
return Ok(None);
}
let device = command_buffer.device();
@@ -342,7 +349,19 @@ fn total(
state.used_resources = residency.used_resources();
state.resident_ranges = live;
let shape = state.shape();
let states = execute.states(device);
// Each state with the ID its records name it by: the encoder's where the buffer inherits it;
// else the states alive, but where the records name the kept program of a state the program
// released since the GPU last could write them (`IndirectCommandBuffer::gpu_states`).
let states = match &execute.pipeline {
Some(pipeline) => vec![(pipeline.gpu_resource_id().0, pipeline.clone())],
None => match execute
.icb
.gpu_states(range.clone(), execute.states(device))
{
Some(states) => states,
None => return Ok(None),
},
};
// Where only the indirect dispatches could run it, none past their bounds, before a variant is
// compiled for it.
if device.shared().generated_commands.is_none()
@@ -351,8 +370,8 @@ fn total(
return Ok(None);
}
let mut prepared = Vec::with_capacity(states.len());
for pipeline in &states {
match prepare(pipeline, &state, &shape)? {
for (id, pipeline) in &states {
match prepare(pipeline, *id, &state, &shape)? {
Some(p) => prepared.push(p),
None => return Ok(None),
}
@@ -444,11 +463,13 @@ fn preprocess(
Ok(Some((pre, Form::Dispatches(templates))))
}
/// The flat replay variant of `pipeline` for `state` (of `shape`), instantiated for its
/// threadgroup size; `None` where it has none (`ComputePipelineState::replay_variant`), its
/// plan cannot run that size, or its kernel fetches `[[stage_in]]` attributes.
/// The flat replay variant of `pipeline`, which the records name by ID `id`, for `state` (of
/// `shape`), instantiated for its threadgroup size; `None` where it has none
/// (`ComputePipelineState::replay_variant`), its plan cannot run that size, or its kernel fetches
/// `[[stage_in]]` attributes.
fn prepare(
pipeline: &ComputePipelineState,
id: u64,
state: &BindState,
shape: &metal2vulkan::bind::BindShape,
) -> Result<Option<Prepared>, Error> {
@@ -473,7 +494,7 @@ fn prepare(
let Some(commands) = refusal(plan.instantiate_replay(state, threads))? else {
return Ok(None);
};
let token = NonZeroU64::new(pipeline.gpu_resource_id().0)
let token = NonZeroU64::new(id)
.ok_or_else(|| internal("an indirect command buffer's state without an ID"))?;
Ok(Some(Prepared {
variant,
File diff suppressed because it is too large. Load diff
@@ -1,12 +1,16 @@
//! Executing an indirect command buffer's compute commands in a compute encoder
//! (`executeCommandsInBuffer:withRange:`).
//!
//! - **When.** The CPU may write a command's record until the command buffer is committed, and
//! an execution runs the records as they stand then. So the encoder records nothing for it at
//! the call: it leaves an [`Execute`] as a segment ([`EncoderCore::defer`]), recorded into a
//! `VkCommandBuffer` of its own ([`Execute::record`]), behind a barrier from everything before
//! it and with one to everything after it, which goes between the encoder's two as its batch
//! is submitted.
//! - **When.** Metal's execution reads the records as it runs, so the CPU may write a command's
//! record after the call. So the encoder records nothing for it at the call: it leaves an
//! [`Execute`] as a segment ([`EncoderCore::defer`]), recorded into a `VkCommandBuffer` of its
//! own ([`Execute::record`]), behind a barrier from everything before it and with one to
//! everything after it, which goes between the encoder's two as its batch is submitted.
//! `commit` records it from the CPU's records as they stand then; where the CPU writes the
//! buffer's records again before the batch is ready to submit (an event wait holds it,
//! [`Execute::rewritten`]), a host step records it again from the records as they stand then,
//! waiting for no work on the GPU, and announcing nothing. A CPU write after the batch was
//! submitted races the GPU, as on Metal.
//! - **Records the GPU may write**. A buffer an encoder made resident for writing
//! (`IndirectCommandBuffer::gpu_written`, for good) is written by functions as they run, so its
//! records are known only once the work before the execution completed. Its segment starts a part
@@ -26,7 +30,9 @@
//! `supportIndirectCommandBuffers` that lived at the commit (`ComputePipelineState::
//! indirect_states`); an ID of none runs nothing, as Metal's undefined one may not. A record
//! naming the ID of the state the CPU set on its command runs that state's program, though the
//! program released the state since (`IndirectCommandBuffer::step_states`).
//! program released the state since (`IndirectCommandBuffer::step_states`); one the GPU wrote,
//! the state that held the ID as the GPU last could write the records, released since or not
//! (`released_programs.rs`).
//! - **Each command** runs through the plan path as the encoder's dispatch would
//! ([`record_dispatch`]): with its pipeline state, or the encoder's when the buffer inherits
//! it; its kernel buffers, or the encoder's bound ones when the buffer inherits them; its
@@ -61,6 +67,13 @@
//! - **Threadgroup lengths** are kept as set: one past the device's `max_threadgroup_memory_length`
//! runs clamped to it (ruling c); one that is not a multiple of 16 bytes runs rounded up to one,
//! as the plan rounds every length.
//! - **Checks.** An execution given a check (`execute_commands_in_buffer_checked`) calls it with
//! each command it will record, before it records any, where what the buffer's records may hold
//! leaves the check something to see ([`Execute::check_sees`]): `commit` with the CPU's records
//! it read, a host step with the records as the GPU and the CPU left them. An execution `commit`
//! recorded on the GPU alone (`gpu_execute.rs`), its check having nothing to see, whose check a
//! route encoded since gives something to see takes the host step before its batch is submitted
//! ([`Execute::outgrown`]).
//! - **Order.** Between commands, the segment orders as the encoder orders its dispatches (a
//! serial encoder's where their uses meet; a concurrent one's not at all), and a command with
//! its barrier set runs after every earlier command of the segment.
@@ -91,6 +104,7 @@ use metal2vulkan::bind::{Dispatch, ImageblockSize, ReplayFaults, StageInRegion};
use metal2vulkan::error::{BindError, Feature, Unsupported};
use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
/// The call an execution's refusals name.
@@ -142,16 +156,28 @@ pub(super) struct Execute {
/// (`predication.rs`): a host step records it, and nothing where the counter skips.
pub(super) gate: Option<HostGate>,
/// Inside a block of command predication, for a range given as such
/// ([`ExecutionRange::Fixed`]) that is not empty and no caller's check: the gate its preprocess
/// runs from on the GPU-alone path (`gpu_execute.rs`), of one invocation per command of the
/// range, which the step before it writes (`Predication::gates`).
/// ([`ExecutionRange::Fixed`]) that is not empty: the gate its preprocess runs from on the
/// GPU-alone path (`gpu_execute.rs`), of one invocation per command of the range, which the
/// step before it writes (`Predication::gates`).
pub(super) preprocess_gate: Option<Upload>,
/// The caller's check of the commands its host step records
/// (`execute_commands_in_buffer_checked`), and what it looks for: the step calls it before it
/// records them, and it keeps the execution off the GPU-alone path (`gpu_execute.rs`).
/// The caller's check of the commands it records (`execute_commands_in_buffer_checked`), and
/// what it looks for: `commit` or the host step calls it before it records them, where it may
/// see something ([`check_sees`](Self::check_sees)), and then it keeps the execution off the
/// GPU-alone path (`gpu_execute.rs`).
pub(super) check: Option<(Mutex<IndirectCommandCheck>, IndirectCommandCheckNeeds)>,
/// Where `commit` recorded it on the GPU alone with a check that had nothing to see then: the
/// states its host step lets the records name, settled then ([`settle`](Self::settle)), for a
/// route encoded since that gives the check something to see
/// ([`outgrown`](Self::outgrown)). The step takes them.
pub(super) unchecked: Mutex<Option<Vec<ComputePipelineState>>>,
/// Where `commit` recorded it from the CPU's records, the count of the CPU's writes of them
/// it read them after (`IndirectCommandBuffer::cpu_writes`); [`NOT_READ`] until then.
pub(super) read_at: AtomicU64,
}
/// [`Execute::read_at`] of an execution `commit` did not record from the CPU's records.
pub(super) const NOT_READ: u64 = u64::MAX;
/// The commands an execution runs.
pub(super) enum ExecutionRange {
/// `executeCommandsInBuffer:withRange:`'s, inside the buffer's size.
@@ -416,6 +442,53 @@ impl Execute {
self.range.indirect()
}
/// Whether its check, if any, may see something among its commands, as its buffer's records
/// may hold them now (`IndirectCommandCheckNeeds::sees`): commands under states that may
/// encode indirect commands, where it looks for them (the encoder's state where the buffer
/// inherits it, else those the records may name,
/// `IndirectCommandBuffer::may_name_encoding_states`). A compute buffer's records hold no
/// draw: a command of one runs no draw of points.
pub(super) fn check_sees(&self) -> bool {
let Some((_, needs)) = &self.check else {
return false;
};
let needs = IndirectCommandCheckNeeds {
point_draws: false,
..*needs
};
let encodes = || match &self.pipeline {
Some(pipeline) => pipeline.can_encode_indirect_commands(),
None => self.icb.may_name_encoding_states(),
};
let (points, encodes) = needs.sees(self.icb.command_writes(), encodes);
points || encodes
}
/// Whether `commit` recorded it on the GPU alone with a check that had nothing to see, and a
/// route encoded since gives the check something ([`check_sees`](Self::check_sees)): its host
/// step records it instead, before its batch is submitted, calling the check.
pub(super) fn outgrown(&self) -> bool {
let unchecked = lock(&self.unchecked).is_some();
unchecked && self.check_sees()
}
/// Where it is [`outgrown`](Self::outgrown), the states its host step lets the records name,
/// taken: the step records it for good.
pub(super) fn take_outgrown(&self) -> Option<Vec<ComputePipelineState>> {
match self.outgrown() {
true => lock(&self.unchecked).take(),
false => None,
}
}
/// Whether `commit` recorded it from the CPU's records and the CPU wrote the buffer's records
/// since ([`read_at`](Self::read_at)): its host step records it again, from the records as
/// they stand then, before its batch is submitted.
pub(super) fn rewritten(&self) -> bool {
let read_at = self.read_at.load(Ordering::Acquire);
read_at != NOT_READ && self.icb.cpu_writes() != read_at
}
/// Whether it lies inside a block of command predication: a host step records it, once the
/// steps before it left their counter (`predication.rs`), unless it runs on the GPU alone from
/// its preprocess's gate (`gpu_execute.rs`).
@@ -448,13 +521,23 @@ impl Execute {
// The execution announces the commands it runs otherwise than Metal's may, as it records
// them.
let Some(states) = states else {
let start = range.start;
// Counted before the records are read: a write meanwhile records it again.
self.read_at.store(self.icb.cpu_writes(), Ordering::Release);
let (commands, released) = self.icb.records(range, Reader::Commit)?;
self.icb.degrade_released(&released);
// The caller's check sees each command `commit` will record, before it records any,
// where it may see something.
if let Some((check, _)) = self.check.as_ref().filter(|_| self.check_sees()) {
let read = commands.iter().map(|(record, _)| record);
self.icb.check_read(check, start, read);
}
return Ok((commands.into_iter().map(Some).collect(), faults));
};
let written = self.icb.written_records(range.clone())?;
// The caller's check sees each command the step will record, before it records any.
if let Some((check, _)) = &self.check {
// The caller's check sees each command the step will record, before it records any,
// where it may see something.
if let Some((check, _)) = self.check.as_ref().filter(|_| self.check_sees()) {
self.icb
.check_recorded(check, range.start, &written.records);
}
@@ -560,17 +643,20 @@ pub(super) fn degrade_nil_offset(device: &Device, binding: &BufferBinding, index
/// Announce, once per device, that an execution is replayed on the host (the module's records
/// the GPU may write, and ranges read from a buffer).
pub(super) fn degrade_host_replay(device: &Device, execute: &Execute) {
let why = if execute.icb.gpu_written() {
"an encoder made it resident for writing, so the GPU may write the records an execution \
runs"
} else if execute.indirect() {
"an execution reads its range from a buffer \
(executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:), which the GPU may write"
} else if execute.predicated() {
"an execution inside a block of command predication, whose condition is GPU memory"
} else {
// Recorded again for the CPU's writes since the commit (`Execute::rewritten`), waiting
// for no work on the GPU.
return;
};
device.degrade(Degradation::HostReplayedIndirectCommands, || {
let why = if execute.icb.gpu_written() {
"an encoder made it resident for writing, so the GPU may write the records an \
execution runs"
} else if !execute.indirect() {
"an execution inside a block of command predication, whose condition is GPU memory"
} else {
"an execution reads its range from a buffer \
(executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:), which the GPU may \
write"
};
(
format!(
"an indirect command buffer of {} commands",
+1
View File
@@ -167,6 +167,7 @@ mod rebind;
mod recorder;
mod recycle;
mod release;
mod released_programs;
mod render;
mod render_pass;
mod render_state;
@@ -101,6 +101,7 @@ use super::Device;
use crate::argument_table::AtBindViews;
use crate::binary_archive::Used;
use crate::degradation::{CompiledPipeline, Occurrence};
use crate::released_programs::KeptProgram;
use crate::residency::handle_stages;
use crate::resource_ids::{
function_name, number, pipeline_placement, Holder, IdHold, IdPlacement, IdSpace, Numbered,
@@ -242,6 +243,24 @@ impl std::ops::Deref for StateShared {
}
}
/// The program's release of a state made with `supportIndirectCommandBuffers`: each buffer whose
/// records the GPU may write keeps what it runs (`released_programs.rs`).
impl Drop for StateShared {
fn drop(&mut self) {
let Some(id) = self.id.as_ref().filter(|id| id.id().0 != 0) else {
return;
};
let program = &self.program;
program
.device
.shared()
.keepers
.released(id.id().0, id.serial(), || {
KeptProgram::Compute(ComputeProgram(Arc::clone(program)))
});
}
}
/// What a compute state runs and answers, but its ID.
pub(super) struct Program {
device: Device,
@@ -690,7 +709,11 @@ impl ComputePipelineState {
// command's record can name (`indirect_states`).
let id = indirect.then(|| {
let id = IdHold::take(&device.shared().resource_ids, IdSpace::Pipeline, placement);
id.hold(Holder::Pipeline(Weak::clone(state)));
id.hold_state(
Holder::Pipeline(Weak::clone(state)),
StateKind::Compute,
identifier.value(),
);
id
});
let program = Program {
@@ -55,6 +55,7 @@ use crate::color_reformat::Routing;
use crate::degradation::{BoundFormats, CompiledPipeline, Degradation, Occurrence};
use crate::device::{device_error, lock};
use crate::error::{internal, invalid, ArchivedPipeline, Error, Problem, RuntimeGap};
use crate::released_programs::KeptProgram;
use crate::render_pass::MAX_COLOR_ATTACHMENTS;
use crate::render_target::RenderPassObject;
use crate::residency::{every_render_stage, handle_stages};
@@ -154,6 +155,24 @@ impl std::ops::Deref for StateShared {
}
}
/// The program's release of a state made with `supportIndirectCommandBuffers`: each buffer whose
/// records the GPU may write keeps what it runs (`released_programs.rs`).
impl Drop for StateShared {
fn drop(&mut self) {
let Some(id) = self.id.as_ref().filter(|id| id.id().0 != 0) else {
return;
};
let program = &self.program;
program
.device
.shared()
.keepers
.released(id.id().0, id.serial(), || {
KeptProgram::Render(RenderProgram(Arc::clone(program)))
});
}
}
/// What a drawing state runs and answers, but its ID.
pub(crate) struct Program {
device: Device,
@@ -1647,7 +1666,11 @@ impl GraphicsState {
// command's record can name (`indirect_states`).
let id = descriptor.support_indirect_command_buffers().then(|| {
let id = IdHold::take(&device.shared().resource_ids, IdSpace::Pipeline, placement);
id.hold(Holder::RenderPipeline(Weak::clone(state)));
id.hold_state(
Holder::RenderPipeline(Weak::clone(state)),
StateKind::Render,
identifier.value(),
);
id
});
let program = Program {
@@ -0,0 +1,141 @@
//! The programs of released pipeline states that records the GPU wrote still run.
//!
//! - **What Metal runs** (an M3 Max on macOS 27, plain Metal, a kernel encoding a compute command
//! through an argument buffer that names a state made with `supportIndirectCommandBuffers`). A
//! GPU write of a pipeline state ID resolves the ID as it runs, to the state that took it last,
//! released or not: a state released before the write, its ID taken by no state since, runs.
//! The record runs that state's program, and its `getPipelineStateUniqueIdentifier` answers
//! that state's, from then on: after the program releases the state, after another state takes
//! the ID, and after four rounds of 48 states took the ID and gave it back. A write of an ID
//! another state took before the write runs that state.
//! - **The runtime.** A record holds the ID alone, and names the state that held the ID as the
//! GPU last could write the buffer's records (`IndirectCommandBuffer::window_holder`, which the
//! getter answers too). A buffer the GPU may write keeps, from its first such write
//! (`IndirectCommandBuffer::gpu_write`), the program of each state made with
//! `supportIndirectCommandBuffers` the program releases since ([`Keepers::released`]), and a
//! blit's copy of commands keeps in its destination the source's kept programs and those of
//! the released states the CPU set on the commands it copies: a record naming the ID runs that
//! program where the state held the ID then. Nothing is kept for a buffer the GPU never writes,
//! so a program that writes no records on the GPU keeps nothing.
//! - **Bounded.** A buffer keeps an ID's last [`PIPELINE_HOLDERS`] released programs, as the
//! device keeps its last holders: a fifth drops the oldest, whose records then run nothing,
//! announced (below). So what the buffers keep is at most four programs per pipeline state ID
//! the program used, each one `Arc` the buffers share: with plain allocation, which hands out
//! the lowest free ID as Metal does, four times the peak count of live states made with
//! `supportIndirectCommandBuffers`, however long the program makes and releases them; each ID a
//! placement (`PipelineOptions::placement`) names besides counts four more.
//! - **Not kept** (`Degradation::ReleasedCommandState`, the command running nothing): the program
//! of a state released before any buffer whose records the GPU writes naming its ID could be
//! written, which Metal runs where no state took the ID since; and one past an ID's last
//! [`PIPELINE_HOLDERS`] holders.
use super::device::lock;
use super::pipeline::{ComputePipelineState, ComputeProgram, RenderPipelineState, RenderProgram};
use super::resource_ids::PIPELINE_HOLDERS;
use std::collections::{BTreeMap, VecDeque};
use std::sync::{Arc, Mutex, Weak};
/// A released pipeline state's program.
#[derive(Clone)]
pub(super) enum KeptProgram {
Compute(ComputeProgram),
Render(RenderProgram),
}
impl KeptProgram {
/// A compute program, as a state of no ID (`ComputeProgram::state`).
pub(super) fn compute(&self) -> Option<ComputePipelineState> {
match self {
KeptProgram::Compute(program) => Some(program.state()),
KeptProgram::Render(_) => None,
}
}
/// A render program, as a state of no ID (`RenderProgram::state`).
pub(super) fn render(&self) -> Option<RenderPipelineState> {
match self {
KeptProgram::Render(program) => Some(program.state()),
KeptProgram::Compute(_) => None,
}
}
}
/// The programs a buffer keeps: by pipeline state ID, each with its state's hold serial
/// (`IdHold::serial`), the last kept last, at most [`PIPELINE_HOLDERS`] of an ID.
#[derive(Clone, Default)]
pub(super) struct KeptPrograms(BTreeMap<u64, VecDeque<(u64, KeptProgram)>>);
impl KeptPrograms {
/// Keep `program`, of the state whose hold of ID `id` had `serial`.
pub(super) fn keep(&mut self, id: u64, serial: u64, program: KeptProgram) {
let kept = self.0.entry(id).or_default();
if kept.iter().any(|&(held, _)| held == serial) {
return;
}
if kept.len() == PIPELINE_HOLDERS {
kept.pop_front();
}
kept.push_back((serial, program));
}
/// Keep what `other` keeps.
pub(super) fn keep_all(&mut self, other: KeptPrograms) {
for (id, kept) in other.0 {
for (serial, program) in kept {
self.keep(id, serial, program);
}
}
}
/// The program of the state whose hold of ID `id` had `serial`, where kept.
pub(super) fn program(&self, id: u64, serial: u64) -> Option<&KeptProgram> {
self.0
.get(&id)?
.iter()
.find(|&&(held, _)| held == serial)
.map(|(_, program)| program)
}
/// The IDs it keeps programs of.
pub(super) fn ids(&self) -> impl Iterator<Item = u64> + '_ {
self.0.keys().copied()
}
/// How many programs it keeps.
#[cfg(test)]
pub(super) fn count(&self) -> usize {
self.0.values().map(VecDeque::len).sum()
}
}
/// The buffers of a device whose records the GPU may write, each by what it keeps, weakly: the
/// buffer holds its programs, so the device holds no program (a program holds its device).
#[derive(Default)]
pub(super) struct Keepers(Mutex<Vec<Weak<Mutex<KeptPrograms>>>>);
impl Keepers {
/// From now on keep, in `kept`, the programs of the states the program releases.
pub(super) fn add(&self, kept: &Arc<Mutex<KeptPrograms>>) {
let mut keepers = lock(&self.0);
keepers.retain(|keeper| keeper.strong_count() > 0);
keepers.push(Arc::downgrade(kept));
}
/// The program released a state made with `supportIndirectCommandBuffers` whose hold of ID
/// `id` had `serial`, and which runs `program`: each buffer whose records the GPU may write
/// keeps it. Nothing, and `program` is not called, where there is none.
pub(super) fn released(&self, id: u64, serial: u64, program: impl FnOnce() -> KeptProgram) {
let keepers: Vec<Arc<Mutex<KeptPrograms>>> = {
let mut keepers = lock(&self.0);
keepers.retain(|keeper| keeper.strong_count() > 0);
keepers.iter().filter_map(Weak::upgrade).collect()
};
if keepers.is_empty() {
return;
}
let program = program();
for keeper in keepers {
lock(&keeper).keep(id, serial, program.clone());
}
}
}
+1 -1
View File
@@ -1660,7 +1660,7 @@ impl CommandBuffer {
};
// A refusal past here leaves the secondary command buffer unused, freed with the pool.
let mut core = match again {
None => EncoderCore::open(self, CALL, false)?,
None => EncoderCore::open(self, CALL, EncoderKind::Render, false)?,
Some(_) => EncoderCore::replaying(self, false)?,
};
// The whole pass, every group's colors.
@@ -75,6 +75,7 @@ impl RenderLowering {
if let ResourceRef::IndirectCommandBuffer(icb) = resource {
if usage.contains(ResourceUsage::WRITE) {
self.writers.made_writable(icb.written());
self.core.retain(icb.gpu_write());
}
}
}
@@ -2,9 +2,13 @@
//! (`executeCommandsInBuffer:withRange:`).
//!
//! - **When.** As a compute encoder's (`indirect_execute.rs`), an execution runs the records as
//! they stand when the command buffer is committed: Metal's sees CPU writes made after the
//! call and before commit, and the GPU's writes before it where an encoder made the buffer
//! resident for writing. So the call records nothing for the commands:
//! they stand when its batch is submitted: Metal's reads them as it runs, so it sees CPU writes
//! made after the call, and the GPU's writes before it where an encoder made the buffer
//! resident for writing. `commit` records the CPU's records as they stand then; where the CPU
//! writes them again before the pass's batch is ready to submit (an event wait holds it), the
//! host step records the pass again from the records as they stand then, waiting for no work
//! on the GPU and announcing nothing. A CPU write after the batch was submitted races the GPU,
//! as on Metal. So the call records nothing for the commands:
//! the instance it is encoded in ends its secondary command buffer there and goes on in a new
//! one, the execution's own secondary standing between the two ([`Piece`](super::Piece)).
//! A secondary command buffer must be recorded before a primary executes it, so a pass with an
@@ -319,6 +323,7 @@ use metal2vulkan::pipeline::{CommandWrites, VertexStride};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Range;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
mod ahead;
@@ -411,9 +416,9 @@ impl RenderLowering {
range_buffer: &Buffer,
offset: u64,
check: IndirectCommandCheck,
needs: IndirectCommandCheckNeeds,
) -> Result<(), Error> {
let check = (check, IndirectCommandCheckNeeds::ALL);
self.execute_indirect_range(icb, range_buffer, offset, Some(check))
self.execute_indirect_range(icb, range_buffer, offset, Some((check, needs)))
}
/// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect), with
@@ -729,6 +734,7 @@ impl RenderLowering {
.as_ref()
.map_or(IndirectCommandCheckNeeds::ALL, |(_, needs)| *needs),
check: check.map(|(check, _)| Mutex::new(check)),
read_at: AtomicU64::new(indirect_execute::NOT_READ),
});
// Its commands may name any pipeline state, reading handles in any stage.
self.command_encoded(every_render_stage());
@@ -738,9 +744,10 @@ impl RenderLowering {
impl RenderCommandEncoder {
/// `executeCommandsInBuffer:withRange:`: run render commands `range` of `icb` here, as their
/// records stand when the command buffer is committed, or, where an encoder made `icb`
/// resident for writing, once the work before them completed (a host step the device
/// announces once, `Degradation::HostReplayedIndirectCommands`). Each draws as this
/// records stand when the command buffer's batch that executes them is submitted (the commit
/// reads them, and the batch's submission again where the CPU wrote them since), or, where an
/// encoder made `icb` resident for writing, once the work before them completed (a host step
/// the device announces once, `Degradation::HostReplayedIndirectCommands`). Each draws as this
/// encoder's `draw_primitives`, `draw_indexed_primitives` or `draw_patches` would, with the
/// encoder's state as it is now, and its own pipeline state and buffers, or the encoder's
/// where `icb` inherits them (the module docs).
@@ -772,16 +779,16 @@ impl RenderCommandEncoder {
}
/// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) with a check of the
/// commands its host step runs (a runtime extension; Metal has none), which looks for `needs`:
/// where a host step records the pass from the records as the GPU and the CPU left them (an
/// encoder made `icb` resident for writing, `IndirectCommandBuffer::gpu_written`), the step
/// first calls `check` with each command of the range it will record, in order, before it
/// records any of them ([`IndirectCommandCheck`]). An execution `commit` records from the CPU's
/// records never calls it; nor does one that runs on the GPU alone (`render/executions/gpu.rs`),
/// which it may only where what `icb`'s records may hold, at the commit and again as the
/// pass's batch is ready to submit, rules out every kind `needs` names
/// ([`IndirectCommandCheckNeeds`], [`IndirectCommandCheckNeeds::ALL`] included). Refused as
/// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) refuses.
/// commands it runs (a runtime extension; Metal has none), which looks for `needs`: where the
/// commit records the pass from the CPU's records, or a host step from the records as the GPU
/// and the CPU left them (an encoder made `icb` resident for writing,
/// `IndirectCommandBuffer::gpu_written`), it first calls `check` with each command of the range
/// it will record, in order, before it records any of them ([`IndirectCommandCheck`]). Neither
/// calls it where what `icb`'s records may hold rules out every kind `needs` names
/// ([`IndirectCommandCheckNeeds`], [`IndirectCommandCheckNeeds::ALL`] included); nor does an
/// execution that runs on the GPU alone (`render/executions/gpu.rs`), which it may only where
/// they rule them out at the commit and again as the pass's batch is ready to submit. Refused
/// as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) refuses.
pub fn execute_commands_in_buffer_checked(
&mut self,
icb: &IndirectCommandBuffer,
@@ -840,11 +847,12 @@ impl RenderCommandEncoder {
}
/// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect) with a
/// check of the commands its host step runs, which always records the pass: the step first
/// calls `check` with each command of the range it read that it will record, in order, before
/// it records any of them, as
/// check of the commands its host step runs, which always records the pass, looking for
/// `needs`: the step first calls `check` with each command of the range it read that it will
/// record, in order, before it records any of them, as
/// [`execute_commands_in_buffer_checked`](Self::execute_commands_in_buffer_checked)'s does
/// ([`IndirectCommandCheck`]). Refused as
/// ([`IndirectCommandCheck`]), unless what `icb`'s records may hold then rules out every kind
/// `needs` names ([`IndirectCommandCheckNeeds`]). Refused as
/// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect) refuses.
pub fn execute_commands_in_buffer_indirect_checked(
&mut self,
@@ -852,6 +860,7 @@ impl RenderCommandEncoder {
range_buffer: &Buffer,
offset: u64,
check: IndirectCommandCheck,
needs: IndirectCommandCheckNeeds,
) -> Result<(), Error> {
match self.lowers_at_call() {
true => self.at_call(|lowering| {
@@ -860,11 +869,12 @@ impl RenderCommandEncoder {
range_buffer,
offset,
check,
needs,
)
}),
false => self.defer(|_| {
let check = SharedCheck::new(check);
let call = (icb.clone(), range_buffer.clone(), offset, check);
let call = (icb.clone(), range_buffer.clone(), offset, check, needs);
RenderCall::ExecuteIndirectChecked(Box::new(call))
}),
}
@@ -920,6 +930,10 @@ pub(crate) struct RenderExecution {
/// What the check looks for, which decides whether the execution may run on the GPU alone
/// (`gpu.rs`): every kind where it has no check.
needs: IndirectCommandCheckNeeds,
/// Where `commit` recorded it from the CPU's records, the count of the CPU's writes of them it
/// read them after (`IndirectCommandBuffer::cpu_writes`); `indirect_execute::NOT_READ` until
/// then ([`rewritten`](Self::rewritten)).
read_at: AtomicU64,
}
/// The encoder's state an execution's draws take: as the call found it, its tables only where
@@ -2402,6 +2416,37 @@ impl RenderExecution {
core
}
/// What its check, if any, may see among commands whose records may hold `written`
/// (`IndirectCommandCheckNeeds::sees`): draws of points, and commands under states that may
/// encode indirect commands (the encoder's state where the buffer inherits it, else those the
/// records may name, `IndirectCommandBuffer::may_name_encoding_states`), each where it looks
/// for them; neither without a check.
fn check_sees(&self, written: CommandWrites) -> (bool, bool) {
if self.check.is_none() {
return (false, false);
}
let encodes = || match &self.pipeline {
Some(pipeline) => pipeline.can_encode_indirect_commands(),
None => self.icb.may_name_encoding_states(),
};
self.needs.sees(written, encodes)
}
/// Whether `commit` recorded it from the CPU's records and the CPU wrote the buffer's records
/// since ([`read_at`](Self::read_at)): the pass's host step records it again, from the
/// records as they stand then, before its batch is submitted.
fn rewritten(&self) -> bool {
let read_at = self.read_at.load(Ordering::Acquire);
read_at != indirect_execute::NOT_READ && self.icb.cpu_writes() != read_at
}
/// Whether its check may see something among its commands, as its buffer's records may hold
/// them now ([`check_sees`](Self::check_sees)).
fn check_sees_now(&self) -> bool {
let (points, encodes) = self.check_sees(self.icb.command_writes());
points || encodes
}
/// The commands of the range, in order, `None` where a record runs nothing for a fault, and
/// the faults: the CPU's records, or for the host step the records as the GPU and the CPU
/// left them, each naming its state among the live ones made with
@@ -2420,16 +2465,26 @@ impl RenderExecution {
}
// The execution announces the commands it runs otherwise than Metal's may, as it
// records them.
let start = range.start;
// Counted before the records are read: a write meanwhile records it again.
self.read_at.store(self.icb.cpu_writes(), Ordering::Release);
let (commands, released) = self.icb.render_records(range, Reader::Commit)?;
self.icb.degrade_released(&released);
// The caller's check sees each command `commit` will record, before it records any,
// where it may see something.
if let Some(check) = self.check.as_ref().filter(|_| self.check_sees_now()) {
let read = commands.iter().map(|(record, _)| record);
self.icb.check_read(check, start, read);
}
return Ok((
commands.into_iter().map(Some).collect(),
ReplayFaults::default(),
));
}
let written = self.icb.written_records(range.clone())?;
// The caller's check sees each command the step will record, before it records any.
if let Some(check) = &self.check {
// The caller's check sees each command the step will record, before it records any,
// where it may see something.
if let Some(check) = self.check.as_ref().filter(|_| self.check_sees_now()) {
self.icb
.check_recorded(check, range.start, &written.records);
}
@@ -2797,12 +2852,24 @@ impl DeferredPass {
/// Whether a route encoded since `commit` recorded the pass with executions in their GPU form
/// may write more into one of their buffers than the decision found (`gpu.rs`): a route that
/// runs before the pass, which a command buffer enqueued before its own and committed after it
/// may hold, may have written commands the GPU form does not run. Until its batch is
/// submitted, the host step records the pass instead (`Deferred::outgrown`).
/// may hold, may have written commands the GPU form does not run; or the CPU wrote the records
/// of one of its other executions, which `commit` read ([`rewritten`](Self::rewritten)). Until
/// its batch is submitted, the host step records the pass instead (`Deferred::outgrown`).
pub(crate) fn outgrown(&self) -> bool {
lock(&self.on_gpu)
.iter()
.any(|(written, decided)| written.writes() != *decided)
let on_gpu = lock(&self.on_gpu);
!on_gpu.is_empty()
&& (on_gpu
.iter()
.any(|(written, decided)| written.writes() != *decided)
|| self.rewritten())
}
/// Whether `commit` recorded one of its executions from the CPU's records, which the CPU
/// wrote since (`RenderExecution::rewritten`): its host step records the pass again, from the
/// records as they stand then, before its batch is submitted (`Deferred::rewritten`; where
/// `commit` recorded the pass on the GPU for good, [`outgrown`](Self::outgrown)).
pub(crate) fn rewritten(&self) -> bool {
self.executions.iter().any(RenderExecution::rewritten)
}
/// [`record`](Self::record), each execution with a GPU form among `forms` (by index) in it.
@@ -63,7 +63,7 @@
//! commit: a CPU setter, or a route encoded since. Where it grew by the time the pass's batch is
//! otherwise ready to submit (`DeferredPass::outgrown`, `Segment::needs_step`), the host step
//! records the pass instead, as for any pass whose records the GPU may write, and calls the
//! caller's check. Every writer the runtime orders before the pass was committed by then: a
//! caller's check where it then has something to see. Every writer the runtime orders before the pass was committed by then: a
//! queue's batches go in commit order, and a batch that waits for an event is ready only once a
//! submitted signal reaches it. A CPU write after that races the GPU, as on Metal.
//! - **Faults.** A record the host's decode refuses draws nothing, and the execution report
@@ -392,22 +392,12 @@ impl RenderExecution {
/// Whether the caller's check, if any, has nothing to see among commands whose records may
/// hold `written`, under the encoder's state, which the buffer inherits: neither draws of
/// points (a primitive type the writes do not state counts as one) nor a state that may encode
/// indirect commands where it looks for them (`IndirectCommandCheckNeeds`); else which of
/// indirect commands where it looks for them (`RenderExecution::check_sees`); else which of
/// those it may see.
fn check_has_nothing_to_see(&self, written: CommandWrites) -> Result<(), HostStepCause> {
let needs = self.needs;
let points = written.may_draw_primitive_type(PrimitiveType::Point.as_raw());
let encodes = self
.pipeline
.as_ref()
.is_none_or(|pipeline| pipeline.can_encode_indirect_commands());
let (points, encodes) = (
needs.point_draws && points,
needs.encoding_states && encodes,
);
match self.check.is_some() && (points || encodes) {
true => Err(HostStepCause::Check { points, encodes }),
false => Ok(()),
match self.check_sees(written) {
(false, false) => Ok(()),
(points, encodes) => Err(HostStepCause::Check { points, encodes }),
}
}
@@ -206,7 +206,15 @@ pub(crate) enum RenderCall {
)>,
),
/// `execute_commands_in_buffer_indirect_checked`, deferred, likewise.
ExecuteIndirectChecked(Box<(IndirectCommandBuffer, Buffer, u64, SharedCheck)>),
ExecuteIndirectChecked(
Box<(
IndirectCommandBuffer,
Buffer,
u64,
SharedCheck,
IndirectCommandCheckNeeds,
)>,
),
ColorResolveTarget(Option<Box<ResolveTarget>>, u32),
DepthResolveTarget(Option<Box<ResolveTarget>>),
StencilResolveTarget(Option<Box<ResolveTarget>>),
@@ -915,8 +923,14 @@ pub(super) fn render(
encoder.execute_commands_in_buffer_checked(icb, range.clone(), check.boxed(), *needs)
}
C::ExecuteIndirectChecked(call) => {
let (icb, buffer, offset, check) = &**call;
encoder.execute_commands_in_buffer_indirect_checked(icb, buffer, *offset, check.boxed())
let (icb, buffer, offset, check, needs) = &**call;
encoder.execute_commands_in_buffer_indirect_checked(
icb,
buffer,
*offset,
check.boxed(),
*needs,
)
}
C::ColorResolveTarget(target, index) => {
encoder.set_color_resolve_target(target.as_deref().cloned(), *index)
+190 -44
View File
@@ -92,10 +92,19 @@
//! textures, sampler states, pipeline states and indirect command buffers, Metal's types 0, 1,
//! 4 and 5) keep IDs from plain allocation for good, whether a resource placed at one lives or
//! not. Only a space's first call with an ID counts: one once the space handed out an ID,
//! placed or plain, or took a reservation is ignored, with a diagnostic line, as Metal's is
//! (its pool logs "reserve() must be called before any allocation takes place" for both). A
//! call of no ID, or of 0 alone, changes nothing, and 0 beside other IDs reserves nothing:
//! Metal's pool, given 0, later hands IDs out twice (1 to 4 again after 9), a defect not copied.
//! placed or plain, or took a reservation is ignored whatever it holds, with a diagnostic
//! line, as Metal's is (its pool logs "reserve() must be called before any allocation takes
//! place" for both; an M3 Max, macOS 27.0.1, so ignored IDs of 2^31, 2^32 - 1, 2^32 + 5 and
//! 0 alone of indirect command buffers, and 2^28 + 5 of textures, each refused or dropped in
//! a first call). A
//! call of no ID changes nothing, and 0 beside other IDs is no ID (0 and 5 reserve 5). A call
//! of 0 alone reserves nothing, but leaves the pool made, as a texture pool is by the device's
//! first queue ([`Pool::make`]): a later reservation keeps the pool's first range beside the
//! ranges it leaves, and Metal hands out that range's IDs twice, as the runtime does (an M3
//! Max, macOS 27.0.1, indirect command buffers: 0 then 10 gives 1 to 9, 11 to 31, then 1 to
//! 15; 0 then 20, 21 to 31, 1 to 19, then 1 to 10; 0 then 40, 41 to 63, 1 to 31, then 1 to 16;
//! 0 then 31, 1 to 30, then 1 to 50; 0 then 32, 1 to 31, then 33 on, the first range equal to
//! the one left; textures, 0 then 10, 11 to 15, 1 to 9, then 1 to 31).
//! A call holding an ID of 2^32 or more is dropped whole, silently, and a later call is the
//! reservation (2^32 to 2^63, alone or beside 10, for textures, sampler states and indirect
//! command buffers).
@@ -107,12 +116,17 @@
//! 20001 next), and the runtime's. A texture or sampler state ID of [`RESERVED_POOL_LIMIT`]
//! (2^28) or more, whose pool would hold 2^29 IDs, ended Metal's process (2^27 + 5 was taken,
//! 2^28 + 5 to 2^32 - 1 ended it, at the reservation or the first allocation after it): refused
//! `Invalid`. So is an indirect command buffer ID of [`RECORDS_RESERVED_LIMIT`] (2^30) or more
//! (2^30 - 1 was taken, 2^30 + 5 and up ended the process), and a placement of one at
//! [`RECORDS_PLACEMENT_LIMIT`] (16384) or more, past Metal's table of them. A reserved indirect
//! command buffer ID needs no records, but a buffer whose own ID is 2^23 or more has no records
//! address: it is refused `OutOfMemory` as it is made, as a buffer is once every ID below it is
//! held. Pipeline state IDs, measured to 1,000,000, are refused nowhere. The texture table
//! `Invalid`. An indirect command buffer ID is reserved to 2^31 - 1, and plain IDs are handed
//! out past it, each buffer made and run (an M3 Max, macOS 27.0.1: 2^23 + 5, 2^30 + 5 and
//! 2^31 - 2 gave 2^23 + 6, 2^30 + 6 and 2^31 - 1 next); one of [`RECORDS_RESERVED_LIMIT`] (2^31)
//! to 2^32 - 1 never returned there (Metal's pool spins), and is refused `Invalid`
//! (`Problem::ReservationHangs`, which says so). An M4's
//! Metal ended the process at the first allocation after a reservation of 2^30 + 5 to 2^31 - 1,
//! which the M3 Max, of the same GPU family (Apple9), made and ran: the runtime follows the M3
//! Max. A placement of one at [`RECORDS_PLACEMENT_LIMIT`] (16384) or more, past Metal's table
//! of them, is refused `Invalid`. A buffer's records start at its ID's records address, at any
//! length (Metal made and ran 2^22 commands at 2^26 + 6 and 2^23 + 6); a buffer is refused
//! `OutOfMemory` only once every ID below 2^31 is held. Pipeline state IDs, measured to 1,000,000, are refused nowhere. The texture table
//! reaches every ID a heap array can (`heap_sets.rs`), so a texture Metal numbers past its
//! placement limit is reached as any other. A texture's ID indexes every set-1 array its usage
//! can bind it through (sampled where it reads, storage where it writes), so an ID past the least
@@ -128,8 +142,9 @@
//! answers it as its own. Once the holder is gone the slot reads the neutral resource, even
//! while an earlier resource with the ID lives (Metal's kernel read the gone holder's texels
//! there, probe 2). A pipeline state ID keeps the kind of its gone holder until a state takes
//! it again (`ResourceIds::released_pipeline`): a record the GPU wrote naming it runs the
//! released state's program on Metal, which the runtime no longer has.
//! it again (`ResourceIds::released_pipeline`), and the device its last holders, released or
//! not (`ResourceIds::pipeline_holder_by`): a record the GPU wrote naming the ID runs the state
//! that held it as the GPU wrote it on Metal, released since or not (`released_programs.rs`).
//! - **When an ID is resolved.** A command reaches texture ID `X` whatever its encoder named,
//! as Metal's did (the M4 probe: a texture no encoder named, or one a later encoder
//! made resident, was read through its ID in an argument buffer): the device writes each
@@ -147,7 +162,7 @@ use super::texture::TextureShared;
use metal2vulkan::device::VkLimit;
use metal2vulkan::error::{Capability, Feature, Unsupported};
use metal2vulkan::metal::{TextureType, TextureUsage};
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, Weak};
@@ -212,11 +227,12 @@ const RESERVED_POOL_LIMIT: u64 = 1 << 28;
/// 16383 placed, 16384 to 65536 ended it).
pub(super) const PIPELINE_ID_LIMIT: u64 = 16384;
/// The first indirect command buffer ID whose reservation ended Metal's process: its pool would
/// hold 2^31 IDs or more (on an M4: 2^29 + 5 and 2^30 - 1 were taken and plain
/// IDs handed out past them; 2^30 + 5 to 2^31 - 1 ended it at the first allocation, 2^31 and up
/// at the reservation).
const RECORDS_RESERVED_LIMIT: u64 = 1 << 30;
/// The first indirect command buffer ID whose reservation Metal never returns from: its pool
/// would hold 2^32 IDs (on an M3 Max, macOS 27.0.1: 2^23 + 5, 2^29 + 5, 2^30 + 5, 3 * 2^29 and
/// 2^31 - 2 were taken and plain IDs handed out past them, each buffer made and run; 2^31, 2^31 +
/// 5 and 2^32 - 1 spun, and 2^32 was dropped). An M4 ended the process at the first allocation
/// after 2^30 + 5 to 2^31 - 1, and at the reservation from 2^31.
const RECORDS_RESERVED_LIMIT: u64 = 1 << 31;
/// The first ID an indirect command buffer's placement is refused at: past Metal's table of
/// them, which Metal writes past (on an M4: 16384 to 50367 made in each of six
@@ -287,6 +303,9 @@ pub(super) struct ResourceIds {
/// The pipeline state IDs whose holder the program released, which no state took since,
/// each with its last holder's kind and hold serial (`IdHold::serial`).
released_pipelines: BTreeMap<u64, (StateKind, u64)>,
/// The last [`PIPELINE_HOLDERS`] holders of each pipeline state ID, oldest first, released
/// or not ([`ResourceIds::pipeline_holder_by`]).
pipeline_holders: BTreeMap<u64, VecDeque<PipelineHolder>>,
/// The keys pipeline states numbered that a holder may hold, each with its ID
/// (`numbered.rs`).
numbered: BTreeMap<numbered::SamplerKey, (u64, Weak<Numbered>)>,
@@ -326,6 +345,7 @@ impl Default for ResourceIds {
counter: 0,
device_sampler: None,
released_pipelines: BTreeMap::new(),
pipeline_holders: BTreeMap::new(),
numbered: BTreeMap::new(),
libraries: BTreeMap::new(),
functions: BTreeMap::new(),
@@ -350,6 +370,35 @@ impl ResourceIds {
self.counter
}
/// A value of the counter past every hold serial handed out so far: a holder whose serial
/// is below it took its ID before now ([`ResourceIds::pipeline_holder_by`]).
pub(super) fn stamp(&mut self) -> u64 {
self.next()
}
/// The state that held pipeline state ID `id` at `stamp` ([`ResourceIds::stamp`]): the last
/// to take it before then, released since or not; none where none of the ID's last
/// [`PIPELINE_HOLDERS`] holders took it before then.
pub(super) fn pipeline_holder_by(&self, id: u64, stamp: u64) -> Option<HolderThen> {
let holder = self
.pipeline_holders
.get(&id)?
.iter()
.rev()
.find(|holder| holder.serial < stamp)?;
let holds = self
.pipelines
.slots
.get(&id)
.is_some_and(|slot| slot.serial == holder.serial);
Some(HolderThen {
kind: holder.kind,
serial: holder.serial,
identifier: holder.identifier,
holds,
})
}
/// The count of held sampler IDs and the sampler pool's size (the module docs), which the
/// device reads without this lock.
pub(super) fn sampler_id_reads(&self) -> SamplerIdReads {
@@ -381,6 +430,11 @@ impl ResourceIds {
self.space(space).reserve(ids)
}
/// Whether `space`'s pool handed out an ID or took a reservation ([`Pool::started`]).
pub(super) fn started(&mut self, space: IdSpace) -> bool {
self.space(space).plain.started()
}
/// Take the sampler ID Metal's device keeps for itself as it makes its first object of a
/// kind that keeps one (the module docs): the ID a live pipeline state's numbered device
/// sampler has, kept now for good (a queue or a texture made after a render
@@ -576,6 +630,11 @@ impl Pool {
pool
}
/// Whether the pool handed out an ID or took a reservation: a reservation is ignored then.
pub(super) fn started(&self) -> bool {
self.started
}
/// Count a resource of the space as an allocation, as Metal counts one placed at an ID:
/// a reservation after it is ignored.
pub(super) fn start(&mut self) {
@@ -592,14 +651,19 @@ impl Pool {
}
/// Reserve `ids` ([`Pool::keep`]): false, reserving nothing, once the pool started. 0, the
/// null handle, is no ID, and a call of no other ID leaves the pool as it was, as Metal's
/// does (Metal's pool, given 0, later hands IDs out twice: not copied). A made pool
/// ([`Pool::make`]) keeps its first range, from 1 to its first size, beside the ranges the
/// reservation leaves, as Metal's does.
/// null handle, is no ID: a call of no ID leaves the pool as it was, and one of 0 alone leaves
/// it made ([`Pool::make`]) before it started, and is ignored after (Metal logs it then, as
/// any late call), as Metal's does. A made pool keeps its first range, from 1 to its first
/// size, beside the ranges the reservation leaves, as Metal's does.
pub(super) fn reserve(&mut self, ids: impl IntoIterator<Item = u64>) -> bool {
let ids: Vec<u64> = ids.into_iter().filter(|&id| id != 0).collect();
let all: Vec<u64> = ids.into_iter().collect();
let ids: Vec<u64> = all.iter().copied().filter(|&id| id != 0).collect();
if ids.is_empty() {
return true;
if all.is_empty() {
return true;
}
self.make();
return !self.started;
}
if self.started {
return false;
@@ -764,6 +828,31 @@ impl Elements {
}
}
/// How many of each pipeline state ID's holders the device keeps
/// ([`ResourceIds::pipeline_holder_by`]), and a buffer the programs of
/// (`released_programs.rs`).
pub(super) const PIPELINE_HOLDERS: usize = 4;
/// A pipeline state that took an ID: its kind, its hold serial and its `uniqueIdentifier`.
#[derive(Clone, Copy, Debug)]
struct PipelineHolder {
kind: StateKind,
serial: u64,
identifier: u64,
}
/// The state that held a pipeline state ID at a stamp ([`ResourceIds::pipeline_holder_by`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct HolderThen {
pub(super) kind: StateKind,
/// Its hold serial (`IdHold::serial`).
pub(super) serial: u64,
/// Its `uniqueIdentifier`.
pub(super) identifier: u64,
/// It holds the ID still: the program has not released it.
pub(super) holds: bool,
}
/// One ID's slot, while its holder lives: the holder and its hold serial.
#[derive(Debug)]
struct Slot {
@@ -851,6 +940,23 @@ impl IdHold {
}
}
/// Make `holder`, a pipeline state of `kind` whose `uniqueIdentifier` is `identifier`, its
/// slot's holder ([`hold`](Self::hold)), and the ID's last holder
/// ([`ResourceIds::pipeline_holder_by`]).
pub(super) fn hold_state(&self, holder: Holder, kind: StateKind, identifier: u64) {
self.hold(holder);
let mut all = lock(&self.ids);
let holders = all.pipeline_holders.entry(self.id).or_default();
if holders.len() == PIPELINE_HOLDERS {
holders.pop_front();
}
holders.push_back(PipelineHolder {
kind,
serial: self.serial,
identifier,
});
}
/// The ID.
pub(super) fn id(&self) -> ResourceId {
ResourceId(self.id)
@@ -930,24 +1036,37 @@ impl Device {
/// runtime extension): keep `ids` of `kind` from plain allocation for the device's life,
/// plain IDs then numbered as Metal numbers them (the module docs). Only the device's first
/// call of `kind` with an ID counts: a later one, or one once the device handed out an ID of
/// `kind`, is ignored, as Metal's is, and the device says so in one diagnostic line (through
/// its message sink, else on stderr). A call of no ID changes nothing.
/// `kind`, is ignored whatever it holds (an ID of 2^32 or more, 0 alone, or one refused
/// below), as Metal's is, and the device says so in one diagnostic line (through its message
/// sink, else on stderr), as Metal logs it. A call of no ID changes nothing.
///
/// A call holding an ID of 2^32 or more is dropped whole, silently, and leaves the kind's
/// reservation to a later call, as Metal's is; 0, the null handle, reserves nothing.
/// Before that, a call holding an ID of 2^32 or more is dropped whole, silently, and leaves
/// the kind's reservation to a later call, as Metal's is; 0, the null handle, reserves nothing. A call
/// of 0 alone, before any ID of `kind`, leaves `kind`'s pool to keep its first range beside a
/// later reservation's ranges, so plain allocation hands that range's IDs out twice, as
/// Metal's does (the module docs).
///
/// Refused, reserving nothing: a texture or sampler state ID of 2^28 or more, and an indirect
/// command buffer ID of 2^30 or more (`Invalid`, `Problem::ResourceId`), which end Metal's
/// process; a texture ID no set-1 array of the device can hold (`Unsupported`, naming the
/// limit). An indirect command buffer ID needs no records to be reserved, but a buffer whose
/// own ID would be [`RECORDS_ID_LIMIT`](metal2vulkan::bind::indirect_commands::RECORDS_ID_LIMIT)
/// or more is refused `OutOfMemory` as it is made: its records would have no address.
/// Refused, reserving nothing, where the call is not ignored: a texture or sampler state ID
/// of 2^28 or more, which ends
/// Metal's process (`Invalid`, `Problem::ResourceId`); an indirect command buffer ID of 2^31
/// or more, at which Metal's reservation never returns (`Invalid`,
/// `Problem::ReservationHangs`); and a texture ID no set-1 array of the device can hold
/// (`Unsupported`, naming the limit). Plain indirect command buffer IDs past a reservation
/// are Metal's, to 2^31 - 1, each buffer made at any length.
pub fn reserve_resource_ids(
&self,
kind: ResourceIdKind,
ids: &[ResourceId],
) -> Result<(), Error> {
const CALL: &str = "reserve_resource_ids";
// Metal ignores a late call before it looks at what the call holds (an M3 Max, macOS
// 27.0.1: after a buffer or a reservation, 2^31, 2^31 + 5, 2^32 - 1, 2^32 + 5 and 0 alone
// of indirect command buffers, and 2^28 + 5 and 2^31 + 5 of textures, each logged and
// ignored, plain IDs going on as before).
if !ids.is_empty() && self.reservation_closed(kind) {
self.ignore_late_reservation(kind, ids.len());
return Ok(());
}
if ids.iter().any(|id| id.0 > u64::from(u32::MAX)) {
return Ok(());
}
@@ -960,9 +1079,16 @@ impl Device {
self.check_capacity(id, sampled.max(storage))?;
}
ResourceIdKind::SamplerState => check_limit(CALL, id, RESERVED_POOL_LIMIT)?,
ResourceIdKind::IndirectCommandBuffer => {
check_limit(CALL, id, RECORDS_RESERVED_LIMIT)?
ResourceIdKind::IndirectCommandBuffer if id >= RECORDS_RESERVED_LIMIT => {
return Err(invalid(
CALL,
Problem::ReservationHangs {
id,
limit: RECORDS_RESERVED_LIMIT,
},
));
}
ResourceIdKind::IndirectCommandBuffer => {}
ResourceIdKind::PipelineState => {}
}
}
@@ -976,19 +1102,39 @@ impl Device {
lock(&self.shared().addresses).reserve_records(&ids)
}
};
// Another thread's allocation may have come between: the call is late then too.
if !taken {
self.diagnose(
"metal2vulkan-late-reservation",
format!(
"metal2vulkan: {CALL}: reserve() must be called before any allocation takes \
place; the reservation of {} {kind:?} IDs is ignored, as Metal ignores it",
ids.len()
),
);
self.ignore_late_reservation(kind, ids.len());
}
Ok(())
}
/// Whether `kind`'s pool handed out an ID or took a reservation, so a reservation call is
/// ignored ([`Pool::started`]).
fn reservation_closed(&self, kind: ResourceIdKind) -> bool {
let space = |space| lock(&self.shared().resource_ids).started(space);
match kind {
ResourceIdKind::Texture => space(IdSpace::Texture),
ResourceIdKind::SamplerState => space(IdSpace::Sampler),
ResourceIdKind::PipelineState => space(IdSpace::Pipeline),
ResourceIdKind::IndirectCommandBuffer => {
lock(&self.shared().addresses).records_started()
}
}
}
/// Say that a late reservation call of `count` IDs of `kind` is ignored, as Metal logs it.
fn ignore_late_reservation(&self, kind: ResourceIdKind, count: usize) {
const CALL: &str = "reserve_resource_ids";
self.diagnose(
"metal2vulkan-late-reservation",
format!(
"metal2vulkan: {CALL}: reserve() must be called before any allocation takes \
place; the reservation of {count} {kind:?} IDs is ignored, as Metal ignores it"
),
);
}
/// How many sampler IDs the device holds now: one for each holder of one (the module docs'
/// live count). That is each live sampler state (equal requests share one state, as on
/// Metal; a state placed at an ID counts as one of its own); the device's own sampler once
@@ -90,7 +90,7 @@ impl CommandBuffer {
}
state.encoder_open = true;
drop(state);
self.device().shared().identifiers.encoder_opened();
(self.device().shared().identifiers).encoder_opened(EncoderKind::ResourceState);
Ok(ResourceStateCommandEncoder {
open: OpenGuard {
command_buffer: self.clone(),
@@ -551,10 +551,62 @@ fn records_take_the_lowest_free_id_and_leave_the_spaces_alone() {
space.place(Place::Records(RECORDS_ID_LIMIT), PAGE).is_err(),
"no records address"
);
// Records of any length start at their ID's address, past later IDs' starts too, and end
// below 2^64 (2^62 bytes past the last ID's start).
for (id, length) in [
(1, (1 << 31) + 1),
(1 << 26, 1 << 36),
(RECORDS_ID_LIMIT - 1, 1 << 62),
] {
let (at, records) = space.place(Place::Records(id), length).unwrap();
assert_eq!(at.0, records_address(id));
space.free(records);
}
assert!(
space.place(Place::Records(1), (1 << 40) + 1).is_err(),
"past one ID's records"
space
.place(Place::Records(RECORDS_ID_LIMIT - 1), (1 << 62) + (1 << 31))
.is_err(),
"past 2^64"
);
assert!(space.is_empty());
}
/// Indirect command buffers' plain IDs past a reservation of 2^23 or more are the ones Metal hands
/// out (an M3 Max, macOS 27.0.1): the lower of the two free ranges the reserved ID splits, the
/// shorter where they differ, to 2^31 - 1, each below the records' limit.
#[test]
fn records_ids_past_a_high_reservation_are_the_m3_max_s() {
let cases: [(u64, &[u64]); 11] = [
(1 << 23, &[1, 2]),
((1 << 23) + 5, &[(1 << 23) + 6, (1 << 23) + 7]),
(16_000_000, &[16_000_001, 16_000_002]),
((1 << 29) + 5, &[(1 << 29) + 6, (1 << 29) + 7]),
((1 << 30) - 1, &[1, 2]),
(1 << 30, &[1, 2]),
((1 << 30) + 5, &[(1 << 30) + 6, (1 << 30) + 7]),
(3 << 29, &[(3 << 29) + 1, (3 << 29) + 2]),
((1 << 31) - 2, &[(1 << 31) - 1, 1]),
((1 << 31) - 1, &[1, 2]),
((1 << 26) - 3, &[(1 << 26) - 2, (1 << 26) - 1, 1]),
];
for (reserved, ids) in cases {
let mut space = AddressSpace::new();
assert!(space.reserve_records(&[reserved]));
let mut held = Vec::new();
for &id in ids {
let next = space.take_records_id(None).unwrap();
assert_eq!(next.id, id, "{reserved}");
assert!(next.id < RECORDS_ID_LIMIT);
held.push(next);
}
for id in held {
space.give_records_id(id);
}
}
// Beside a low ID, the range below the low one is the shortest.
let mut space = AddressSpace::new();
assert!(space.reserve_records(&[10, (1 << 30) + 5]));
assert_eq!(space.take_records_id(None).unwrap().id, 1);
}
/// Indirect command buffers' records IDs after a reservation are the ones Metal hands out, from a
@@ -587,6 +639,36 @@ fn records_ids_after_a_reservation_are_metal_s() {
}
}
/// Indirect command buffers' plain IDs after a call of 0 alone, then a reservation, are Metal's:
/// the pool's first range kept beside the reservation's, its IDs handed out twice (an M3 Max,
/// macOS 27.0.1, and the consumer's runs of 0 then 100 and 0 then 2^31 - 1 there).
#[test]
fn records_ids_after_a_lone_zero_are_handed_out_twice_as_metal_s() {
let cases: [(u64, &[(u64, u64)]); 7] = [
(10, &[(1, 9), (11, 31), (1, 15)]),
(20, &[(21, 31), (1, 19), (1, 10)]),
(40, &[(41, 63), (1, 31), (1, 16)]),
(31, &[(1, 30), (1, 50)]),
(32, &[(1, 31), (33, 81)]),
(100, &[(101, 127), (1, 31), (1, 82)]),
((1 << 31) - 1, &[(1, 31), (1, 40)]),
];
for (reserved, runs) in cases {
let mut space = AddressSpace::new();
assert!(space.reserve_records(&[0]));
assert!(space.reserve_records(&[reserved]));
let mut held = Vec::new();
for id in runs.iter().flat_map(|&(first, last)| first..=last) {
let next = space.take_records_id(None).unwrap();
assert_eq!(next.id, id, "0, then {reserved}");
held.push(next);
}
for id in held {
space.give_records_id(id);
}
}
}
/// A placed indirect command buffer's ID is not the pool's (on an M4, plain and
/// under API validation): plain allocation neither skips it (1, 2, then 3 placed, then 3 and 4
/// plain) nor gets it back once the placed buffer is gone (1 to 4 plain, 2 placed and gone: 5, 6
@@ -106,7 +106,6 @@ metal2vulkan-degrade-implementation-defined-reconvergence
metal2vulkan-degrade-in-place-vertex-reads
metal2vulkan-degrade-indirect-index-bounds-pass
metal2vulkan-degrade-indirect-nil-buffer-offset
metal2vulkan-degrade-indirect-value-past-record
metal2vulkan-degrade-input-attachment-srgb-decode
metal2vulkan-degrade-isolated-index-bytes
metal2vulkan-degrade-landed-visibility-results
@@ -160,6 +160,8 @@ mod rate_map;
mod reader_sizes;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod recycle;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod released_programs;
mod render;
mod replays;
mod resource;
@@ -0,0 +1,59 @@
//! The programs a buffer whose records the GPU may write keeps of the pipeline states the
//! program releases (`released_programs.rs`) stay bounded: at most four of an ID, however many
//! states take the ID and give it back.
//!
//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The function is the owned fixture
//! `validation/fixtures/public/examples/runtime_examples.ll` (`llvm-as`).
use super::blit_holds::{device, Scratch};
use crate::{IndirectCommandBufferDescriptor, PipelineOptions, ResourceId, ResourceOptions};
use metal2vulkan::metal::IndirectCommandType;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use std::path::Path;
/// The states made and released on one ID.
const CYCLES: usize = 1000;
/// A buffer the GPU may write keeps the programs of the states made with
/// `supportIndirectCommandBuffers` the program releases, at most four of an ID: after 1000 states
/// took ID 1 and gave it back, it keeps four, the last released, and the buffer made after it
/// that the GPU never writes keeps none.
#[test]
fn a_buffer_keeps_at_most_four_released_programs_of_an_id() {
let scratch = Scratch::new("released-programs");
let device = device(&scratch.0);
let ll = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll");
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap();
let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap();
let function = device
.new_library_with_compile_library(library)
.new_function_with_name("scale_and_offset")
.unwrap();
let mut descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
descriptor.support_indirect_command_buffers = true;
let mut commands = IndirectCommandBufferDescriptor::new();
commands.command_types = IndirectCommandType::CONCURRENT_DISPATCH_THREADS;
commands.max_kernel_buffer_bind_count = 3;
let make = || {
device
.new_indirect_command_buffer(&commands, 1, ResourceOptions::shared())
.unwrap()
};
let written = make();
// The hold of a command buffer that may write its records, completed at once.
drop(written.gpu_write());
let unwritten = make();
for cycle in 0..CYCLES {
let state = device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
assert_eq!(state.gpu_resource_id(), ResourceId(1), "cycle {cycle}");
drop(state);
assert!(written.kept_count() <= 4, "cycle {cycle}");
}
assert_eq!(written.kept_count(), 4);
assert_eq!(unwritten.kept_count(), 0);
}
@@ -386,9 +386,9 @@ fn an_id_given_back_joins_its_free_neighbours() {
}
/// Only a space's first reservation with an ID counts, whether or not the space handed one out
/// since; a call of no ID, or of 0 alone, changes nothing (16, then 5, keeps 16 alone;
/// `empty_first`; whose later IDs the runtime hands out once, where Metal's pool handed out 1 to 4
/// again).
/// since; a call of no ID, or of 0 alone, reserves nothing (16, then 5, keeps 16 alone;
/// `empty_first`; an M3 Max handed out these 17 IDs after it, where the M4's pool handed out 1 to
/// 4 again later).
#[test]
fn only_the_first_reservation_with_an_id_counts() {
let ids = ids();
@@ -403,6 +403,37 @@ fn only_the_first_reservation_with_an_id_counts() {
assert_eq!(got, expand(&[(1, 15), (17, 18)]));
}
/// A call of 0 alone leaves the pool made, so a later reservation keeps the pool's first range
/// beside its own and plain allocation hands that range's IDs out twice, as Metal's does (an M3
/// Max, macOS 27.0.1: textures, 0 then 10 gives 11 to 15, 1 to 9, then 1 to 31; 0 then 16, the
/// first range equal to one left, 1 to 15, then 17 on); a lone 0 once the pool started is ignored,
/// as Metal ignores and logs it (5, then 0: 1 to 4, then 6 on).
#[test]
fn a_lone_zero_leaves_the_pool_made() {
for (reserved, runs) in [
(10, &[(11, 15), (1, 9), (1, 31)][..]),
(16, &[(1, 15), (17, 61)][..]),
] {
let ids = ids();
let mut all = ids.lock().unwrap();
assert!(all.reserve(IdSpace::Texture, &[ResourceId(0)]));
assert!(all.reserve(IdSpace::Texture, &[ResourceId(reserved)]));
drop(all);
let want = expand(runs);
let held: Vec<IdHold> = want.iter().map(|_| id(&ids, IdSpace::Texture)).collect();
let got: Vec<u64> = held.iter().map(|held| held.id().0).collect();
assert_eq!(got, want, "0, then {reserved}");
}
let ids = ids();
let mut all = ids.lock().unwrap();
assert!(all.reserve(IdSpace::Texture, &[ResourceId(5)]));
assert!(!all.reserve(IdSpace::Texture, &[ResourceId(0)]), "late");
drop(all);
let held: Vec<IdHold> = (0..8).map(|_| id(&ids, IdSpace::Texture)).collect();
let got: Vec<u64> = held.iter().map(|held| held.id().0).collect();
assert_eq!(got, expand(&[(1, 4), (6, 9)]));
}
/// Visible-function tables' first pool is 32, as Metal's (2 to 4 of 1 to 5
/// given back come back before 6, 2 to 6 of 1 to 13 before 14, and 2 to 10 of 1 to 29 after 30
/// and 31).
@@ -6,9 +6,10 @@ use std::sync::Arc;
use crate::degradation::Degradation;
use crate::resource_ids::StateKind;
use crate::unique_identifier::{
state_value_degradation, UniqueIdentifier, UniqueIdentifiers, BUFFERS_END, BUFFER_FIRST,
COMPUTE_FIRST, COMPUTE_STEP, INDIRECT_BASE, PLAIN_FIRST, RENDER_STEP,
state_value_degradation, ScheduledWork, UniqueIdentifier, UniqueIdentifiers, BUFFERS_END,
BUFFER_FIRST, COMPUTE_FIRST, COMPUTE_STEP, INDIRECT_BASE, PLAIN_FIRST, RENDER_STEP,
};
use crate::used_resources::EncoderKind;
fn device() -> Arc<UniqueIdentifiers> {
Arc::default()
@@ -91,14 +92,15 @@ fn compute_states_go_past_the_buffers_once_metal_s_region_is_full() {
assert_eq!(buffer.value(), INDIRECT_BASE + BUFFER_FIRST);
}
/// Which identifiers are measured to be Metal's number: a buffer made before its device opened
/// an encoder; not one made after, nor any state, each with the kind its answer announces.
/// Which identifiers are measured to be Metal's number: a buffer made before Metal's own
/// allocations go past the model (a resource state encoder opened, or a render encoder's command
/// buffer scheduled); not one made after, nor any state, each with the kind its answer announces.
#[test]
fn only_buffers_made_before_an_encoder_are_metal_s_number() {
fn only_buffers_made_before_unmodelled_work_are_metal_s_number() {
let ids = device();
let before = UniqueIdentifier::buffer(&ids, 0x4000).unwrap();
assert_eq!(before.degradation(), None);
ids.encoder_opened();
ids.encoder_opened(EncoderKind::ResourceState);
let after = UniqueIdentifier::buffer(&ids, 0x4000).unwrap();
let unmeasured = Some(Degradation::UnmeasuredUniqueIdentifier);
assert_eq!(after.degradation(), unmeasured);
@@ -113,3 +115,99 @@ fn only_buffers_made_before_an_encoder_are_metal_s_number() {
assert_eq!(state_value_degradation(indirect.value()), unmeasured);
assert_eq!(state_value_degradation(plain.value()), run_to_run);
}
/// Metal's encoders take their pieces of the buffers' range as an M3 Max's do (macOS 27.0.1, the
/// probes' sequences, each on a device of its own; buffers of one page, 32 KiB each): a blit
/// encoder 256 KiB at its opening, a render encoder 384 KiB, the two sharing 192 KiB of it, and
/// the first command buffer scheduled with a dispatch or a blit's command 32 KiB more, each at the
/// lowest gap that holds it, once a device. A render command buffer scheduled leaves the model.
#[test]
fn encoders_take_metal_s_pieces_of_the_buffers_range() {
let page = |ids: &Arc<UniqueIdentifiers>| {
UniqueIdentifier::buffer(ids, 0x4000).unwrap().value() - INDIRECT_BASE
};
let held = |ids: &Arc<UniqueIdentifiers>| UniqueIdentifier::buffer(ids, 0x4000).unwrap();
// `n` more buffers, held, by their offsets.
let pages = |ids: &Arc<UniqueIdentifiers>, n: usize| -> Vec<u64> {
let made: Vec<UniqueIdentifier> = (0..n).map(|_| held(ids)).collect();
made.iter().map(|id| id.value() - INDIRECT_BASE).collect()
};
let dispatch = ScheduledWork {
dispatch: true,
render: false,
};
// A compute encoder takes nothing at its opening, its dispatch 32 KiB as it is scheduled,
// once.
let ids = device();
let first = held(&ids);
ids.encoder_opened(EncoderKind::Compute);
assert_eq!(page(&ids), 0x2_0000, "an open compute encoder");
let ids = device();
let first_too = held(&ids);
ids.encoder_opened(EncoderKind::Compute);
ids.scheduled(dispatch);
ids.scheduled(dispatch);
assert_eq!(page(&ids), 0x2_8000, "a dispatch scheduled");
// A blit encoder 256 KiB at its opening; its copy 32 KiB more as it is scheduled.
let ids = device();
ids.encoder_opened(EncoderKind::Blit);
assert_eq!(page(&ids), 0x5_8000, "an open blit encoder");
let ids = device();
let _first = held(&ids);
ids.encoder_opened(EncoderKind::Blit);
ids.scheduled(dispatch);
assert_eq!(page(&ids), 0x6_8000, "a blit encoder's copy");
// A dispatch and a copy share their 32 KiB, either first.
for blit_first in [false, true] {
let ids = device();
if blit_first {
ids.encoder_opened(EncoderKind::Blit);
}
ids.scheduled(dispatch);
ids.encoder_opened(EncoderKind::Blit);
ids.scheduled(dispatch);
assert_eq!(page(&ids), 0x6_0000, "blit first: {blit_first}");
}
// A render encoder 384 KiB at its opening, 192 KiB shared with a blit encoder's.
let ids = device();
ids.encoder_opened(EncoderKind::Render);
assert_eq!(page(&ids), 0x7_8000, "an open render encoder");
let ids = device();
ids.encoder_opened(EncoderKind::Blit);
ids.encoder_opened(EncoderKind::Render);
let after = UniqueIdentifier::buffer(&ids, 0x4000).unwrap();
assert_eq!(
after.value() - INDIRECT_BASE,
0x8_8000,
"the shared piece once"
);
assert_eq!(after.degradation(), None);
ids.scheduled(ScheduledWork {
dispatch: false,
render: true,
});
let past = UniqueIdentifier::buffer(&ids, 0x4000).unwrap();
assert_eq!(
past.degradation(),
Some(Degradation::UnmeasuredUniqueIdentifier),
"a render command buffer scheduled"
);
// Pieces take the lowest gap that holds them: of four buffers, the second and third
// released, a blit encoder's 64 KiB takes their gap, its 192 KiB and its copy's 32 KiB go
// past the fourth.
let ids = device();
let four: Vec<UniqueIdentifier> = (0..4).map(|_| held(&ids)).collect();
let [kept, second, third, fourth]: [UniqueIdentifier; 4] = four.try_into().unwrap();
drop((second, third));
ids.encoder_opened(EncoderKind::Blit);
ids.scheduled(dispatch);
assert_eq!(pages(&ids, 3), [0x7_0000, 0x7_8000, 0x8_0000]);
// Of three buffers, the second released, a dispatch scheduled takes its gap.
let ids = device();
let three: Vec<UniqueIdentifier> = (0..3).map(|_| held(&ids)).collect();
let [one, two, last]: [UniqueIdentifier; 3] = three.try_into().unwrap();
drop(two);
ids.scheduled(dispatch);
assert_eq!(pages(&ids, 2), [0x3_0000, 0x3_8000]);
drop((first, first_too, kept, fourth, one, last));
}
@@ -20,7 +20,7 @@ fn draws(primitive_types: u8) -> W {
#[test]
fn a_record_adds_what_it_holds() {
let written = Arc::new(WrittenCommands::default());
written.add_record(&CommandRecord::default(), None);
written.add_record(CommandRecord::default().writes(), None);
assert!(written.writes().is_empty());
let mut record = CommandRecord {
action: Action::DrawPrimitives {
@@ -32,14 +32,14 @@ fn a_record_adds_what_it_holds() {
},
..CommandRecord::default()
};
written.add_record(&record, None);
written.add_record(record.writes(), None);
assert_eq!(written.writes(), draws(0b1000));
record.barrier = true;
let named = Named {
encodes: true,
writes: W::NONE,
};
written.add_record(&record, Some(named));
written.add_record(record.writes(), Some(named));
assert_eq!(
written.writes().operations,
W::DRAW | W::BARRIER | W::PIPELINE
@@ -54,12 +54,13 @@ fn a_record_adds_what_it_holds() {
base_vertex: 0,
base_instance: 0,
};
written.add_record(&record, None);
written.add_record(record.writes(), None);
assert_eq!(written.writes().primitive_types, W::ALL_PRIMITIVE_TYPES);
}
/// A writer that may set a pipeline or copy a command may name any state; one that only draws
/// names none.
/// names none. One that may copy a command may write anything: the copied command holds what
/// its source held (a dispatch, a barrier), which the copier's own operations do not state.
#[test]
fn a_writer_that_sets_pipelines_names_any_state() {
let drawing = Arc::new(WrittenCommands::default());
@@ -67,12 +68,18 @@ fn a_writer_that_sets_pipelines_names_any_state() {
assert_eq!(drawing.named(), Named::default());
for bit in [W::PIPELINE, W::COPY] {
let setting = Arc::new(WrittenCommands::default());
setting.add_writer(W {
let writes = W {
operations: bit,
primitive_types: 0,
});
};
setting.add_writer(writes);
assert!(setting.named().encodes);
assert_eq!(setting.named().writes, W::ANY);
let held = match bit {
W::COPY => W::ANY,
_ => writes,
};
assert_eq!(setting.writes(), held, "{bit:#x}");
}
}
@@ -28,39 +28,44 @@
//! - **An indirect command buffer** answers `2^36` plus its private `gpuAddress`, in a range of
//! Metal's for them: the lowest gap from `0x18000` that holds its `allocatedSize` and one 16-KiB
//! page more, at a multiple of 32 KiB (`0x18000`, `0x20000`, `0x28000` for buffers of four
//! commands), free again as the buffer goes. The runtime answers that rule. Metal's own work
//! takes ranges there too, which the runtime does not (on the M4 the process's first blit
//! encoder that copies, resets or fills takes `0x48000` after the live buffers, and the first
//! render encoder about `0x298000`; on the M3 Max a first copy or reset about `0x4a8000`, a fill
//! `0x48000`, a render encoder that makes one resident or draws about `0x4c8000`), so a buffer
//! made after such work answers below Metal's; and Metal keeps a buffer's range while a command
//! buffer that executes it may run, where the runtime frees it as the buffer's last holder goes.
//! commands), free again as the buffer goes and no command buffer that executes it may run
//! (the command buffer holds it until it completed). The runtime answers that rule.
//!
//! **Which answers are Metal's**. An indirect command buffer made before its device opened any
//! command encoder answers Metal's number (the rule above; on an M4, on the M3 Max, gaps and
//! releases included): Metal's own encoders take ranges from their first, by kind and by machine
//! (on an M4 and the M3 Max package of the same probe): a compute encoder that dispatches or
//! executes a buffer takes a slot, and one that is empty, makes a buffer resident or is never
//! committed none; a blit encoder that copies takes a range on both, an empty one on the M4 only; a
//! render encoder takes one, never committed too, of another size on each machine. The runtime
//! counts every encoder, as no rule tells the encoders that take nothing on every machine (a
//! resource-state encoder's is not measured). No state's answer is measured to be Metal's. The
//! first answer of a program's call that is not Metal's number
//! **Metal's own encoders** take pieces of that range, each once a device, kept for its life, at
//! the lowest gap that holds it, as a buffer's range is (an M3 Max, macOS 27.0.1, each sequence
//! in a process of its own, alike in three rounds): a blit encoder 256 KiB at its opening (an
//! empty one, one never committed and one made while a buffer is made inside it alike), of which
//! 192 KiB a render encoder's opening takes too, and that 384 KiB in all; and the first command
//! buffer scheduled with a compute encoder's dispatch or execution, or a blit encoder's command (a
//! copy, a fill, a reset or copy of commands, a texture copy, a fence update; not a
//! `synchronizeResource`), 32 KiB as it is scheduled, after its waits (one that waits for an event
//! not yet signaled has taken nothing; one past `waitUntilScheduled` has). A compute encoder takes
//! nothing at its opening, nor one that is empty or only makes a buffer resident. Where the
//! pieces' order inside one opening is not told apart by a measured gap, the runtime takes the
//! shared piece first. The runtime takes them so ([`Piece`]). A render command buffer's run takes
//! more, by its targets' sizes and what the device drew before (a buffer made after a draw into a
//! 64-pixel target answers `0x4e0000` from the base, a 1024-pixel one `0x508000`, a 4096-pixel one
//! `0x17c8000`, and after one of 16 pixels then one of 4096 `0x4d8000`, below the 16-pixel one's
//! alone): the runtime does not model it, nor a resource state encoder's pieces (not measured).
//!
//! **Which answers are Metal's**. An indirect command buffer made before a command buffer of its
//! device that encoded a render encoder was scheduled, and before a resource state encoder
//! opened, answers Metal's number (the rules above). No state's answer is measured to be Metal's.
//! The first answer of a program's call that is not Metal's number
//! (`ComputePipelineState::unique_identifier`, `RenderPipelineState::unique_identifier`,
//! `IndirectCommandBuffer::unique_identifier`, an indirect command's state identifier but 0)
//! announces, once a device, one of two kinds by how Metal's own answer stands: a plain state's,
//! which differs from run to run on Metal, `plain-state-unique-identifier`
//! ([`Degradation::PlainStateUniqueIdentifier`], one of Metal's answers); a state's with indirect
//! command buffer support, or a buffer's made after an encoder, which Metal answers alike in every
//! command buffer support, or a buffer's made past the model, which Metal answers alike in every
//! run of one program started alike, `unmeasured-unique-identifier`
//! ([`Degradation::UnmeasuredUniqueIdentifier`], a near-equivalent). A program that reads only the
//! first buffers' identifiers announces nothing. The allocations and the encoder flag are the
//! ([`Degradation::UnmeasuredUniqueIdentifier`], a near-equivalent). The allocations are the
//! device's: Metal's measured space is one process's one device, which a device of the runtime
//! stands for.
//!
//! No run reads an identifier: a translated function never sees one.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
@@ -68,6 +73,7 @@ use crate::degradation::Degradation;
use crate::device::lock;
use crate::error::{Error, MemoryKind};
use crate::resource_ids::StateKind;
use crate::used_resources::EncoderKind;
use crate::Device;
/// The base of Metal's identifiers of indirect command buffers and of states made with
@@ -88,6 +94,45 @@ const BUFFER_PAGE: u64 = 0x4000;
/// The alignment of a buffer's range.
const BUFFER_SLOT: u64 = 0x8000;
/// One of Metal's own allocations in the buffers' range, which its encoders take (an M3 Max,
/// macOS 27.0.1; the module docs): each once a device, kept for its life, at the lowest gap that
/// holds it, as a buffer's range is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Piece {
/// The first blit or render encoder's, at its opening: 192 KiB.
Shared,
/// The first blit encoder's own, after [`Piece::Shared`]: 64 KiB.
Blit,
/// The first render encoder's own at its opening, after [`Piece::Shared`]: 192 KiB. Its
/// command buffer's run takes more, by its targets' sizes and what the device drew before,
/// which the runtime does not model ([`UniqueIdentifiers::scheduled`]).
Render,
/// The first command buffer scheduled with a compute encoder's dispatch or execution or a
/// blit encoder's command, as it is scheduled: 32 KiB.
Dispatch,
}
impl Piece {
/// Its footprint in the range, as measured.
fn footprint(self) -> u64 {
match self {
Piece::Shared | Piece::Render => 0x3_0000,
Piece::Blit => 0x1_0000,
Piece::Dispatch => 0x8000,
}
}
}
/// What a command buffer's encoders did that Metal's identifier allocations follow as it is
/// scheduled ([`UniqueIdentifiers::scheduled`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ScheduledWork {
/// A compute encoder dispatched or executed commands, or a blit encoder encoded a command.
pub(crate) dispatch: bool,
/// A render encoder was encoded.
pub(crate) render: bool,
}
/// The end of the buffers' range, from [`INDIRECT_BASE`], where the compute states' starts.
pub(crate) const BUFFERS_END: u64 = 1 << 34;
@@ -159,16 +204,19 @@ const RENDER_RANGES: &[(u64, u64)] = &[(2 * BUFFERS_END, 4 * BUFFERS_END)];
struct Allocations {
compute: Slots,
render: Slots,
/// The live indirect command buffers' ranges: start, then bytes.
/// The live indirect command buffers' ranges and Metal's own taken pieces' ([`Piece`]):
/// start, then bytes.
buffers: BTreeMap<u64, u64>,
/// The pieces taken.
pieces: BTreeSet<Piece>,
}
/// One device's identifiers: its allocations, and whether it opened a command encoder, from
/// which on Metal's own encoders take ranges of the buffers' (the module docs).
/// One device's identifiers: its allocations, and whether Metal's own allocations in the
/// buffers' range are past what the runtime models (the module docs).
#[derive(Debug)]
pub(crate) struct UniqueIdentifiers {
allocations: Mutex<Allocations>,
encoded: AtomicBool,
unmeasured: AtomicBool,
}
impl Default for UniqueIdentifiers {
@@ -178,19 +226,62 @@ impl Default for UniqueIdentifiers {
compute: Slots::new(COMPUTE_RANGES, COMPUTE_STEP),
render: Slots::new(RENDER_RANGES, RENDER_STEP),
buffers: BTreeMap::new(),
pieces: BTreeSet::new(),
}),
encoded: AtomicBool::new(false),
unmeasured: AtomicBool::new(false),
}
}
}
impl UniqueIdentifiers {
/// Note that the device opened a command encoder: an indirect command buffer made from now
/// on answers no number measured to be Metal's.
pub(crate) fn encoder_opened(&self) {
/// The device opened a command encoder of `kind`: the pieces Metal's takes at its opening
/// (a blit encoder's [`Piece::Shared`] and [`Piece::Blit`], a render encoder's
/// [`Piece::Shared`] and [`Piece::Render`], a compute encoder's none). A resource state
/// encoder's are not measured: an indirect command buffer made from then on answers no
/// number measured to be Metal's.
pub(crate) fn encoder_opened(&self, kind: EncoderKind) {
match kind {
EncoderKind::Blit => self.take(&[Piece::Shared, Piece::Blit]),
EncoderKind::Render => self.take(&[Piece::Shared, Piece::Render]),
EncoderKind::Compute => {}
EncoderKind::ResourceState => self.unmodelled(),
}
}
/// A command buffer of the device that did `work` is scheduled, after its waits: the
/// [`Piece::Dispatch`] Metal's dispatch or blit work takes then; and where it encoded a render
/// encoder, what Metal's run of it takes, which follows its targets' sizes and what the
/// device drew before (an M3 Max: a buffer made after a draw into a 64-pixel target answers
/// `0x4e0000` from the base, into a 1024-pixel one `0x508000`, a 4096-pixel one `0x17c8000`,
/// and after one of 16 pixels then one of 4096 `0x4d8000`), which the runtime does not model:
/// a buffer made from then on answers no number measured to be Metal's.
pub(crate) fn scheduled(&self, work: ScheduledWork) {
if work.dispatch {
self.take(&[Piece::Dispatch]);
}
if work.render {
self.unmodelled();
}
}
/// Take `pieces` not yet taken, in order; one no gap holds leaves Metal's allocations past
/// the model.
fn take(&self, pieces: &[Piece]) {
let mut allocations = lock(&self.allocations);
for &piece in pieces {
if allocations.pieces.insert(piece)
&& allocations.take_range(piece.footprint()).is_none()
{
self.unmodelled();
}
}
}
/// Metal's own allocations are past what the runtime models from now on.
fn unmodelled(&self) {
// Relaxed: only the flag's value matters, read by the buffers made after the program's
// call that opened the encoder.
self.encoded.store(true, Ordering::Relaxed);
// call that set it.
self.unmeasured.store(true, Ordering::Relaxed);
}
}
@@ -215,6 +306,12 @@ impl Allocations {
let footprint = allocated_size
.checked_add(BUFFER_PAGE)?
.checked_next_multiple_of(BUFFER_SLOT)?;
self.take_range(footprint)
}
/// The offset of the lowest gap from [`BUFFER_FIRST`] that holds `footprint` bytes (a
/// multiple of the slot), taken; none where the range has none.
fn take_range(&mut self, footprint: u64) -> Option<u64> {
let mut offset = BUFFER_FIRST;
for (&start, &bytes) in &self.buffers {
if start >= offset.checked_add(footprint)? {
@@ -286,10 +383,10 @@ impl UniqueIdentifier {
let offset = lock(&ids.allocations)
.take_buffer(allocated_size)
.ok_or(Error::OutOfMemory(MemoryKind::Device))?;
let encoded = ids.encoded.load(Ordering::Relaxed);
let unmeasured = ids.unmeasured.load(Ordering::Relaxed);
Ok(UniqueIdentifier {
value: INDIRECT_BASE + offset,
degradation: encoded.then_some(Degradation::UnmeasuredUniqueIdentifier),
degradation: unmeasured.then_some(Degradation::UnmeasuredUniqueIdentifier),
back: Some((Arc::clone(ids), Allocation::Buffer)),
})
}
@@ -18,7 +18,6 @@
use std::sync::{Arc, Mutex, Weak};
use metal2vulkan::bind::indirect_commands::CommandRecord;
use metal2vulkan::pipeline::CommandWrites;
use super::device::lock;
@@ -62,6 +61,21 @@ struct Held {
copies: Vec<Weak<WrittenCommands>>,
}
impl Held {
/// Add `writes` and `named`; where that changed what it holds, the buffers a blit copied its
/// records into, which gain them too.
fn grow(&mut self, writes: CommandWrites, named: Named) -> Option<Vec<Arc<WrittenCommands>>> {
let (grown, grown_named) = (self.writes.union(writes), self.named.union(named));
if grown == self.writes && grown_named == self.named {
return None;
}
self.writes = grown;
self.named = grown_named;
self.copies.retain(|copy| copy.strong_count() > 0);
Some(self.copies.iter().filter_map(Weak::upgrade).collect())
}
}
impl WrittenCommands {
/// The operations and primitive types the records may hold.
pub(crate) fn writes(&self) -> CommandWrites {
@@ -74,30 +88,30 @@ impl WrittenCommands {
}
/// Add `writes` and `named` to the buffer's, and to every buffer a blit copied its records
/// into, at any remove.
/// into, at any remove. What adds nothing to the buffer's adds nothing to its copies', which
/// hold the buffer's: it is looked at under the buffer's lock alone, as most setters' calls
/// add nothing new.
pub(crate) fn add(self: &Arc<Self>, writes: CommandWrites, named: Named) {
let mut seen: Vec<*const WrittenCommands> = Vec::new();
let mut next = vec![Arc::clone(self)];
let copies = match lock(&self.held).grow(writes, named) {
Some(copies) => copies,
None => return,
};
let mut seen: Vec<*const WrittenCommands> = vec![Arc::as_ptr(self)];
let mut next = copies;
while let Some(buffer) = next.pop() {
if seen.contains(&Arc::as_ptr(&buffer)) {
continue;
}
seen.push(Arc::as_ptr(&buffer));
let mut held = lock(&buffer.held);
let (was, was_named) = (held.writes, held.named);
held.writes = held.writes.union(writes);
held.named = held.named.union(named);
if held.writes == was && held.named == was_named {
continue;
if let Some(copies) = lock(&buffer.held).grow(writes, named) {
next.extend(copies);
}
held.copies.retain(|copy| copy.strong_count() > 0);
next.extend(held.copies.iter().filter_map(Weak::upgrade));
}
}
/// What the CPU's edit left in a record: its action, its barrier, and the state it names.
pub(crate) fn add_record(self: &Arc<Self>, record: &CommandRecord, named: Option<Named>) {
let mut writes = record.writes();
/// What the CPU's edit left in a record (`CommandRecord::writes`: its action and its
/// barrier), and the state it names.
pub(crate) fn add_record(self: &Arc<Self>, mut writes: CommandWrites, named: Option<Named>) {
if named.is_some() {
writes.operations |= CommandWrites::PIPELINE;
}
@@ -105,12 +119,16 @@ impl WrittenCommands {
}
/// What a state that may write the records adds: its functions' writes, and where they may
/// set a pipeline or copy a command (whose pipeline comes along), any state named.
/// set a pipeline or copy a command (whose pipeline comes along), any state named. A copy
/// brings whatever the source command held, which its writer's own operations do not state:
/// a function that may copy a command may write anything.
pub(crate) fn add_writer(self: &Arc<Self>, writes: CommandWrites) {
let named = if writes.may(CommandWrites::PIPELINE | CommandWrites::COPY) {
Named::ANY
let (writes, named) = if writes.may(CommandWrites::COPY) {
(CommandWrites::ANY, Named::ANY)
} else if writes.may(CommandWrites::PIPELINE) {
(writes, Named::ANY)
} else {
Named::default()
(writes, Named::default())
};
self.add(writes, named);
}
@@ -175,7 +175,7 @@ use super::heap_metal_sizes::{PAST_METAL_SIZES, UNMODELLED_SIZES};
use super::heap_textures::{ALIASES, APART, COMPRESSED, OPTIMIZED};
use super::host_memory::{not_importable, Mapping, GUEST_PAGE, READ_ONLY_PAGES};
use super::index_fetches::INDEX_FETCHES;
use super::indirect_command_buffers::{PAST_RECORD, UNMEASURED_IDENTIFIERS};
use super::indirect_command_buffers::UNMEASURED_IDENTIFIERS;
use super::indirect_dispatches::INDIRECT_DISPATCHES;
use super::indirect_executions::{NIL_OFFSETS, RELEASED_STATES};
use super::indirect_host_steps::HOST_STEPS;
@@ -537,7 +537,6 @@ fn every_kind_has_a_site_a_lane_test_takes() {
&FRESH_PATTERNS,
&UNMODELLED_SIZES,
&UNMEASURED_IDENTIFIERS,
&PAST_RECORD,
&CROSS_CLASS,
&NIL_OFFSETS,
&BLOCK_DECODES,
@@ -19,17 +19,28 @@
//! rebound, recorded once, its resident table pointed at the set as it lies at the first
//! submission;
//! - a range its own commands alone;
//! - a record a blit copied naming a state the program released since, which runs that state's
//! program, after another state took its ID too;
//! - with as many live states as the GPU-alone path takes in its encoder's order on the GPU alone,
//! and with one more in the host step, which runs it faster;
//! - inside a block of command predication, nothing where the block skips and every command where
//! it holds, from the preprocess's gate;
//! - a checked execution, and one whose range is read from a buffer, keep the host step, announced
//! once, and run the same.
//! - an execution `commit` recorded from the CPU's records (no encoder made the buffer resident
//! for writing) whose records the CPU writes after the commit, before the batch is submitted (it
//! waits for an event), runs them as written then, recorded again from the records then, and
//! announces nothing; without the write, the commit's recording runs;
//! - a checked execution whose check has nothing to see (no state the records may name encodes
//! indirect commands) runs on the GPU alone, its check never called, and one whose range is read
//! from a buffer keeps the host step, which does not call it either; where a state the CPU set
//! on a command may encode, the host step of either calls it with each command before any runs,
//! a check that looks for nothing still uncalled; where the CPU sets such a state after the
//! commit, before the batch is submitted, the host step records the execution instead and calls
//! the check. Each runs the same; the host step is announced once.
use super::degrade_notices::assert_made_once;
use super::generated_executions::flat_template;
use super::host_memory::Seen;
use super::indirect_host_steps::HOST_STEPS;
use super::indirect_host_steps::{self, HOST_STEPS};
use super::rebind_reach::{buffer_len, buffer_over, pages};
use super::rebinds::rebind;
use super::shared_kinds;
@@ -44,8 +55,10 @@ use metal2vulkan_devtools::llvm_assemble_text;
use metal2vulkan_runtime::{
Buffer, CommandBuffer, CommandBufferStatus, ComputeCommandEncoder, ComputePipelineState,
Degradation, Device, EventRef, ExecutedPipeline, IndirectCommandBuffer,
IndirectCommandBufferDescriptor, PipelineOptions, ResourceOptions, Size,
IndirectCommandBufferDescriptor, IndirectCommandCheck, IndirectCommandCheckNeeds,
PipelineOptions, ResourceOptions, Size,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
/// `flat_mark(params, out, p)`: each thread adds `params[0] * 1000 + p.x` to `out[p.x]` by a
@@ -174,6 +187,13 @@ fn expected(ran: std::ops::Range<usize>) -> Vec<u32> {
out
}
/// [`expected`] over a buffer of `size` commands: those past [`PLAN`]'s run nothing.
fn expected_of(size: u64, ran: std::ops::Range<usize>) -> Vec<u32> {
let mut out = expected(ran);
out.resize(size as usize * WINDOW, 0);
out
}
/// The test's buffers and states: the indirect command buffer of [`PLAN`]'s commands, written by
/// the CPU, `params`, `out`, and both states.
struct Setup {
@@ -418,6 +438,74 @@ fn each_command_runs_its_own_state_and_group_count() {
});
}
/// A record the GPU wrote naming a state the program released since runs that state's program on
/// the GPU alone, as Metal's runs it (`released_programs.rs`): a blit copies a command of
/// [`FLAT_MARK`]'s state from a buffer of its own into the unwritten command 2 (the GPU writes
/// it), and the program releases the state and the source buffer; the execution runs it beside
/// the others, one indirect dispatch per command and state (the kept program's among them), with
/// nothing announced. So it does where a state made after (`flat_sum`'s) took the released
/// state's ID: the ID names the kept program, as the copy wrote it before the new state took it.
#[test]
fn a_copied_record_runs_its_released_state_s_program_on_the_gpu_alone() {
for taken in [false, true] {
on_device(|device, messages| {
let queue = device.new_command_queue().unwrap();
let setup = Setup::new(device);
let threads = 8;
let id = {
let mark = mark_state(device);
let mut descriptor = IndirectCommandBufferDescriptor::new();
descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH
.union(IndirectCommandType::CONCURRENT_DISPATCH_THREADS);
descriptor.max_kernel_buffer_bind_count = 2;
let source = device
.new_indirect_command_buffer(&descriptor, 1, ResourceOptions::shared())
.unwrap();
let at = source.indirect_compute_command_at(0).unwrap();
at.set_compute_pipeline_state(&mark).unwrap();
let offset = (2 * WINDOW * 4) as u64;
at.set_kernel_buffer(Some(&setup.params), offset, 0)
.unwrap();
at.set_kernel_buffer(Some(&setup.out), offset, 1).unwrap();
at.concurrent_dispatch_threads(Size::new(threads, 1, 1), Size::new(threads, 1, 1))
.unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.copy_indirect_command_buffer(&source, 0..1, &setup.icb, 2)
.unwrap();
blit.end_encoding().unwrap();
complete(&command_buffer);
mark.gpu_resource_id()
};
let taker = taken.then(|| flat_template(device));
if let Some(taker) = &taker {
assert_eq!(taker.gpu_resource_id(), id, "flat_sum's state takes the ID");
}
let before = dispatches_indirect(device);
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.resident(&mut encoder);
encoder
.execute_commands_in_buffer(&setup.icb, 0..COMMANDS)
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
let mut expected = expected(0..COMMANDS as usize);
for p in 0..threads as usize {
expected[2 * WINDOW + p] += base(2) * 1000 + p as u32;
}
assert_eq!(setup.output(), expected, "taken {taken}");
assert!(ran_flat(&command_buffer), "taken {taken}: on the GPU alone");
assert_eq!(
dispatches_indirect(device) - before,
COMMANDS * 3,
"taken {taken}: one indirect dispatch per command and state"
);
announced(device, messages, &[]);
});
}
}
/// A concurrent encoder's execution recorded with no barrier between its commands is recorded
/// again with them where the CPU sets a barrier in one of the buffer's records after the commit,
/// before its batch is submitted (the batch waits for an event the CPU signals after the set): the
@@ -646,45 +734,135 @@ fn predicated_executions_run_as_their_blocks_say() {
});
}
/// A checked execution (the caller's check runs in the host step), and one whose range is read
/// from a buffer, keep the host step, announced once; both run what Metal runs.
/// A state that may encode indirect commands (`icb_replay_encode`'s), made with
/// `supportIndirectCommandBuffers`: a command the CPU sets it on may name a state that encodes.
fn encoding_state(device: &Device) -> ComputePipelineState {
indirect_host_steps::state(device, "icb_replay_encode", true)
}
/// A check that counts its calls, and the count.
fn counting() -> (IndirectCommandCheck, Arc<AtomicUsize>) {
let calls = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&calls);
let check: IndirectCommandCheck = Box::new(move |_, _| {
counted.fetch_add(1, Ordering::SeqCst);
});
(check, calls)
}
/// An execution of the CPU's records, which `commit` records (no encoder made the buffer resident
/// for writing), runs the records as they stand when its batch is submitted, as Metal's execution
/// reads them as it runs: where the CPU resets command 0 after the commit, before the batch is
/// submitted (it waits for an event the test signals after the reset), a host step records the
/// execution again from the records then (each record read again), command 0 runs nothing and the
/// rest run; without the reset, the commit's recording runs, each record read once. Nothing is
/// announced but the split of a ragged grid the dispatches take.
#[test]
fn checked_and_indirect_range_executions_keep_the_host_step() {
fn the_cpu_s_writes_after_the_commit_run_where_the_batch_waits() {
on_device(|device, messages| {
let queue = device.new_command_queue().unwrap();
for form in ["checked", "indirect range"] {
for write in [false, true] {
let setup = Setup::new(device);
let event = device.new_shared_event().unwrap();
let command_buffer = queue.command_buffer().unwrap();
command_buffer
.encode_wait_for_event(EventRef::from(&event), 1)
.unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.resident(&mut encoder);
encoder
.execute_commands_in_buffer(&setup.icb, 0..COMMANDS)
.unwrap();
encoder.end_encoding().unwrap();
let before = device.work_counts().indirect_records_read;
command_buffer.commit().unwrap();
if write {
let command = setup.icb.indirect_compute_command_at(0).unwrap();
command.reset().unwrap();
}
event.set_signaled_value(1);
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
assert_eq!(
command_buffer.execution_report(),
Some(StatusReport::default())
);
let read = device.work_counts().indirect_records_read - before;
assert!(!setup.icb.gpu_written(), "write {write}");
let ran = if write { 1 } else { 0 };
assert_eq!(
setup.output(),
expected(ran..COMMANDS as usize),
"write {write}"
);
let reads = if write { 2 * COMMANDS } else { COMMANDS };
assert_eq!(read, reads, "write {write}: the records read");
}
announced(device, messages, &[Degradation::SplitDispatch]);
});
}
/// A checked execution's check is called only where what the buffer's records may hold leaves it
/// something to see (`IndirectCommandCheckNeeds`): with the flat states alone, which encode no
/// indirect commands, a check that looks for every kind is never called, and a range given as
/// such runs on the GPU alone, while one read from a buffer keeps the host step; once the CPU set
/// a state that may encode on a command outside the range, the host step of either calls it with
/// each command of the range, and a check that looks for nothing is still never called. Each runs
/// what Metal runs; the host step is announced once.
#[test]
fn checked_executions_call_their_check_where_it_may_see_something() {
on_device(|device, messages| {
let queue = device.new_command_queue().unwrap();
let (all, none) = (
IndirectCommandCheckNeeds::ALL,
IndirectCommandCheckNeeds::new(false, false),
);
let mut encoding = None;
for (encodes, needs, indirect) in [
(false, all, false),
(false, all, true),
(true, all, false),
(true, all, true),
(true, none, false),
(true, none, true),
] {
let setup = Setup::sized(device, COMMANDS + 1);
if encodes {
// Made only now: with it alive, the GPU-alone path would run its variant too.
let encoding = encoding.get_or_insert_with(|| encoding_state(device));
let outside = setup.icb.indirect_compute_command_at(COMMANDS).unwrap();
outside.set_compute_pipeline_state(encoding).unwrap();
}
let command_buffer = queue.command_buffer().unwrap();
setup.writable(&command_buffer);
let range = buffer_with(device, &[0, 0, 0, 0, COMMANDS as u8, 0, 0, 0]).unwrap();
let checked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (check, calls) = counting();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.resident(&mut encoder);
match form {
"checked" => {
let seen = std::sync::Arc::clone(&checked);
encoder
.execute_commands_in_buffer_checked(
&setup.icb,
0..COMMANDS,
Box::new(move |_, _| {
seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}),
metal2vulkan_runtime::IndirectCommandCheckNeeds::ALL,
)
.unwrap();
}
_ => encoder
.execute_commands_in_buffer_indirect(&setup.icb, &range, 0)
.unwrap(),
match indirect {
false => encoder.execute_commands_in_buffer_checked(
&setup.icb,
0..COMMANDS,
check,
needs,
),
true => encoder.execute_commands_in_buffer_indirect_checked(
&setup.icb, &range, 0, check, needs,
),
}
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
assert_eq!(setup.output(), expected(0..COMMANDS as usize), "{form}");
assert!(!ran_flat(&command_buffer), "{form}");
if form == "checked" {
// The check saw each command the step recorded.
assert!(checked.load(std::sync::atomic::Ordering::Relaxed) > 0);
let at = format!("encodes {encodes}, {needs:?}, indirect {indirect}");
let want = expected_of(COMMANDS + 1, 0..COMMANDS as usize);
assert_eq!(setup.output(), want, "{at}");
let called = encodes && needs == all;
let expected_calls = if called { COMMANDS as usize } else { 0 };
assert_eq!(calls.load(Ordering::SeqCst), expected_calls, "{at}");
if !encodes {
assert_eq!(ran_flat(&command_buffer), !indirect, "{at}");
} else if called {
assert!(!ran_flat(&command_buffer), "{at}");
}
}
// The check reads the commands, which answer the runtime's unique identifiers of their
@@ -694,3 +872,68 @@ fn checked_and_indirect_range_executions_keep_the_host_step() {
announced(device, messages, &kinds);
});
}
/// A checked execution `commit` recorded on the GPU alone, its check having nothing to see (the
/// flat states encode no indirect commands), takes the host step where the CPU sets a state that
/// may encode on a command after the commit, before the batch is submitted (it waits for an event
/// the test signals after the set): the step calls the check with each command of the range and
/// runs what Metal runs, in a serial and in a concurrent encoder (whose GPU-alone recording kept
/// what its batch's submission would record again). Without the set the check is never called and
/// the commands run on the GPU alone.
#[test]
fn a_check_given_something_to_see_after_the_commit_takes_the_host_step() {
on_device(|device, messages| {
let queue = device.new_command_queue().unwrap();
let mut encoding = None;
for (dispatch_type, set) in [
(DispatchType::Serial, false),
(DispatchType::Serial, true),
(DispatchType::Concurrent, true),
] {
let setup = Setup::sized(device, COMMANDS + 1);
let event = device.new_shared_event().unwrap();
let command_buffer = queue.command_buffer().unwrap();
setup.writable(&command_buffer);
command_buffer
.encode_wait_for_event(EventRef::from(&event), 1)
.unwrap();
let mut encoder = command_buffer
.compute_command_encoder_with_dispatch_type(dispatch_type)
.unwrap();
setup.resident(&mut encoder);
let (check, calls) = counting();
encoder
.execute_commands_in_buffer_checked(
&setup.icb,
0..COMMANDS,
check,
IndirectCommandCheckNeeds::new(false, true),
)
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
if set {
// Made after the commit, which recorded the states alive then.
let encoding = encoding.get_or_insert_with(|| encoding_state(device));
let outside = setup.icb.indirect_compute_command_at(COMMANDS).unwrap();
outside.set_compute_pipeline_state(encoding).unwrap();
}
event.set_signaled_value(1);
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
assert_eq!(
command_buffer.execution_report(),
Some(StatusReport::default())
);
let at = format!("{dispatch_type:?}, set {set}");
let want = expected_of(COMMANDS + 1, 0..COMMANDS as usize);
assert_eq!(setup.output(), want, "{at}");
let expected_calls = if set { COMMANDS as usize } else { 0 };
assert_eq!(calls.load(Ordering::SeqCst), expected_calls, "{at}");
assert_eq!(ran_flat(&command_buffer), !set, "{at}");
}
let identifiers = [Degradation::UnmeasuredUniqueIdentifier];
let kinds: Vec<Degradation> = STEPPED.iter().chain(&identifiers).copied().collect();
announced(device, messages, &kinds);
});
}
@@ -15,7 +15,7 @@ use metal2vulkan::bind::indirect_commands::COMMAND_BYTES;
use metal2vulkan::bind::ArgumentDescriptor;
use metal2vulkan::metal::{
BlendFactor, ColorWriteMask, DataType, IndexType, IndirectCommandType, PixelFormat,
PrimitiveType, ResourceUsage,
PrimitiveType, ResourceUsage, TextureUsage,
};
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, ComputePipelineDescriptor, MeshPipelineDescriptor,
@@ -24,12 +24,13 @@ use metal2vulkan::pipeline::{
use metal2vulkan::reflection::LinkedUseGap;
use metal2vulkan_devtools::{engine_dir, llvm_assemble, llvm_assemble_text};
use metal2vulkan_runtime::{
BlitCommandEncoder, ComputePipelineState, CpuCacheMode, Degradation, Device, DrawProblem,
EncodedComputeCommand, EncodedRenderCommand, Error, GpuAddress, HazardTrackingMode,
IndirectBufferBinding, IndirectCommand, IndirectCommandBuffer, IndirectCommandBufferDescriptor,
IndirectCommandBufferProblem, IndirectDispatch, IndirectDraw, Invalid, MetalError,
PipelineOptions, Problem, PurgeableState, Region, RenderPipelineState, ResourceId,
ResourceOptions, RuntimeGap, Size, StorageMode,
BlitCommandEncoder, Buffer, CommandBuffer, ComputePipelineState, CpuCacheMode, Degradation,
Device, DrawProblem, EncodedComputeCommand, EncodedRenderCommand, Error, EventRef, GpuAddress,
HazardTrackingMode, IndirectBufferBinding, IndirectCommand, IndirectCommandBuffer,
IndirectCommandBufferDescriptor, IndirectCommandBufferProblem, IndirectDispatch, IndirectDraw,
Invalid, LoadAction, MetalError, PipelineOptions, Problem, PurgeableState, Region,
RenderPassDescriptor, RenderPipelineState, ResourceId, ResourceOptions, RuntimeGap, Size,
StorageMode, StoreAction, TextureDescriptor,
};
fn invalid(call: &'static str, problem: Problem) -> Error {
@@ -380,8 +381,9 @@ fn creation_refuses_what_metal_refuses() {
assert_eq!(icb(device, &descriptor, 2).size(), 2);
}
// A buffer set past what a record holds is kept beside the records and read back with
// the record's slots, every slot the descriptor counts; a length past the record is still
// dropped, so the read-back lists the lengths a record holds.
// the record's slots, every slot the descriptor counts; a length past the record is kept
// where Metal keeps it, for its getter (past the last command's lengths here), and the
// read-back lists the lengths a record holds.
let [buffers, lengths, ..] = counts(64);
let wide = icb(device, &buffers, 1);
let set = wide.indirect_compute_command_at(0).unwrap();
@@ -397,6 +399,7 @@ fn creation_refuses_what_metal_refuses() {
let set = long.indirect_compute_command_at(0).unwrap();
set.set_threadgroup_memory_length(16, 63).unwrap();
set.set_threadgroup_memory_length(16, 30).unwrap();
assert_eq!(set.threadgroup_memory_length(63).unwrap(), Some(16));
let lengths = command(&long, 0).threadgroup_memory_lengths;
assert_eq!(lengths.len(), 31);
assert_eq!(lengths[30], 16);
@@ -583,7 +586,9 @@ fn a_command_keeps_a_buffer_offset_s_low_32_bits() {
/// lives, and none where it names none, as Metal's getter answers a released state's identifier
/// and 0 for none (measured by the consumer on an M3 Max): a command copied into another buffer,
/// which holds no state, names the state after the state and its source buffer are released,
/// while `pipeline` reads none; the copy's fresh command names none.
/// while `pipeline` reads none, and its identifier is the state's that held the ID as the copy
/// wrote it, after a render state took the ID too, as Metal's record holds the state its GPU
/// write resolved; the copy's fresh command names none.
#[test]
fn a_command_names_its_state_s_id_after_the_state_is_released() {
on_device(|device| {
@@ -616,7 +621,7 @@ fn a_command_names_its_state_s_id_after_the_state_is_released() {
assert_eq!(
command(&copied, 0).pipeline_unique_identifier,
Some(identifier),
"a record the GPU wrote: the live state of its ID"
"a record the GPU wrote: the state of its ID as it wrote it"
);
drop(state);
assert_eq!(
@@ -627,9 +632,18 @@ fn a_command_names_its_state_s_id_after_the_state_is_released() {
drop((set, source));
let read = command(&copied, 0);
assert_eq!(
read.pipeline_unique_identifier, None,
"a record the GPU wrote, naming an ID no state holds"
read.pipeline_unique_identifier,
Some(identifier),
"a record the GPU wrote, naming an ID no state holds: the released state's"
);
let taker = render_template_state(device, true);
assert_eq!(taker.gpu_resource_id(), id, "a render state takes the ID");
assert_eq!(
command(&copied, 0).pipeline_unique_identifier,
Some(identifier),
"the state the record held when the GPU wrote it, after another took its ID"
);
drop(taker);
assert!(
read.pipeline.is_none(),
"a released compute state reads as none"
@@ -895,7 +909,8 @@ fn dynamic_strides_read_back_as_set() {
/// What Metal's validation stops at a setter, or ends the process for, is refused typed, and an
/// imageblock side the record cannot hold is a gap. A dispatch of the kind a buffer's command types
/// lack, which Metal's validation stops but plain Metal runs, is set.
/// lack, which Metal's validation stops but plain Metal runs, is set, and so is a threadgroup
/// length at or past the descriptor's count, which plain Metal keeps.
#[test]
fn setters_refuse_what_metal_refuses() {
on_device(|device| {
@@ -953,13 +968,10 @@ fn setters_refuse_what_metal_refuses() {
Problem::IndexOutOfRange { index: 4, limit: 4 }
)
);
assert_eq!(
first.set_threadgroup_memory_length(16, 2).unwrap_err(),
invalid(
"set_threadgroup_memory_length",
Problem::IndexOutOfRange { index: 2, limit: 2 }
)
);
// A threadgroup length at or past the count is kept, as plain Metal keeps it
// (`threadgroup_lengths_are_kept_where_metal_keeps_them`).
first.set_threadgroup_memory_length(16, 2).unwrap();
assert_eq!(first.threadgroup_memory_length(2).unwrap(), Some(16));
assert_eq!(
first.set_imageblock_size(65536, 8).unwrap_err(),
Error::NotImplemented(RuntimeGap::IndirectImageblockSize {
@@ -1118,10 +1130,6 @@ pub(super) const UNMEASURED_IDENTIFIERS: [Degradation; 2] = [
Degradation::PlainStateUniqueIdentifier,
];
/// The kind a threadgroup length set past what a record holds takes
/// ([`commands_read_back_their_type_and_slots_past_the_record`]).
pub(super) const PAST_RECORD: [Degradation; 1] = [Degradation::IndirectValuePastRecord];
/// `getCommandType` answers the type of the dispatch or draw a record holds, none fresh and after
/// a reset (on an M4: `0x20`, `0x40`, 1 and 2, then 0). A buffer slot past the 32 a record holds,
/// below the descriptor's count, reads back as set, as Metal's getters answer every slot below the
@@ -1129,23 +1137,11 @@ pub(super) const PAST_RECORD: [Degradation; 1] = [Degradation::IndirectValuePast
/// descriptor of 64, carried by a GPU copy within the buffer, cleared by a GPU reset (one fill of
/// the records and one of the slots past them, no copy) and by the command's reset, and announcing
/// nothing. A copy into a buffer of another count carries the slots
/// both hold and clears the destination's past the source's. A threadgroup length at index 40,
/// which Metal keeps in storage not measured past about index 38, announces
/// `indirect-value-past-record` once a device and reads back as fresh.
/// both hold and clears the destination's past the source's.
#[test]
fn commands_read_back_their_type_and_slots_past_the_record() {
notices::on_device(|device, messages| {
messages.take_notices();
let past = |messages: &Messages| -> Vec<Degradation> {
let notices = messages.take_notices();
counts(&notices);
notices
.into_iter()
.filter_map(|message| message.degradation)
.map(|notice| notice.degradation)
.filter(|kind| PAST_RECORD.contains(kind))
.collect()
};
let queue = device.new_command_queue().unwrap();
let blit = |work: &dyn Fn(&mut metal2vulkan_runtime::BlitCommandEncoder)| {
let command_buffer = queue.command_buffer().unwrap();
@@ -1174,16 +1170,16 @@ fn commands_read_back_their_type_and_slots_past_the_record() {
command(&made, 0).command_type,
IndirectCommandType::CONCURRENT_DISPATCH_THREADS
);
assert_eq!(past(messages), []);
let buffer = device.new_buffer(256, ResourceOptions::shared()).unwrap();
let address = buffer.gpu_address().0;
messages.take_notices();
set.set_kernel_buffer(Some(&buffer), 0x10, 40).unwrap();
set.set_kernel_buffer(None, 0x30, 63).unwrap();
assert_eq!(past(messages), [], "a buffer past the record is kept");
set.set_threadgroup_memory_length(0x200, 40).unwrap();
assert_eq!(past(messages), PAST_RECORD);
set.set_threadgroup_memory_length(0x300, 41).unwrap();
assert_eq!(past(messages), [], "once a device");
assert_eq!(
counts(&messages.take_notices()),
Default::default(),
"a buffer past the record is kept"
);
let slots = |read: &EncodedComputeCommand| {
[39, 40, 63, 64].map(|at| read.kernel_buffer_address(at))
};
@@ -1259,7 +1255,174 @@ fn commands_read_back_their_type_and_slots_past_the_record() {
render_command(&render, 0).command_type,
IndirectCommandType::empty()
);
assert_eq!(past(messages), []);
});
}
/// A probe's case of [`threadgroup_lengths_are_kept_where_metal_keeps_them`]: the descriptor's
/// count, the range read ([`kept_lengths`]), the command that sets `1000 + index` at `index`,
/// `index`, and the indices each command's getter answers it at.
type LengthCase = (u32, u64, u64, u32, [&'static [u64]; 3]);
/// Each command's threadgroup lengths at 0 to `range` (exclusive) that are not 0, as the M3 Max
/// probes printed them: `(index, length)` a command, of commands 0 to 2.
fn kept_lengths(icb: &IndirectCommandBuffer, range: u64) -> [Vec<(u64, u32)>; 3] {
[0, 1, 2].map(|index| {
let command = icb.indirect_compute_command_at(index).unwrap();
(0..range)
.filter_map(|at| match command.threadgroup_memory_length(at).unwrap() {
Some(0) => None,
Some(length) => Some((at, length)),
None => panic!("command {index}: no length at {at}"),
})
.collect()
})
}
/// Threadgroup lengths are kept where Metal keeps them (an M3 Max, macOS 27.0.1, buffers of 3
/// commands): 38 a command, of one array, whatever the descriptor's count (8, 31, 32, 40, 64,
/// 100), so a length set at 38 or more of a command is a later command's and a command's getter
/// past 37 answers a later command's; one at 31 to 37 is kept for the getter alone, one at or
/// past the count is kept as well, and one past the last command's 38 reads back as set (at
/// 1000 of the last command), changing no command's record; the getter takes the index's low 32
/// bits. A command's reset, on the CPU or by a blit, clears its 38 and leaves the next command's;
/// a blit's copy of a command carries its 38. None announces anything.
#[test]
fn threadgroup_lengths_are_kept_where_metal_keeps_them() {
notices::on_device(|device, messages| {
let made = |count: u32| {
let mut descriptor = compute_descriptor();
descriptor.max_kernel_threadgroup_memory_bind_count = count;
icb(device, &descriptor, 3)
};
messages.take_notices();
let cases: [LengthCase; 14] = [
(8, 88, 1, 5, [&[43], &[5], &[]]),
(8, 88, 2, 5, [&[81], &[43], &[5]]),
(8, 88, 1, 10, [&[48], &[10], &[]]),
(31, 111, 1, 30, [&[68], &[30], &[]]),
(32, 112, 1, 31, [&[69], &[31], &[]]),
(32, 112, 0, 31, [&[31], &[], &[]]),
(32, 112, 2, 31, [&[107], &[69], &[31]]),
(64, 144, 1, 30, [&[68], &[30], &[]]),
(64, 144, 1, 70, [&[108], &[70], &[32]]),
(64, 144, 2, 63, [&[139], &[101], &[63]]),
(64, 72, 1, 38, [&[], &[38], &[0]]),
(64, 72, 1, 50, [&[], &[50], &[12]]),
(40, 48, 1, 39, [&[], &[39], &[1]]),
(100, 108, 1, 90, [&[], &[90], &[52]]),
];
for (count, range, command, index, at) in cases {
let icb = made(count);
let set = icb.indirect_compute_command_at(command).unwrap();
set.set_threadgroup_memory_length(1000 + index, index)
.unwrap();
let expected: [Vec<(u64, u32)>; 3] =
at.map(|at| at.iter().map(|&at| (at, 1000 + index)).collect());
assert_eq!(
kept_lengths(&icb, range),
expected,
"{count} lengths, command {command} set at {index}"
);
}
// Far reads, and past the last command's lengths.
let icb = made(64);
let first = icb.indirect_compute_command_at(0).unwrap();
icb.indirect_compute_command_at(1)
.unwrap()
.set_threadgroup_memory_length(1030, 30)
.unwrap();
assert_eq!(first.threadgroup_memory_length(200).unwrap(), Some(0));
let icb = made(8);
let first = icb.indirect_compute_command_at(0).unwrap();
first.set_threadgroup_memory_length(1001, 1).unwrap();
first.set_threadgroup_memory_length(1005, 5).unwrap();
let far = [(1 << 32) + 1, (1 << 32) + 5, (1 << 33) + 5];
assert_eq!(
far.map(|at| first.threadgroup_memory_length(at).unwrap()),
[Some(1001), Some(1005), Some(1005)],
"the index's low 32 bits"
);
let icb = made(8);
let last = icb.indirect_compute_command_at(2).unwrap();
for at in [40, 100, 300, 1000] {
last.set_threadgroup_memory_length(7777, at).unwrap();
assert_eq!(
last.threadgroup_memory_length(u64::from(at)).unwrap(),
Some(7777)
);
}
for index in 0..3 {
let lengths = command(&icb, index).threadgroup_memory_lengths;
assert!(
lengths.iter().all(|&length| length == 0),
"{index}: {lengths:?}"
);
}
// Resets and copies, of 64 lengths, read as the probes read them (0 to 71).
let queue = device.new_command_queue().unwrap();
let blit = |work: &dyn Fn(&mut metal2vulkan_runtime::BlitCommandEncoder)| {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
work(&mut blit);
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
};
let set_three = |icb: &IndirectCommandBuffer| {
let second = icb.indirect_compute_command_at(1).unwrap();
for (length, at) in [(1035, 35), (1038, 38), (1003, 3)] {
second.set_threadgroup_memory_length(length, at).unwrap();
}
assert_eq!(
kept_lengths(icb, 72),
[
vec![(41, 1003)],
vec![(3, 1003), (35, 1035), (38, 1038)],
vec![(0, 1038)]
]
);
};
let after_reset = [vec![], vec![(38, 1038)], vec![(0, 1038)]];
let icb = made(64);
set_three(&icb);
icb.indirect_compute_command_at(1).unwrap().reset().unwrap();
assert_eq!(kept_lengths(&icb, 72), after_reset, "the command's reset");
let icb = made(64);
set_three(&icb);
blit(&|blit| blit.reset_commands_in_buffer(&icb, 1..2).unwrap());
assert_eq!(kept_lengths(&icb, 72), after_reset, "a blit's reset");
let icb = made(64);
set_three(&icb);
blit(&|blit| {
blit.copy_indirect_command_buffer(&icb, 1..2, &icb, 0)
.unwrap()
});
assert_eq!(
kept_lengths(&icb, 72),
[
vec![(3, 1003), (35, 1035), (41, 1003)],
vec![(3, 1003), (35, 1035), (38, 1038)],
vec![(0, 1038)]
],
"a blit's copy"
);
let icb = made(64);
let last = icb.indirect_compute_command_at(2).unwrap();
last.set_threadgroup_memory_length(1038, 38).unwrap();
last.set_threadgroup_memory_length(1045, 45).unwrap();
assert_eq!(
kept_lengths(&icb, 72),
[vec![], vec![], vec![(38, 1038), (45, 1045)]],
"past the last command's"
);
assert_eq!(
counts(&messages.take_notices()),
Default::default(),
"nothing announced"
);
});
}
@@ -1419,10 +1582,10 @@ fn identifier_notices(messages: &Messages) -> Vec<Degradation> {
.collect()
}
/// Which identifiers answer Metal's number: an indirect command buffer made before its device
/// opened a command encoder answers it quietly, as does a command naming no state (0); a buffer
/// made after one, and a state made with indirect command buffer support, announce
/// `unmeasured-unique-identifier` at their first answer, and a plain state
/// Which identifiers answer Metal's number: an indirect command buffer answers it quietly, past
/// the pieces Metal's encoders took ([`buffer_identifiers_follow_metal_s_encoders`]), as does a
/// command naming no state (0); a state made with indirect command buffer support announces
/// `unmeasured-unique-identifier` at its first answer, and a plain state
/// `plain-state-unique-identifier`, each once a device. A compute state with indirect command
/// buffer support starts one step into Metal's range, `2^36 + 0xc0`.
#[test]
@@ -1446,10 +1609,16 @@ fn identifiers_not_metal_s_are_announced_once() {
assert_eq!(first.unique_identifier(), BASE + 0x1_8000);
assert_eq!(identifier_notices(messages), [], "made before the encoder");
let later = icb(device, &descriptor, 1);
assert_eq!(later.unique_identifier(), BASE + 0x2_0000, "the rule still");
assert_eq!(identifier_notices(messages), [kind]);
assert_eq!(
later.unique_identifier(),
BASE + 0x6_0000,
"past the blit encoder's pieces"
);
assert_eq!(identifier_notices(messages), [], "Metal's number");
let state = template_state(device, true);
assert_eq!(state.unique_identifier(), BASE + 0xc0);
assert_eq!(identifier_notices(messages), [kind]);
assert_eq!(state.unique_identifier(), BASE + 0xc0);
assert_eq!(identifier_notices(messages), [], "once a device");
let plain = template_state(device, false).unique_identifier();
assert!(plain > BASE + 0xc0, "{plain:#x}");
@@ -1475,6 +1644,188 @@ fn identifiers_not_metal_s_are_announced_once() {
});
}
/// A buffer of one command whose command runs the template kernel (its parameters at offset
/// 16 of `params`, its output `out` with a stride of 4), as
/// [`a_command_keeps_a_buffer_offset_s_low_32_bits`] sets it.
fn executable(device: &Device, params: &Buffer, out: &Buffer) -> IndirectCommandBuffer {
let mut descriptor = compute_descriptor();
descriptor.support_dynamic_attribute_stride = true;
let made = icb(device, &descriptor, 1);
let command = made.indirect_compute_command_at(0).unwrap();
command
.set_compute_pipeline_state(&template_state(device, true))
.unwrap();
command.set_kernel_buffer(Some(params), 16, 0).unwrap();
command
.set_kernel_buffer_with_stride(Some(out), 0, 4, 1)
.unwrap();
command
.concurrent_dispatch_threadgroups(Size::new(1, 1, 1), Size::new(4, 1, 1))
.unwrap();
made
}
/// Encode into `command_buffer` a compute encoder that executes `icb`'s command, which reads
/// `params` and writes `out` ([`executable`]).
fn execute_one(
command_buffer: &CommandBuffer,
icb: &IndirectCommandBuffer,
params: &Buffer,
out: &Buffer,
) {
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(params.as_resource(), ResourceUsage::READ)
.unwrap();
encoder
.use_resource(out.as_resource(), ResourceUsage::WRITE)
.unwrap();
encoder.execute_commands_in_buffer(icb, 0..1).unwrap();
encoder.end_encoding().unwrap();
}
/// An indirect command buffer's `uniqueIdentifier` follows the pieces of Metal's range its own
/// encoders take (an M3 Max, macOS 27.0.1, the probes' sequences, buffers of 32 KiB from
/// `2^36 + 0x18000`), quietly: a blit encoder 256 KiB at its opening, its command 32 KiB more as
/// its command buffer is scheduled, as a compute encoder's execution does, once a device; an empty
/// compute encoder, or one that only makes a buffer resident, nothing. A render encoder takes 384
/// KiB at its opening, 192 of them a blit encoder's too; its command buffer's run takes what the
/// runtime does not model, so a buffer made after announces `unmeasured-unique-identifier`. A
/// released buffer's range stays taken while a command buffer that executes it may run, and is
/// free again once it completed.
#[test]
fn buffer_identifiers_follow_metal_s_encoders() {
const BASE: u64 = 1 << 36;
let at = |icb: &IndirectCommandBuffer| icb.unique_identifier() - BASE;
let run = |device: &Device, encode: &dyn Fn(&CommandBuffer)| {
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
encode(&command_buffer);
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
};
let params = |device: &Device| {
let words = [0u32, 0, 0, 0, 7, 100];
buffer_with(
device,
&words
.iter()
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>(),
)
.unwrap()
};
let one = |device: &Device| icb(device, &compute_descriptor(), 1);
// Compute: nothing for an empty encoder or a residency alone; 32 KiB for an execution.
notices::on_device(|device, messages| {
messages.take_notices();
let (params, out) = (
params(device),
device.new_buffer(64, ResourceOptions::shared()).unwrap(),
);
let first = executable(device, &params, &out);
assert_eq!(at(&first), 0x1_8000);
run(device, &|command_buffer| {
let encoder = command_buffer.compute_command_encoder().unwrap();
encoder.end_encoding().unwrap();
});
run(device, &|command_buffer| {
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(out.as_resource(), ResourceUsage::READ)
.unwrap();
encoder.end_encoding().unwrap();
});
assert_eq!(at(&one(device)), 0x2_0000, "no compute work");
run(device, &|command_buffer| {
execute_one(command_buffer, &first, &params, &out)
});
run(device, &|command_buffer| {
execute_one(command_buffer, &first, &params, &out)
});
let after = one(device);
assert_eq!(at(&after), 0x2_8000, "an execution's 32 KiB, once");
assert_eq!(identifier_notices(messages), []);
});
// Blit: 256 KiB at the opening; a fill's 32 KiB as it is scheduled.
notices::on_device(|device, messages| {
messages.take_notices();
let first = one(device);
run(device, &|command_buffer| {
command_buffer
.blit_command_encoder()
.unwrap()
.end_encoding()
.unwrap();
});
assert_eq!(at(&one(device)), 0x6_0000, "an empty blit encoder");
let filled = device.new_buffer(256, ResourceOptions::shared()).unwrap();
run(device, &|command_buffer| {
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(&filled, 0..256, 1).unwrap();
blit.end_encoding().unwrap();
});
assert_eq!(at(&one(device)), 0x6_8000, "a fill's 32 KiB");
drop(first);
assert_eq!(identifier_notices(messages), []);
});
// Render: 384 KiB at the opening; past the model once its command buffer is scheduled.
notices::on_device(|device, messages| {
messages.take_notices();
let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 64, 64, false);
target.usage = TextureUsage::RENDER_TARGET;
let target = device.new_texture(&target).unwrap();
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(target);
color.load_action = LoadAction::Clear;
color.store_action = StoreAction::Store;
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let encoder = command_buffer.render_command_encoder(&pass).unwrap();
let inside = one(device);
assert_eq!(at(&inside), 0x7_8000, "made while the encoder is open");
assert_eq!(identifier_notices(messages), []);
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
let _after = one(device).unique_identifier();
assert_eq!(
identifier_notices(messages),
[Degradation::UnmeasuredUniqueIdentifier]
);
});
// A released buffer a command buffer executes keeps its range until that completes.
notices::on_device(|device, messages| {
messages.take_notices();
let (params, out) = (
params(device),
device.new_buffer(64, ResourceOptions::shared()).unwrap(),
);
let executed = executable(device, &params, &out);
let second = one(device);
assert_eq!((at(&executed), at(&second)), (0x1_8000, 0x2_0000));
let event = device.new_shared_event().unwrap();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
command_buffer
.encode_wait_for_event(EventRef::from(&event), 1)
.unwrap();
execute_one(&command_buffer, &executed, &params, &out);
command_buffer.commit().unwrap();
drop(executed);
let while_held = one(device);
assert_eq!(at(&while_held), 0x2_8000, "held while it may run");
event.set_signaled_value(1);
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
assert_eq!(at(&one(device)), 0x1_8000, "free once it completed");
assert_eq!(identifier_notices(messages), []);
});
}
/// A render command's setters write what Metal's getters read back: its
/// pipeline state, kept alive while the command names it; each vertex and fragment buffer's
/// address plus its offset, whatever the offset; a draw's values (the record's low 32 bits); a
@@ -62,8 +62,8 @@ const CHAIN: &str = "saturating-halving-and-wide-product-integers-at-their-edges
/// A kernel whose `[[stage_in]]` layout's stride is `MTLBufferLayoutStrideDynamic`.
const DYNAMIC: &str = "stage-in-of-a-dynamic-stride-layout-of-an-executed-command-template";
/// The kind [`a_host_step_runs_a_released_state_s_program_and_announces_what_it_cannot_tell`]
/// takes where a host step cannot run what Metal runs.
/// The kind [`a_record_the_gpu_wrote_runs_the_state_its_id_named_as_it_was_written`] takes where
/// a host step cannot run what Metal runs.
pub(super) const RELEASED_STATES: [Degradation; 1] = [Degradation::ReleasedCommandState];
/// Run `test` on a validated device of the lane, then fail on any validation message.
@@ -953,32 +953,33 @@ fn a_command_naming_a_released_state_runs_its_program() {
}
}
/// A host step, which runs records the GPU may write, cannot tell the GPU's write of an ID from
/// the CPU's, nor run a released state's program it does not hold. Command 0 is encoded with a
/// state, and copied to command 1 by a blit (the GPU writes it, so the buffer's executions take
/// the host step), which then gets buffers of its own; the program releases the state.
/// A record the GPU wrote runs the state that held its ID as the GPU wrote it, released since or
/// not, as Metal's runs it (measured on an M3 Max: `released_programs.rs`); a host step, which runs
/// records the GPU may write, cannot tell the GPU's write of an ID from the CPU's. Command 0 is
/// encoded with a state, and copied to command 1 by a blit (the GPU writes it, so the buffer's
/// executions take the host step or the GPU alone), which then gets buffers of its own; the
/// program releases the state.
///
/// - No state takes the ID: command 0 runs the released state's program, as Metal's runs it
/// whoever wrote the ID, unannounced. Command 1 names the ID with no state set on it on the
/// CPU: Metal runs the released state's program, which only command 0 holds, so it runs
/// nothing, announced once for two executions (`Degradation::ReleasedCommandState`), and at
/// each on a device whose options ask for the kind at each occurrence.
/// - A compute state of another interface ([`CHAIN`]'s kernel) takes the ID: command 0 runs the
/// released state's program, as Metal runs the command the CPU encoded, announced, as Metal
/// runs the new state for a record the GPU wrote; command 1 runs the new state, as Metal's
/// record the GPU wrote does, unannounced.
///
/// On a device with generated commands, an execution of command 0 takes the host step too: the GPU
/// alone would run the ID's holder.
/// - No state takes the ID: both commands run the released state's program, unannounced.
/// - A compute state of another interface ([`CHAIN`]'s kernel) takes the ID: both still run the
/// released state's program, as Metal runs the command the CPU encoded and the record its copy
/// wrote before the new state took the ID, unannounced.
/// - The new state takes the ID and an encoder then makes the buffer resident for writing, so
/// the GPU may write command 0's record while the new state holds the ID: command 0 runs the
/// released state's program, as Metal runs the command the CPU encoded, announced once for two
/// executions (`Degradation::ReleasedCommandState`), as Metal runs the new state for a record
/// the GPU wrote then; and at each on a device whose options ask for the kind at each
/// occurrence.
#[test]
fn a_host_step_runs_a_released_state_s_program_and_announces_what_it_cannot_tell() {
let run = |device: &Device, messages: &Messages, taken: bool, times: usize| {
fn a_record_the_gpu_wrote_runs_the_state_its_id_named_as_it_was_written() {
// `rewritable`: an encoder makes the buffer resident for writing after the new state took the
// ID, and command 0 alone runs.
let run = |device: &Device, messages: &Messages, taken: bool, rewritable: bool| {
let case = public_case(RAGGED).unwrap();
let resources = CaseResources::new(device, &case).unwrap();
let sets: Vec<_> = (0..2)
.map(|_| bound_buffers(device, &case.compute, &resources).unwrap())
.collect();
let initial = output(&case.compute, &sets[1]);
let icb = icb(device, 2, false);
let queue = device.new_command_queue().unwrap();
let id = {
@@ -1001,22 +1002,37 @@ fn a_host_step_runs_a_released_state_s_program_and_announces_what_it_cannot_tell
"the state made after takes the ID"
);
}
// The case's kernel adds to its output, as its Metal output is one run's: `check` reads
// the output after the first execution.
let execute = |range: std::ops::Range<u64>, check: &dyn Fn()| {
for run in 0..times {
if rewritable {
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(icb.as_resource(), ResourceUsage::WRITE)
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
}
// The case's kernel adds to its output, as its Metal output is one run's: each command's
// output is read after its first execution.
let execute = |command: usize| {
for run in 0..2 {
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
for buffers in &sets {
make_resident(&mut encoder, buffers, &resources);
}
let at = command as u64;
encoder
.execute_commands_in_buffer(&icb, range.clone())
.execute_commands_in_buffer(&icb, at..at + 1)
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
if run == 0 {
check();
assert_eq!(
output(&case.compute, &sets[command]),
case.metal_output,
"taken {taken}, rewritable {rewritable}: command {command} ran the \
released state's program"
);
}
}
counts(&messages.take_notices())
@@ -1024,32 +1040,24 @@ fn a_host_step_runs_a_released_state_s_program_and_announces_what_it_cannot_tell
.copied()
.unwrap_or(0)
};
let first = execute(0..1, &|| {
assert_eq!(output(&case.compute, &sets[0]), case.metal_output);
});
let second = execute(1..2, &|| {
if !taken {
assert_eq!(
output(&case.compute, &sets[1]),
initial,
"command 1 ran nothing"
);
}
});
[first, second]
let commands = if rewritable { 0..1 } else { 0..2 };
commands.map(execute).collect::<Vec<usize>>()
};
on_device(|device, messages| {
assert_eq!(run(device, messages, false, 2), [0, 1]);
assert_eq!(run(device, messages, false, false), [0, 0]);
});
on_device(|device, messages| {
assert_eq!(run(device, messages, true, 2), [1, 0]);
assert_eq!(run(device, messages, true, false), [0, 0]);
});
on_device(|device, messages| {
assert_eq!(run(device, messages, true, true), [1]);
});
// Asked for at each occurrence: each execution announces it.
let each = |options: &mut DeviceOptions| {
options.announce_each = RELEASED_STATES.into_iter().collect();
};
on_device_with(each, |device, messages| {
assert_eq!(run(device, messages, false, 2), [0, 2]);
assert_eq!(run(device, messages, true, true), [2]);
});
}
@@ -16,10 +16,15 @@
//! - a sticky encoding fault in the header runs no command, and the execution report says so;
//! - an execution reads its range from a buffer as it runs;
//! - a checked execution's host step checks each command before it records any, from the records
//! it read once;
//! it read once; `commit` checks the CPU's records it records the same way, where a state the
//! records may name may encode, and never where none may;
//! - the blit encoder's copy, reset and optimize act on the commands as they run;
//! - a record the kernel wrote runs the state its ID named as it wrote it, after the program
//! released it and after another state took its ID; where the state was released before the
//! buffer could be written, nothing, announced;
//! - a kernel reaches the buffer made last with the ID it encodes through, placed or not, and
//! none once that one is gone;
//! none once that one is gone, the buffer at an ID a reservation leaves next, and an ID's
//! records where an earlier ID's run past their start;
//! - a command buffer's executed-commands handler sees each execution where its records are read:
//! in `commit` for the CPU's, in the host step (or on the GPU alone) for the kernel's, with each
//! command's state's ability to encode indirect commands and the buffers made resident for
@@ -35,7 +40,9 @@
use super::degrade_notices::{
assert_made_once, counts, forced, on_device_with, shared_in_system_memory,
};
use super::generated_executions::flat_template;
use super::host_memory::{gpu_fill, no_copy, Mapping, GUEST_PAGE};
use super::indirect_executions::RELEASED_STATES;
use super::resource_ids::DELAYED_DEALLOCATORS as DELAYED;
use super::{buffer_with, read_buffer, WAIT};
use crate::air_library::AirLibrary;
@@ -49,10 +56,9 @@ use metal2vulkan_runtime::{
Error, EventRef, ExecutedCommands, ExecutedCommandsHandler, ExecutedPipeline, Execution,
IdPlacement, IndirectCommand, IndirectCommandBuffer, IndirectCommandBufferDescriptor,
IndirectCommandBufferProblem, IndirectCommandCheckNeeds, Invalid, PipelineOptions, Problem,
RecordsRead, ResourceId, ResourceOptions, Size,
RecordsRead, ResourceId, ResourceIdKind, ResourceOptions, Size,
};
use std::ptr::NonNull;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::time::Instant;
@@ -237,6 +243,15 @@ impl Setup {
}
}
/// The setup with its template released, the writer's state in its place: the argument
/// buffer still names the template's ID, which a state made after may take.
fn releasing_template(self) -> Setup {
Setup {
template: self.writer.clone(),
..self
}
}
/// `out`, which the commands write.
pub(super) fn out(&self) -> &Buffer {
&self.out
@@ -251,13 +266,18 @@ impl Setup {
/// A buffer of `COMMANDS` commands of both dispatch kinds with `bind_count` kernel buffers and
/// one threadgroup length.
fn commands_buffer(device: &Device, bind_count: u32) -> IndirectCommandBuffer {
commands_buffer_of(device, bind_count, COMMANDS)
}
/// [`commands_buffer`] of `count` commands.
fn commands_buffer_of(device: &Device, bind_count: u32, count: u64) -> IndirectCommandBuffer {
let mut descriptor = IndirectCommandBufferDescriptor::new();
descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH
.union(IndirectCommandType::CONCURRENT_DISPATCH_THREADS);
descriptor.max_kernel_buffer_bind_count = bind_count;
descriptor.max_kernel_threadgroup_memory_bind_count = 1;
device
.new_indirect_command_buffer(&descriptor, COMMANDS, ResourceOptions::shared())
.new_indirect_command_buffer(&descriptor, count, ResourceOptions::shared())
.unwrap()
}
@@ -423,9 +443,12 @@ fn commands_a_kernel_writes_run_after_it() {
/// step calls the check once for each command it records, in order, with the command as
/// `IndirectCommandBuffer::commands` reads it (each a dispatch), before it records any: the
/// commands' windows of `out` are all still zero at every call. An execution of the CPU's records
/// in a buffer no encoder made resident for writing, which `commit` records, never calls it, and
/// both run as their plain forms run. The commands the check reads answer the runtime's unique
/// identifiers of their states, which the device announces as the getter does.
/// in a buffer no encoder made resident for writing, which `commit` records, calls it there, on
/// the committing thread before `commit` returns, with each command, where the CPU set a state
/// that may encode on one of them (since replaced by the template); where no state the records
/// may name may, never. All run as their plain forms run. The commands the check reads answer
/// the runtime's unique identifiers of their states, which the device announces as the getter
/// does.
#[test]
fn a_checked_execution_checks_each_written_command_before_its_step_records_it() {
on_device_forcing(&[Degradation::UnmeasuredUniqueIdentifier], |device| {
@@ -469,34 +492,60 @@ fn a_checked_execution_checks_each_written_command_before_its_step_records_it()
every,
"each command, before any runs"
);
// The CPU's records, recorded at the commit: no call.
let setup = Setup::new(device, 2);
setup.write_on_the_cpu();
let calls = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&calls);
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(setup.params.as_resource(), ResourceUsage::READ)
.unwrap();
encoder
.use_resource(setup.out.as_resource(), ResourceUsage::WRITE)
.unwrap();
encoder
.execute_commands_in_buffer_checked(
&setup.icb,
0..COMMANDS,
Box::new(move |_, _| {
counted.fetch_add(1, Ordering::SeqCst);
}),
IndirectCommandCheckNeeds::ALL,
)
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
assert!(!setup.icb.gpu_written());
assert_eq!(setup.output(), expected(), "the CPU's records run");
assert_eq!(calls.load(Ordering::SeqCst), 0, "no host step, no check");
// The CPU's records, recorded at the commit: checked there where a state they may name
// may encode.
let encoding = state(device, "icb_replay_encode", true);
for encodes in [false, true] {
let setup = Setup::new(device, 2);
if encodes {
let command = setup.icb.indirect_compute_command_at(0).unwrap();
command.set_compute_pipeline_state(&encoding).unwrap();
}
setup.write_on_the_cpu();
let seen: Arc<Mutex<Vec<(u64, std::thread::ThreadId)>>> = Arc::default();
let log = Arc::clone(&seen);
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(setup.params.as_resource(), ResourceUsage::READ)
.unwrap();
encoder
.use_resource(setup.out.as_resource(), ResourceUsage::WRITE)
.unwrap();
encoder
.execute_commands_in_buffer_checked(
&setup.icb,
0..COMMANDS,
Box::new(move |index, _| {
log.lock()
.unwrap()
.push((index, std::thread::current().id()));
}),
IndirectCommandCheckNeeds::ALL,
)
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
let at_commit = seen.lock().unwrap().clone();
wait(&command_buffer);
assert!(!setup.icb.gpu_written());
assert_eq!(
setup.output(),
expected(),
"the CPU's records run, encodes {encodes}"
);
let committing = std::thread::current().id();
let every: Vec<(u64, std::thread::ThreadId)> = match encodes {
true => (0..COMMANDS).map(|index| (index, committing)).collect(),
false => Vec::new(),
};
assert_eq!(at_commit, every, "checked in `commit`, encodes {encodes}");
assert_eq!(
*seen.lock().unwrap(),
every,
"and only there, encodes {encodes}"
);
}
});
}
@@ -580,6 +629,59 @@ fn a_kernel_writes_the_buffer_that_holds_the_id_now() {
});
}
/// A record a kernel wrote runs the state its ID named as the kernel wrote it, released since or
/// not, as Metal's runs it (measured on an M3 Max, `released_programs.rs`): where the program
/// releases the template after the kernel wrote the commands, they run the template's program,
/// and so they do after a state made after (the flat template of `generated_executions`) took its
/// ID, unannounced. Where the program released the template before any command buffer that may
/// write the buffer was encoded, the buffer keeps no program of it: Metal runs it, the commands
/// run nothing, announced (`Degradation::ReleasedCommandState`).
#[test]
fn commands_a_kernel_wrote_run_the_state_their_id_named_then() {
for taken in [false, true] {
on_device(|device| {
let queue = device.new_command_queue().unwrap();
let setup = Setup::new(device, 2);
let id = setup.template.gpu_resource_id();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.write(&mut encoder);
encoder.end_encoding().unwrap();
complete(&command_buffer);
let setup = setup.releasing_template();
let taker = taken.then(|| flat_template(device));
if let Some(taker) = &taker {
assert_eq!(
taker.gpu_resource_id(),
id,
"the flat template takes the ID"
);
}
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.execute(&mut encoder);
encoder.end_encoding().unwrap();
complete(&command_buffer);
assert_eq!(setup.output(), expected(), "taken {taken}");
});
}
on_device_forcing(&RELEASED_STATES, |device| {
let queue = device.new_command_queue().unwrap();
let setup = Setup::new(device, 2).releasing_template();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.write(&mut encoder);
setup.execute(&mut encoder);
encoder.end_encoding().unwrap();
complete(&command_buffer);
assert_eq!(
setup.output(),
expected_in(0..0),
"the commands ran nothing"
);
});
}
/// A kernel encoding through an ID reaches the buffer made last with it, placed or not, as
/// Metal's does (`r_*`): a buffer placed at the setup's buffer's ID takes it,
/// so the kernel writes the placed buffer's commands and the setup's buffer keeps fresh ones,
@@ -653,6 +755,106 @@ fn a_kernel_reaches_the_buffer_made_last_with_its_id() {
});
}
/// A kernel encoding through the ID a reservation leaves next reaches its buffer's records, and
/// the commands it writes run, as Metal's do (on an M3 Max, each buffer made past a reservation
/// of 2^23 + 5, 2^30 + 5 or 2^31 - 2 ran), up to the last ID, 2^31 - 1, whose records start 2^62
/// bytes below 2^64.
#[test]
fn a_kernel_reaches_the_records_of_a_buffer_past_a_reservation() {
for reserved in [(1 << 23) + 5, (1 << 26) - 2, (1 << 26) + 5, (1 << 31) - 2] {
on_device(|device| {
device
.reserve_resource_ids(
ResourceIdKind::IndirectCommandBuffer,
&[ResourceId(reserved)],
)
.unwrap();
let setup = Setup::new(device, 2);
assert_eq!(setup.icb.gpu_resource_id(), ResourceId(reserved + 1));
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
setup.write(&mut encoder);
setup.execute(&mut encoder);
encoder.end_encoding().unwrap();
complete(&command_buffer);
assert_eq!(setup.output(), expected(), "{reserved}");
});
}
}
/// A kernel reaches each ID's records at their start, however far an earlier ID's run, as Metal
/// makes and runs buffers of any length past a reservation (on an M3 Max, 2^22 commands at
/// 2^26 + 6): the records of ID r + 1, 955,300 commands (past 2^31 bytes), run past ID r + 2's
/// start. Through r + 2 the kernel writes r + 2's commands, which run, and r + 1's stay fresh;
/// with r + 2's buffer not resident, its writes miss, which the execution report counts, and
/// reach none of r + 1's records where r + 2's would start.
#[test]
fn a_kernel_reaches_an_id_s_records_where_an_earlier_id_s_run_past_them() {
on_device(|device| {
let reserved = (1 << 26) + 5;
device
.reserve_resource_ids(
ResourceIdKind::IndirectCommandBuffer,
&[ResourceId(reserved)],
)
.unwrap();
let count = 955_300;
let long = commands_buffer_of(device, 2, count);
assert_eq!(long.gpu_resource_id(), ResourceId(reserved + 1));
let setup = Setup::new(device, 2);
assert_eq!(setup.icb.gpu_resource_id(), ResourceId(reserved + 2));
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(long.as_resource(), ResourceUsage::WRITE)
.unwrap();
setup.write(&mut encoder);
setup.execute(&mut encoder);
encoder.end_encoding().unwrap();
complete(&command_buffer);
assert_eq!(setup.output(), expected(), "through r + 2");
// The records about r + 2's start, 2^31 bytes into r + 1's, and r + 1's first: fresh.
let fresh = format!(
"{:?}",
commands_buffer(device, 2).commands(0..1).unwrap()[0]
);
let first = (1 << 31) / 2248 - 2;
let around = (first..first + 6).chain(0..COMMANDS);
let fresh_all = |what: &str| {
for index in around.clone() {
let command = long.commands(index..index + 1).unwrap();
assert_eq!(
format!("{:?}", command[0]),
fresh,
"{what}: command {index}"
);
}
};
fresh_all("written through r + 2");
// r + 2's buffer not resident: the writes miss.
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder
.use_resource(long.as_resource(), ResourceUsage::WRITE)
.unwrap();
encoder.set_compute_pipeline_state(&setup.writer).unwrap();
encoder.set_buffer(Some(&setup.arguments), 0, 0).unwrap();
encoder.set_buffer(Some(&setup.params), 0, 1).unwrap();
encoder.set_buffer(Some(&setup.out), 0, 2).unwrap();
let commands = Size::new(COMMANDS, 1, 1);
encoder.dispatch_threads(commands, commands).unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let report = command_buffer.execution_report().unwrap();
assert!(report.resident_miss, "the writes miss: {report:?}");
fresh_all("with r + 2's records not resident");
});
}
/// The commands run on another queue after an event the writer signals, the executing command
/// buffer committed first: its batch waits for the event, then for the writer's work to
/// complete. So does an execution committed before any encoder made the buffer resident for
@@ -15,6 +15,12 @@
//! written) is never called, and the commands draw on the GPU; where the CPU writes a point
//! draw after the commit, before the pass's batch is ready, the host step records the pass
//! instead and calls the check;
//! - a check of the CPU's records, which `commit` records, is called there with each command,
//! before `commit` returns, where the records may hold draws of points and it looks for them;
//! never where they hold triangles alone, or where it looks for nothing;
//! - the CPU's records, which `commit` records, written again after the commit, before the pass's
//! batch is submitted (it waits for an event), draw as written then, the host step recording
//! the pass again and announcing nothing;
//! - two executions of one buffer in one pass draw each its own range;
//! - a buffer that may hold a barrier takes the host step, announced once;
//! - an address outside the resident resources misses, counted, while its neighbours draw;
@@ -386,6 +392,122 @@ fn facts_that_grow_before_the_batch_is_ready_take_the_host_step() {
});
}
/// A check of commands the CPU wrote, in a buffer no encoder made resident for writing, which
/// `commit` records from the CPU's records: `commit` calls it with each command of the range
/// before it returns, where the CPU drew points and the check looks for them; where the CPU drew
/// triangles alone, or the check looks for nothing, never. The commands draw the same each time,
/// and no host step runs.
#[test]
fn commit_checks_the_cpu_s_records_where_the_check_may_see_something() {
on_device(|device, messages| {
let points = IndirectCommandCheckNeeds::new(true, false);
let nothing = IndirectCommandCheckNeeds::new(false, false);
for (primitive_type, needs) in [
(PrimitiveType::Point, points),
(PrimitiveType::Triangle, points),
(PrimitiveType::Point, nothing),
] {
let setup = Setup::new(device);
let icb = icb(device, &inheriting(1), 4);
for index in 0..4 {
buffers(&setup, &icb, index, index as usize);
icb.indirect_render_command_at(index)
.unwrap()
.draw_primitives(primitive_type, 0, 3, 1, 0)
.unwrap();
}
let seen: Arc<Mutex<Vec<u64>>> = Arc::default();
let log = Arc::clone(&seen);
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass()).unwrap();
encoder.set_render_pipeline_state(&setup.state).unwrap();
setup.resident(&mut encoder);
encoder
.execute_commands_in_buffer_checked(
&icb,
0..4,
Box::new(move |index, _| log.lock().unwrap().push(index)),
needs,
)
.unwrap();
encoder.end_encoding().unwrap();
let (_, read) = counted(device, || command_buffer.commit().unwrap());
let at_commit = seen.lock().unwrap().clone();
indirect_host_steps::wait(&command_buffer);
let at = format!("{primitive_type:?}, {needs:?}");
assert!(!icb.gpu_written(), "{at}");
assert_eq!(read, 4, "{at}: the commit read each record");
let every: Vec<u64> = match primitive_type == PrimitiveType::Point && needs == points {
true => vec![0, 1, 2, 3],
false => Vec::new(),
};
assert_eq!(at_commit, every, "{at}: checked in `commit`");
assert_eq!(*seen.lock().unwrap(), every, "{at}: and only there");
let draws: Vec<Drawn> = (0..4).map(|window| drawn(window, 0, 3)).collect();
assert_eq!(setup.output(), expected(&draws), "{at}");
}
assert_made_once(messages, &[], &forced_with(device, &[]));
});
}
/// Commands the CPU wrote, in a buffer no encoder made resident for writing, draw as their records
/// stand when the pass's batch is submitted, as Metal's execution reads them as it runs: where the
/// CPU draws 2 more vertices in command 1 after the commit, before the batch is submitted (it waits
/// for an event the test signals after the write), the host step records the pass again from the
/// records then (each record read again) and command 1 draws 5 vertices; without the write, the
/// commit's recording draws 3. Nothing is announced.
#[test]
fn the_cpu_s_writes_after_the_commit_draw_where_the_batch_waits() {
on_device(|device, messages| {
for write in [false, true] {
let setup = Setup::new(device);
let icb = icb(device, &inheriting(1), 4);
for index in 0..4 {
buffers(&setup, &icb, index, index as usize);
icb.indirect_render_command_at(index)
.unwrap()
.draw_primitives(PrimitiveType::Point, 0, 3, 1, 0)
.unwrap();
}
let event = device.new_shared_event().unwrap();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
command_buffer
.encode_wait_for_event(EventRef::from(&event), 1)
.unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass()).unwrap();
encoder.set_render_pipeline_state(&setup.state).unwrap();
setup.resident(&mut encoder);
encoder.execute_commands_in_buffer(&icb, 0..4).unwrap();
encoder.end_encoding().unwrap();
let (_, read) = counted(device, || {
command_buffer.commit().unwrap();
if write {
icb.indirect_render_command_at(1)
.unwrap()
.draw_primitives(PrimitiveType::Point, 0, 5, 1, 0)
.unwrap();
}
event.set_signaled_value(1);
indirect_host_steps::wait(&command_buffer);
});
assert!(!icb.gpu_written(), "write {write}");
let reads = if write { 8 } else { 4 };
assert_eq!(read, reads, "write {write}: the records read");
let count = |window: usize| match (write, window) {
(true, 1) => 5,
_ => 3,
};
let draws: Vec<Drawn> = (0..4)
.map(|window| drawn(window, 0, count(window)))
.collect();
assert_eq!(setup.output(), expected(&draws), "write {write}");
}
assert_made_once(messages, &[], &forced_with(device, &[]));
});
}
/// Two executions of one buffer in one pass, of ranges that overlap, draw each its own range in
/// the GPU form.
#[test]
@@ -24,7 +24,9 @@
//! the buffer a shadowed target lies over: the render encoder encoded again, its copies and its
//! merged draw into the new pages.
use super::degrade_notices::{assert_made_once, assert_once, counts, expected_once, on_device};
use super::degrade_notices::{
assert_made_once, assert_once, counts, expected_once, made_compute_kinds, on_device,
};
use super::host_memory::Mapping;
use super::host_memory::Seen;
use super::indirect_host_steps::{complete, HOST_STEPS};
@@ -38,7 +40,8 @@ use metal2vulkan::metal::{
IndirectCommandType, PixelFormat, PrimitiveType, ResourceUsage, TextureUsage,
};
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource,
ColorAttachmentDescriptor, ComputePipelineDescriptor, FunctionDescriptor,
RenderPipelineDescriptor, StageSource,
};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
@@ -47,6 +50,7 @@ use metal2vulkan_runtime::{
PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size,
StoreAction, Texture, TextureDescriptor,
};
use std::collections::BTreeSet;
use std::sync::Arc;
/// The target's width and height, and the rows an instance moves its vertices down.
@@ -63,20 +67,45 @@ fn library(device: &Device) -> Library {
device.new_library_with_air(&bitcode).unwrap()
}
/// The kernel of the writer of `kind` (`points`, `lines` or `triangles`).
fn writer_function(library: &Library, kind: &str) -> FunctionDescriptor {
library
.new_function_with_name(&format!("icb_merged_{kind}"))
.unwrap()
.function_descriptor()
}
/// The writer of `kind` (`points`, `lines` or `triangles`).
fn writer(device: &Device, library: &Library, kind: &str) -> ComputePipelineState {
let function = library
.new_function_with_name(&format!("icb_merged_{kind}"))
.unwrap();
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
ComputePipelineDescriptor::new(StageSource::Function(writer_function(library, kind)));
device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
}
/// The commands' state, made with `supportIndirectCommandBuffers`.
/// The commands' state ([`state_descriptor`]).
fn state(device: &Device, library: &Library) -> RenderPipelineState {
device
.new_render_pipeline_state(&state_descriptor(library), &PipelineOptions::default())
.unwrap()
}
/// The kinds the makings of the commands' state and of the writers of `writers` announce on
/// `device` the first time, beside the device's own ([`forced_with`], [`made_compute_kinds`]):
/// their translations' precision notes, which the device's arithmetic and point sizes decide
/// (lavapipe's `device-arithmetic` and `device-point-size` for the vertex function; none on
/// MoltenVK).
fn made(device: &Device, library: &Library, writers: &[&str]) -> BTreeSet<Degradation> {
let mut kinds = forced_with(device, &[state_descriptor(library)]);
for kind in writers {
kinds.extend(made_compute_kinds(device, writer_function(library, kind)));
}
kinds
}
/// The descriptor of the commands' state, with `supportIndirectCommandBuffers`.
fn state_descriptor(library: &Library) -> RenderPipelineDescriptor {
let function = |name: &str| {
StageSource::Function(
library
@@ -89,9 +118,7 @@ fn state(device: &Device, library: &Library) -> RenderPipelineState {
descriptor.fragment = Some(function("icb_merged_fragment"));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint));
descriptor.support_indirect_command_buffers = true;
device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
descriptor
}
/// Draw commands of three vertex buffers that inherit the encoder's state.
@@ -330,7 +357,7 @@ fn merged_points_draw_each_command_s_own_vertices_and_instances() {
});
assert_eq!(scene.pixels(), drawn_points(&draws));
assert_eq!((merged, gpu, read), (8, 8, 0), "drawn in one merged draw");
assert_made_once(messages, &[], &forced_with(device, &[]));
assert_made_once(messages, &[], &made(device, &library, &["points"]));
});
}
@@ -397,7 +424,8 @@ fn merged_draws_draw_what_the_host_step_draws() {
outputs.push(scene.pixels());
}
if !host_step {
assert_made_once(messages, &[], &forced_with(device, &[]));
let writers: Vec<&str> = kinds.iter().map(|(kind, _)| *kind).collect();
assert_made_once(messages, &[], &made(device, &library, &writers));
}
}
let host_notices = counts(&messages.take_notices());
@@ -475,7 +503,8 @@ fn gpu_forms_draw_into_a_shadowed_target_what_the_host_step_draws() {
}
if !host_step {
let shadowed = [Degradation::ShadowedTexture];
assert_made_once(messages, &shadowed, &forced_with(device, &[]));
let first = made(device, &library, &["triangles"]);
assert_made_once(messages, &shadowed, &first);
}
}
let host_notices = counts(&messages.take_notices());
@@ -551,7 +580,7 @@ fn rebound_run(
command_buffer.wait_until_completed_for(WAIT).unwrap();
let pointed = device.work_counts().replay_tables_pointed - before.replay_tables_pointed;
let ended = (command_buffer.status(), command_buffer.error());
let expected = expected_once(messages, kinds, &forced_with(device, &[]));
let expected = expected_once(messages, kinds, &made(device, &library, &["points"]));
let notices = messages.take_notices();
let reasons: Vec<String> = (notices.iter())
.filter_map(|message| message.degradation.as_ref())
@@ -719,7 +748,8 @@ fn a_rebind_of_a_shadowed_target_s_bytes_encodes_a_pass_that_draws_again() {
return;
};
let scene = Scene::over(device, &[draw], &point_row(), bytes, rows);
let state = state(device, &library(device));
let library = library(device);
let state = state(device, &library);
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(scene.target.clone());
@@ -776,7 +806,7 @@ fn a_rebind_of_a_shadowed_target_s_bytes_encodes_a_pass_that_draws_again() {
"(encoders encoded again, refused), and the command buffer's end"
);
let shadowed = [Degradation::ShadowedTexture];
assert_made_once(messages, &shadowed, &forced_with(device, &[]));
assert_made_once(messages, &shadowed, &made(device, &library, &[]));
let drawn = drawn_points(&[draw]);
assert_rows(scene.over.as_ref().unwrap(), rows, &drawn);
assert_eq!(scene.pixels(), drawn, "the texture over the new pages");
@@ -41,10 +41,11 @@ use metal2vulkan_runtime::{
BlitOption, Buffer, BufferContents, BufferDescriptor, CommandBuffer, CommandBufferError,
CommandBufferStatus, CommandQueue, ComputePipelineState, Deallocator, DebugMessage,
Degradation, Device, DeviceOptions, Error, EventRef, ExecutedPipeline, Fence, Heap,
HeapDescriptor, HeapType, HostMemory, IdPlacement, IndirectCommandBufferDescriptor, Invalid,
IoSurfacePlane, KeepAlive, MemoryKind, MessageSeverity, MessageSink, Origin, Problem, Region,
RenderPassDescriptor, ResourceId, ResourceIdKind, ResourceOptions, SamplerState,
SamplerStateOptions, SharedEvent, Size, Texture, TextureDescriptor, TextureSwizzleChannels,
HeapDescriptor, HeapType, HostMemory, IdPlacement, IndirectCommandBuffer,
IndirectCommandBufferDescriptor, Invalid, IoSurfacePlane, KeepAlive, MessageSeverity,
MessageSink, Origin, Problem, Region, RenderPassDescriptor, ResourceId, ResourceIdKind,
ResourceOptions, SamplerState, SamplerStateOptions, SharedEvent, Size, Texture,
TextureDescriptor, TextureSwizzleChannels,
};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicBool, Ordering};
@@ -2279,8 +2280,9 @@ fn a_queue_or_buffer_made_before_a_texture_reservation_keeps_the_pool_s_first_ra
/// Plain IDs after a reservation are the ones Metal hands out, for textures, sampler states,
/// pipeline states and indirect command buffers, and an ID given back joins its free neighbours
/// (each sequence measured on an M4): only a kind's first reservation with an ID counts, and IDs
/// past Metal's placement limit are taken.
/// (each sequence measured on an M4, those of indirect command buffers past 2^23 on an M3 Max):
/// only a kind's first reservation with an ID counts, and IDs past Metal's placement limit are
/// taken.
#[test]
fn plain_ids_after_a_reservation_are_metal_s() {
let plain = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 4, 4, false);
@@ -2300,7 +2302,9 @@ fn plain_ids_after_a_reservation_are_metal_s() {
// One reserved texture ID inside the pool's second half: 11 to 15 first (`o1_0_10`); a
// second call is ignored, even before any texture was made (`w_16_5`). A call of no ID, of
// 0 alone, or holding an ID of 2^32 or more (dropped whole) is not the reservation
// (`empty_first`, `y_zero_then_10`, `y_high_and_10`, `y_high_then_10`).
// (`empty_first`, `y_high_and_10`, `y_high_then_10`), but the call of 0 alone leaves the pool
// made, so its first range's IDs are handed out twice: 1 after 9, where the M4's
// `y_zero_then_10` handed out 16 (an M3 Max, macOS 27.0.1, this very sequence).
on_device(|device, _| {
let reserve = |ids: &[u64]| {
let ids: Vec<ResourceId> = ids.iter().copied().map(ResourceId).collect();
@@ -2312,7 +2316,7 @@ fn plain_ids_after_a_reservation_are_metal_s() {
reserve(&[10]).unwrap();
reserve(&[12]).unwrap();
let made = textures(device, 17);
assert_eq!(ids(&made), runs(&[(11, 15), (1, 9), (16, 18)]));
assert_eq!(ids(&made), runs(&[(11, 15), (1, 9), (1, 3)]));
});
// IDs past Metal's placement limit (`hi_0_16380`, `multi_0`): 16383 is handed out.
on_device(|device, _| {
@@ -2378,23 +2382,50 @@ fn plain_ids_after_a_reservation_are_metal_s() {
let state = super::indirect_command_buffers::render_template_state(device, true);
assert_eq!(state.gpu_resource_id(), ResourceId(18));
});
// Refused, reserving nothing: a texture or sampler state ID of 2^28 or more, and an indirect
// command buffer ID of 2^30 or more, which ended Metal's process (`x_0_2p28p5`,
// `x_1_2p28p5`).
// Refused, reserving nothing: a texture or sampler state ID of 2^28 or more, which ended
// Metal's process (`x_0_2p28p5`, `x_1_2p28p5`), and an indirect command buffer ID of 2^31 to
// 2^32 - 1, at which Metal's reservation never returned (an M3 Max), as such.
on_device(|device, _| {
let hangs = |id| Problem::ReservationHangs {
id,
limit: RECORDS_ID_LIMIT,
};
let refused = [
(ResourceIdKind::Texture, 1 << 28),
(ResourceIdKind::SamplerState, 1 << 28),
(ResourceIdKind::IndirectCommandBuffer, 1 << 30),
(
ResourceIdKind::Texture,
1 << 28,
Problem::ResourceId {
id: 1 << 28,
limit: 1 << 28,
},
),
(
ResourceIdKind::SamplerState,
1 << 28,
Problem::ResourceId {
id: 1 << 28,
limit: 1 << 28,
},
),
(
ResourceIdKind::IndirectCommandBuffer,
RECORDS_ID_LIMIT,
hangs(RECORDS_ID_LIMIT),
),
(
ResourceIdKind::IndirectCommandBuffer,
(1 << 32) - 1,
hangs((1 << 32) - 1),
),
];
for (kind, limit) in refused {
for (kind, id, expected) in refused {
let error = device
.reserve_resource_ids(kind, &[ResourceId(limit)])
.reserve_resource_ids(kind, &[ResourceId(id)])
.unwrap_err();
let Error::Invalid(Invalid { problem, .. }) = error else {
panic!("{kind:?}: {error:?}");
};
assert_eq!(problem, Problem::ResourceId { id: limit, limit });
assert_eq!(problem, expected);
}
// Nothing was reserved: 10 is the reservation still.
device
@@ -2405,18 +2436,24 @@ fn plain_ids_after_a_reservation_are_metal_s() {
ResourceId(11)
);
});
// An indirect command buffer ID needs no records to be reserved: 2^23 + 5 is taken, and the
// buffer Metal numbers past it (2^23 + 6) has no records address,
// refused `OutOfMemory` as it is made; after 2^23 alone, 1 is handed out (`x_5_2p23`).
// Plain indirect command buffer IDs past a reservation are the ones Metal hands out, each
// buffer made (an M3 Max, macOS 27.0.1): 2^23 + 5, 16,000,000, 2^30 + 5 and 3 * 2^29 give the
// next IDs, 2^31 - 2 gives 2^31 - 1, then 1, and 2^23, 2^30 - 1, 2^30 and 2^31 - 1 give 1
// (`x_5_2p23`).
let mut icb = IndirectCommandBufferDescriptor::new();
icb.command_types = IndirectCommandType::CONCURRENT_DISPATCH;
for (reserved, made) in [
(
RECORDS_ID_LIMIT + 5,
Err(Error::OutOfMemory(MemoryKind::Device)),
),
(RECORDS_ID_LIMIT, Ok(ResourceId(1))),
] {
let made: [(u64, &[u64]); 9] = [
((1 << 23) + 5, &[(1 << 23) + 6, (1 << 23) + 7]),
(16_000_000, &[16_000_001, 16_000_002, 16_000_003]),
(1 << 23, &[1, 2]),
((1 << 30) - 1, &[1]),
(1 << 30, &[1]),
((1 << 30) + 5, &[(1 << 30) + 6]),
(3 << 29, &[(3 << 29) + 1]),
(RECORDS_ID_LIMIT - 2, &[RECORDS_ID_LIMIT - 1, 1]),
(RECORDS_ID_LIMIT - 1, &[1, 2]),
];
for (reserved, ids) in made {
on_device(|device, _| {
device
.reserve_resource_ids(
@@ -2424,8 +2461,112 @@ fn plain_ids_after_a_reservation_are_metal_s() {
&[ResourceId(reserved)],
)
.unwrap();
let buffer = device.new_indirect_command_buffer(&icb, 1, ResourceOptions::shared());
assert_eq!(buffer.map(|b| b.gpu_resource_id()), made, "{reserved}");
let buffers: Vec<IndirectCommandBuffer> = ids
.iter()
.map(|_| {
device
.new_indirect_command_buffer(&icb, 1, ResourceOptions::shared())
.unwrap()
})
.collect();
let got: Vec<u64> = buffers.iter().map(|b| b.gpu_resource_id().0).collect();
assert_eq!(got, ids, "{reserved}");
});
}
// A late call (after a buffer, or after a reservation) is ignored whatever it holds, as
// Metal ignores and logs it (an M3 Max, macOS 27.0.1): IDs of 2^31 and up, refused in a first
// call, 2^32 + 5, dropped in a first call, and 0 alone; textures' 2^28 + 5 too.
let late = [
(
ResourceIdKind::IndirectCommandBuffer,
None,
RECORDS_ID_LIMIT + 5,
[2, 3],
),
(
ResourceIdKind::IndirectCommandBuffer,
None,
(1 << 32) - 1,
[2, 3],
),
(
ResourceIdKind::IndirectCommandBuffer,
Some(5),
RECORDS_ID_LIMIT,
[1, 2],
),
(
ResourceIdKind::IndirectCommandBuffer,
None,
(1 << 32) + 5,
[2, 3],
),
(ResourceIdKind::IndirectCommandBuffer, None, 0, [2, 3]),
(ResourceIdKind::Texture, None, (1 << 28) + 5, [2, 3]),
(ResourceIdKind::Texture, Some(10), (1 << 28) + 5, [11, 12]),
];
for (kind, first, held, next) in late {
on_device(|device, _| {
// Each kept alive, so its ID stays held.
let (mut textures, mut buffers) = (Vec::new(), Vec::new());
let mut make = || match kind {
ResourceIdKind::Texture => {
let texture = device.new_texture(&plain).unwrap();
let id = texture.gpu_resource_id().0;
textures.push(texture);
id
}
_ => {
let buffer = device
.new_indirect_command_buffer(&icb, 1, ResourceOptions::shared())
.unwrap();
let id = buffer.gpu_resource_id().0;
buffers.push(buffer);
id
}
};
match first {
Some(id) => device
.reserve_resource_ids(kind, &[ResourceId(id)])
.unwrap(),
None => assert_eq!(make(), 1),
}
assert_eq!(
device.reserve_resource_ids(kind, &[ResourceId(held)]),
Ok(()),
"{kind:?}: {held} after {first:?}"
);
let got = [make(), make()];
assert_eq!(got, next, "{kind:?}: {held} after {first:?}");
});
}
// After a call of 0 alone, a reservation keeps the pool's first range beside its own, whose
// IDs Metal hands out twice (an M3 Max, macOS 27.0.1): 0 then 10 gives 1 to 9, 11 to 31,
// then 1 to 15; 0 then 20, 21 to 31, 1 to 19, then 1 to 10.
for (reserved, runs) in [
(10, &[(1, 9), (11, 31), (1, 15)]),
(20, &[(21, 31), (1, 19), (1, 10)]),
] {
on_device(|device, _| {
for ids in [0, reserved] {
device
.reserve_resource_ids(ResourceIdKind::IndirectCommandBuffer, &[ResourceId(ids)])
.unwrap();
}
let want: Vec<u64> = runs
.iter()
.flat_map(|&(first, last)| first..=last)
.collect();
let buffers: Vec<IndirectCommandBuffer> = want
.iter()
.map(|_| {
device
.new_indirect_command_buffer(&icb, 1, ResourceOptions::shared())
.unwrap()
})
.collect();
let got: Vec<u64> = buffers.iter().map(|b| b.gpu_resource_id().0).collect();
assert_eq!(got, want, "0, then {reserved}");
});
}
}
@@ -5,7 +5,8 @@
//! A consumer that runs its own runtime on the compile layer needs it to execute and read back
//! indirect command buffers: [`CommandBuffer::initialize`] writes the header a
//! [`CommandDescriptor`] and an [`Inheritance`] fix and resets every record,
//! [`CommandRecord::encode_into`] writes one command as the CPU's encoder sets it, and
//! [`CommandRecord::encode_into`] writes one command as the CPU's encoder sets it (and
//! [`CommandRecord::write_field`] one field of it, as one setter does), and
//! [`CommandBuffer::decode`] checks storage a kernel wrote (its sticky encoding fault, the header,
//! every record against the descriptor) before [`CommandBuffer::records`] reads a range back as
//! [`CommandRecord`]s. [`CommandRecord::resolve_bindings`] picks each command's pipeline and
@@ -17,7 +18,7 @@ pub use crate::indirect_commands::records_address;
pub use crate::indirect_commands::{
Action, AddressError, BindingError, Bindings, BufferBinding, BufferStage, CommandBuffer,
CommandBufferError, CommandDescriptor, CommandRecord, ComputeDispatch, Inheritance,
RecordError, RegisteredBuffer, RenderDraws, ResolvedBindings, ResolvedBuffer, StateSource,
BINDING_COUNT, COMMAND_BUFFER_HEADER_BYTES, COMMAND_BYTES, RECORDS_ADDRESS_BASE,
RECORDS_ADDRESS_SHIFT, RECORDS_ID_LIMIT, THREADGROUP_BUFFER_ARGUMENT_COUNT,
RecordError, RecordField, RecordView, RegisteredBuffer, RenderDraws, ResolvedBindings,
ResolvedBuffer, StateSource, BINDING_COUNT, COMMAND_BUFFER_HEADER_BYTES, COMMAND_BYTES,
RECORDS_ADDRESS_BASE, RECORDS_ID_LIMIT, THREADGROUP_BUFFER_ARGUMENT_COUNT,
};
+3 -2
View File
@@ -327,8 +327,9 @@ impl ResidentRange {
/// A resident set a consumer uploads apart from the root tables that search it: its allocations
/// coalesced as a root table's are (sorted by Metal address, one inside another dropped, a partial
/// overlap trimmed of its head, an empty one dropped), each at its padded size, as entries in a
/// root table's layout. The consumer uploads [`bytes`]( Self::bytes) at a 32-byte-aligned device
/// overlap trimmed of its head, an empty one dropped; indirect command buffers' records, from
/// `RECORDS_ADDRESS_BASE`, kept whole, one for each start), each at its padded size, as entries in
/// a root table's layout. The consumer uploads [`bytes`]( Self::bytes) at a 32-byte-aligned device
/// address and points root tables there ([`RootTable::resident_fields`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResidentSet {
+18 -3
View File
@@ -5,11 +5,14 @@
//! guest address, an allocation inside another dropped (the outermost wins: a heap over its
//! sub-buffers), a partially overlapping one trimmed of its overlapping head (host and guest
//! advancing together), and empty ones dropped, of any count (At most 2¹⁶ entries before, else
//! `ResidentSetTooLarge`). Each stage that reads a root table gets its own (`stage_root_table`):
//! `ResidentSetTooLarge`). Indirect command buffers' records (from `RECORDS_ADDRESS_BASE`) are
//! kept whole however they overlap, one a start: a kernel finds an ID's records only where they
//! start (`indirect_commands::records_address`). Each stage that reads a root table gets its own (`stage_root_table`):
//! its `Psb` entries are that stage's slots; the resident set is shared.
use crate::bind::instantiate::{padded, RootTable};
use crate::bind::state::{BindState, BoundBuffer, ResourceClass};
use crate::indirect_commands::RECORDS_ADDRESS_BASE;
/// One root-table entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
@@ -27,7 +30,10 @@ pub(crate) struct RootEntry {
/// The resident set of `all` allocations: sorted by guest address; an allocation inside another one
/// is dropped (the outermost wins: a heap over its sub-buffers); a partially overlapping one loses
/// its overlapping head (its host and guest addresses advance together, which is exact when both
/// ranges view one mapping); empty allocations are dropped.
/// ranges view one mapping); empty allocations are dropped. Records of indirect command buffers
/// (from `RECORDS_ADDRESS_BASE`, where no Metal allocation lies) are kept whole, one for each
/// start (the largest): an ID's records may run past later IDs' starts, and a kernel searches
/// them only at their start, so each start must stay an entry's.
pub(crate) fn resident_set(mut all: Vec<RootEntry>) -> Vec<RootEntry> {
all.retain(|e| e.size > 0);
all.sort_by(|a, b| a.guest.cmp(&b.guest).then(b.size.cmp(&a.size)));
@@ -35,6 +41,14 @@ pub(crate) fn resident_set(mut all: Vec<RootEntry>) -> Vec<RootEntry> {
let mut out: Vec<RootEntry> = Vec::with_capacity(all.len());
for mut e in all {
if let Some(last) = out.last() {
if e.guest >= RECORDS_ADDRESS_BASE {
if e.guest == last.guest {
continue;
}
e.bind_offset = 0;
out.push(e);
continue;
}
let last_end = end(last);
if end(&e) <= last_end {
continue;
@@ -104,7 +118,8 @@ fn resident_allocations(state: &BindState) -> impl Iterator<Item = (u64, u64, u6
/// (`BufferBinding::resolve_buffer`); the converse fails only for an address past a gap inside one
/// padded window, which only allocations whose guest addresses are not 16-aligned leave. Sorting,
/// then one forward pass per entry over the allocations that start inside its window (the windows
/// are disjoint), bounds the work by the allocations' count times its logarithm.
/// are disjoint but for records, which hold few allocations), bounds the work by the allocations'
/// count times its logarithm.
pub(crate) fn resident_extents(state: &BindState, resident: &[RootEntry]) -> Vec<u64> {
let allocations = resident_allocations(state).map(|(_, guest, length)| (guest, length));
extents_of(allocations, resident)
@@ -222,6 +222,32 @@ fn the_resident_set_is_sorted_disjoint_and_outermost() {
assert_eq!(resident_set(Vec::new()), Vec::new());
}
/// Indirect command buffers' records are kept whole however they overlap, one entry a start (the
/// largest of those at one start), past the Metal allocations, which coalesce as before: the
/// records of ID 5, 3 GiB long, run past ID 6's start, and ID 6's own stay an entry, so a search
/// at each ID's start finds that ID's records.
#[test]
fn records_are_kept_whole_one_entry_a_start() {
use crate::indirect_commands::records_address;
let gib = 1u64 << 30;
let metal = entry(0x9000, 0x1000, 0x1000);
let inner = entry(0x9100, 0x1100, 0x100);
let five = entry(0x10_0000_0000, records_address(5), 3 * gib);
let six = entry(0x20_0000_0000, records_address(6), 0x1000);
let six_again = entry(0x30_0000_0000, records_address(6), 0x100);
let seven = entry(0x40_0000_0000, records_address(7), 0x1000);
let set = resident_set(vec![seven, six_again, inner, six, five, metal]);
assert_eq!(set, vec![metal, five, six, seven]);
for id in [5, 6, 7] {
let start = records_address(id);
let found = set.iter().rposition(|e| e.guest <= start).unwrap();
assert_eq!(
set[found].guest, start,
"ID {id}'s start is its own entry's"
);
}
}
/// Each resident entry's extent is the unpadded run its allocations hold from its guest address. A
/// 60-byte allocation's entry is 64 bytes and its extent 60; an allocation whose padded window a
/// partially overlapping one continues holds its whole window; the trimmed one's entry holds up to
+390 -194
View File
@@ -7,10 +7,11 @@
mod descriptor;
pub use descriptor::{CommandDescriptor, ComputeDispatch, RenderDraws};
mod host;
pub use host::{BindingError, CommandBuffer, CommandBufferError, ResolvedBindings};
pub use host::{BindingError, CommandBuffer, CommandBufferError, RecordView, ResolvedBindings};
use std::fmt;
use std::num::NonZeroU64;
use std::ops::Range;
/// Buffer namespace of an encoded command.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -96,23 +97,28 @@ pub const COMMAND_BUFFER_HEADER_BYTES: usize = 16;
/// The guest address of the records of the indirect command buffer of resource ID 0, the null
/// one, which no records lie at ([`records_address`]).
pub const RECORDS_ADDRESS_BASE: u64 = 1 << 63;
/// How far an indirect command buffer's resource ID is shifted to give the guest address of its
/// records past [`RECORDS_ADDRESS_BASE`] ([`records_address`]): each ID's records have 2^40
/// bytes of guest addresses to themselves.
pub const RECORDS_ADDRESS_SHIFT: u32 = 40;
/// The first resource ID whose records [`records_address`] cannot place: the IDs of indirect
/// command buffers run from 1 below it.
pub const RECORDS_ID_LIMIT: u64 = 1 << (63 - RECORDS_ADDRESS_SHIFT);
/// How far an indirect command buffer's resource ID is shifted to give the guest address its
/// records start at past [`RECORDS_ADDRESS_BASE`] ([`records_address`]): 2^31 bytes from one ID's
/// start to the next's. Records of more bytes run past the next IDs' starts, which a search for
/// those IDs' records still tells apart: it finds an ID's records only at their start.
pub(crate) const RECORDS_ADDRESS_SHIFT: u32 = 31;
/// The first resource ID whose records [`records_address`] cannot place, 2^31: the IDs of indirect
/// command buffers run from 1 below it, as Metal's do (on an M3 Max, a reservation of 2^31 - 2
/// handed out 2^31 - 1 next, and one of 2^31 to 2^32 - 1 never returned). The last ID's records
/// start 2^62 bytes below 2^64, so records of any length a device holds fit after any ID's start.
pub const RECORDS_ID_LIMIT: u64 = 1 << 31;
/// The guest address of the records of the indirect command buffer whose resource ID is `id`
/// (below [`RECORDS_ID_LIMIT`]): `2^63 + id * 2^40`. An argument buffer's command-buffer member
/// The guest address the records of the indirect command buffer whose resource ID is `id` (below
/// [`RECORDS_ID_LIMIT`]) start at: `2^63 + id * 2^31`. An argument buffer's command-buffer member
/// holds the ID, as Metal's `gpuResourceID` and `setIndirectCommandBuffer:atIndex:` give it (small
/// integers from 1, measured on an M3 Max and an M4), and a translated kernel that encodes through
/// it reaches the records at this address of its resident set. So a consumer that makes an indirect
/// command buffer with ID `id` makes its record buffer resident at `records_address(id)`, a range
/// no Metal buffer reaches (each lies below 2^63). The null ID 0 gives an address no records lie
/// at, so an encoder operation through it is contained as a record buffer outside the resident set
/// is.
/// integers from 1, measured on an M3 Max and an M4, or the IDs a reservation leaves next, up to
/// 2^31 - 1 on an M3 Max), and a translated kernel that encodes through it reaches the records
/// that start at this address in its resident set, and no other: records of more than 2^31 bytes
/// run past the next IDs' starts, and the resident set keeps each records range whole
/// (`ResidentSet`). So a consumer that makes an indirect command buffer with ID `id` makes its
/// record buffer resident at `records_address(id)`, a range no Metal buffer reaches (each lies
/// below 2^63). The null ID 0 gives an address no records start at, so an encoder operation
/// through it is contained as one through an ID whose records are not resident is.
pub const fn records_address(id: u64) -> u64 {
RECORDS_ADDRESS_BASE | (id << RECORDS_ADDRESS_SHIFT)
}
@@ -637,8 +643,9 @@ pub struct CommandRecord {
}
/// Why a record was refused: its length, an unknown action, a barrier flag other than 0 or 1,
/// the all-ones attribute stride, which stands for the pipeline's static stride, or a stage-in
/// region beside a draw whose arguments take its words.
/// the all-ones attribute stride, which stands for the pipeline's static stride, a stage-in
/// region beside a draw whose arguments take its words, or a field's index past what a record
/// holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordError {
Length {
@@ -662,6 +669,13 @@ pub enum RecordError {
/// takes the first two lengths' words (`layout::CONTROL_POINT_INDICES`): a render command
/// sets none.
ThreadgroupMemoryLength,
/// A field's index past what a record holds ([`CommandRecord::write_field`]): a buffer slot
/// at or past [`BINDING_COUNT`], or a threadgroup length at or past
/// [`THREADGROUP_BUFFER_ARGUMENT_COUNT`].
Index {
index: usize,
count: usize,
},
}
impl fmt::Display for RecordError {
@@ -687,6 +701,10 @@ impl fmt::Display for RecordError {
"an indexed patch draw's control-point index buffer takes the threadgroup \
lengths' first words",
),
Self::Index { index, count } => write!(
f,
"indirect command field index {index} is past the record's {count}"
),
}
}
}
@@ -699,41 +717,7 @@ impl CommandRecord {
/// of them), and its barrier. The pipeline state it names is the writer's to add: a CPU setter
/// names one by the state itself.
pub fn writes(&self) -> crate::pipeline::CommandWrites {
use crate::pipeline::CommandWrites;
let draw = |operations: u32, primitive_type: u32| CommandWrites {
operations,
primitive_types: if primitive_type < 5 {
1 << primitive_type
} else {
CommandWrites::ALL_PRIMITIVE_TYPES
},
};
let only = |operations: u32| CommandWrites {
operations,
primitive_types: 0,
};
let mut writes = match self.action {
Action::Empty => CommandWrites::NONE,
Action::DispatchThreadgroups { .. } | Action::DispatchThreads { .. } => {
only(CommandWrites::DISPATCH)
}
Action::DrawPrimitives { primitive_type, .. } => {
draw(CommandWrites::DRAW, primitive_type)
}
Action::DrawIndexedPrimitives { primitive_type, .. } => {
draw(CommandWrites::DRAW_INDEXED, primitive_type)
}
Action::DrawPatches { .. } | Action::DrawIndexedPatches { .. } => {
only(CommandWrites::DRAW_PATCHES)
}
Action::DrawMeshThreadgroups { .. } | Action::DrawMeshThreads { .. } => {
only(CommandWrites::DRAW_MESH)
}
};
if self.barrier {
writes.operations |= CommandWrites::BARRIER;
}
writes
writes_of(&self.action, self.barrier)
}
/// Encode a complete record without allocating. Invalid input leaves the destination unchanged.
@@ -770,147 +754,7 @@ impl CommandRecord {
return Err(RecordError::PipelineState);
}
bytes.fill(0);
let (tag, arguments) = match self.action {
Action::Empty => (0, arguments([])),
Action::DispatchThreadgroups { grid, local_size } => (
1,
arguments([
grid[0],
grid[1],
grid[2],
local_size[0],
local_size[1],
local_size[2],
]),
),
Action::DispatchThreads { grid, local_size } => (
2,
arguments([
grid[0],
grid[1],
grid[2],
local_size[0],
local_size[1],
local_size[2],
]),
),
Action::DrawPrimitives {
primitive_type,
vertex_start,
vertex_count,
instance_count,
base_instance,
} => (
3,
arguments([
primitive_type,
vertex_start,
vertex_count,
instance_count,
base_instance,
]),
),
Action::DrawIndexedPrimitives {
primitive_type,
index_count,
index_type,
index_buffer,
instance_count,
base_vertex,
base_instance,
} => (
4,
arguments([
primitive_type,
index_count,
index_type,
instance_count,
index_buffer as u32,
(index_buffer >> 32) as u32,
base_vertex as u32,
base_instance,
]),
),
Action::DrawPatches {
control_points,
patch_start,
patch_count,
patch_index_buffer,
instance_count,
base_instance,
factor_buffer,
factor_instance_stride,
factor_scale,
} => (
5,
arguments([
control_points,
patch_start,
patch_count,
instance_count,
patch_index_buffer as u32,
(patch_index_buffer >> 32) as u32,
factor_buffer as u32,
(factor_buffer >> 32) as u32,
base_instance,
factor_instance_stride,
factor_scale,
]),
),
Action::DrawIndexedPatches {
control_points,
patch_start,
patch_count,
patch_index_buffer,
control_point_index_buffer: _,
instance_count,
base_instance,
factor_buffer,
factor_instance_stride,
factor_scale,
} => (
6,
arguments([
control_points,
patch_start,
patch_count,
instance_count,
patch_index_buffer as u32,
(patch_index_buffer >> 32) as u32,
factor_buffer as u32,
(factor_buffer >> 32) as u32,
base_instance,
factor_instance_stride,
factor_scale,
]),
),
Action::DrawMeshThreadgroups {
threadgroups: grid,
object_threads,
mesh_threads,
}
| Action::DrawMeshThreads {
threads: grid,
object_threads,
mesh_threads,
} => (
match self.action {
Action::DrawMeshThreadgroups { .. } => 7,
_ => 8,
},
arguments([
grid[0],
grid[1],
grid[2],
object_threads[0],
object_threads[1],
object_threads[2],
mesh_threads[0],
mesh_threads[1],
mesh_threads[2],
]),
),
};
let (tag, arguments) = action_words(&self.action);
put_word(bytes, 0, tag);
put_word(bytes, 1, u32::from(self.barrier));
// The pipeline word holds the pipeline the command executes with; the state word says
@@ -955,6 +799,212 @@ impl CommandRecord {
}
}
/// What a record of `action` and `barrier` holds ([`CommandRecord::writes`]).
pub(crate) fn writes_of(action: &Action, barrier: bool) -> crate::pipeline::CommandWrites {
use crate::pipeline::CommandWrites;
let draw = |operations: u32, primitive_type: u32| CommandWrites {
operations,
primitive_types: if primitive_type < 5 {
1 << primitive_type
} else {
CommandWrites::ALL_PRIMITIVE_TYPES
},
};
let only = |operations: u32| CommandWrites {
operations,
primitive_types: 0,
};
let mut writes = match *action {
Action::Empty => CommandWrites::NONE,
Action::DispatchThreadgroups { .. } | Action::DispatchThreads { .. } => {
only(CommandWrites::DISPATCH)
}
Action::DrawPrimitives { primitive_type, .. } => draw(CommandWrites::DRAW, primitive_type),
Action::DrawIndexedPrimitives { primitive_type, .. } => {
draw(CommandWrites::DRAW_INDEXED, primitive_type)
}
Action::DrawPatches { .. } | Action::DrawIndexedPatches { .. } => {
only(CommandWrites::DRAW_PATCHES)
}
Action::DrawMeshThreadgroups { .. } | Action::DrawMeshThreads { .. } => {
only(CommandWrites::DRAW_MESH)
}
};
if barrier {
writes.operations |= CommandWrites::BARRIER;
}
writes
}
/// One field of a command's record, as one CPU setter writes it ([`CommandRecord::write_field`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordField {
/// The action ([`CommandRecord::action`]): a dispatch or a draw.
Action(Action),
/// The barrier flag ([`CommandRecord::barrier`]).
Barrier(bool),
/// The pipeline the command names ([`Bindings::pipeline`]), set: a pipeline a reset retained
/// goes ([`CommandRecord::retained_pipeline`]).
Pipeline(NonZeroU64),
/// Slot `slot` of `stage`'s buffers ([`Bindings::buffers`]), set, or unset with `None`.
Buffer {
stage: BufferStage,
slot: usize,
binding: Option<BufferBinding>,
},
/// Threadgroup-memory length `index` ([`CommandRecord::threadgroup_memory_lengths`]).
ThreadgroupMemoryLength { index: usize, length: u32 },
/// The stage-in region ([`CommandRecord::stage_in_region`]).
StageInRegion([u32; 6]),
/// The imageblock size ([`CommandRecord::imageblock_size`]).
ImageblockSize([u16; 2]),
}
impl CommandRecord {
/// Write `field` into the record `bytes` hold ([`COMMAND_BYTES`]), as `decode`, setting the
/// field and [`encode_into`](Self::encode_into) would, but touching no word the field does
/// not take: `bytes` then decode as what `encode_into` writes of the record
/// [`decode`](Self::decode) read from them with `field` set, and bytes `encode_into` wrote
/// stay what it writes. One setter's write, without decoding and encoding the rest. Refused,
/// leaving `bytes` unchanged: what `decode` refuses of `bytes`, what `encode_into` refuses of
/// the record with `field` set (an all-ones stride, a stage-in region beside a draw whose
/// arguments take its words, the first two threadgroup lengths beside an indexed patch
/// draw), and an index past the record's ([`RecordError::Index`]). Answers the bytes it may
/// have changed.
pub fn write_field(bytes: &mut [u8], field: RecordField) -> Result<Range<usize>, RecordError> {
let view = RecordView::new(bytes)?;
let (action, retained) = (view.action(), view.retained_pipeline().is_some());
let (stage_in, lengths) = (
view.stage_in_region(),
[0, 1].map(|index| view.threadgroup_memory_length(index).unwrap_or(0)),
);
let word_bytes = |word: usize, words: usize| word * 4..(word + words) * 4;
match field {
RecordField::Barrier(barrier) => {
put_word(bytes, 1, u32::from(barrier));
Ok(word_bytes(1, 1))
}
RecordField::Pipeline(pipeline) => {
put_u64(bytes, 2, pipeline.get());
if !retained {
return Ok(word_bytes(2, 2));
}
let state = layout::STATE as usize;
put_word(bytes, state / 4, 0);
Ok(8..state + 4)
}
RecordField::Buffer {
stage,
slot,
binding,
} => {
if slot >= BINDING_COUNT {
return Err(RecordError::Index {
index: slot,
count: BINDING_COUNT,
});
}
let (address, stride) = match binding {
None => (0, 0),
Some(binding) if binding.attribute_stride == Some(u64::MAX) => {
return Err(RecordError::ReservedStride);
}
Some(binding) => (
binding.address,
binding.attribute_stride.unwrap_or(u64::MAX),
),
};
let word = HEADER_WORDS + (stage.index() * BINDING_COUNT + slot) * BUFFER_WORDS;
put_u64(bytes, word, address);
put_u64(bytes, word + 2, stride);
Ok(word_bytes(word, BUFFER_WORDS))
}
RecordField::ThreadgroupMemoryLength { index, length } => {
if index >= THREADGROUP_COUNT {
return Err(RecordError::Index {
index,
count: THREADGROUP_COUNT,
});
}
// An indexed patch draw's control-point index buffer takes the first two
// lengths' words: a length of 0 there is the record's already.
if matches!(action, Action::DrawIndexedPatches { .. }) && index < 2 {
return match length {
0 => Ok(0..0),
_ => Err(RecordError::ThreadgroupMemoryLength),
};
}
put_word(bytes, THREADGROUP_WORD + index, length);
Ok(word_bytes(THREADGROUP_WORD + index, 1))
}
RecordField::StageInRegion(region) => {
// A draw whose arguments take the stage-in region's words has none.
if action.takes_stage_in_words() {
return match region {
[0, 0, 0, 0, 0, 0] => Ok(0..0),
_ => Err(RecordError::StageInRegion),
};
}
let first = layout::STAGE_IN as usize / 4;
for (index, &value) in region.iter().enumerate() {
put_word(bytes, first + index, value);
}
Ok(word_bytes(first, 6))
}
RecordField::ImageblockSize(size) => {
let at = layout::IMAGEBLOCK as usize;
for (index, value) in size.iter().enumerate() {
bytes[at + 2 * index..at + 2 * index + 2].copy_from_slice(&value.to_le_bytes());
}
Ok(at..at + 4)
}
RecordField::Action(new) => {
let wide = new.takes_stage_in_words();
if wide && stage_in != [0; 6] {
return Err(RecordError::StageInRegion);
}
let control_point_indices = match new {
Action::DrawIndexedPatches {
control_point_index_buffer,
..
} => Some(control_point_index_buffer),
_ => None,
};
if control_point_indices.is_some() && lengths != [0; 2] {
return Err(RecordError::ThreadgroupMemoryLength);
}
let (tag, arguments) = action_words(&new);
put_word(bytes, 0, tag);
let first = layout::ARGUMENTS as usize / 4;
for (index, value) in arguments.into_iter().enumerate() {
put_word(bytes, first + index, value);
}
// The stage-in region keeps its words beside a dispatch or a draw of primitives;
// an indexed or patch draw's arguments took them, and leave it none.
if !wide {
let stage_in_word = layout::STAGE_IN as usize / 4;
for (index, &value) in stage_in.iter().enumerate() {
put_word(bytes, stage_in_word + index, value);
}
}
let mut end = (first + layout::DRAW_ARGUMENT_WORDS) * 4;
// The first two threadgroup lengths' words: the control-point index buffer of an
// indexed patch draw, else the lengths, which one took and leaves 0.
let taken = matches!(action, Action::DrawIndexedPatches { .. });
if let Some(address) = control_point_indices {
put_u64(bytes, layout::CONTROL_POINT_INDICES as usize / 4, address);
end = layout::CONTROL_POINT_INDICES as usize + 8;
} else if taken {
put_word(bytes, THREADGROUP_WORD, lengths[0]);
put_word(bytes, THREADGROUP_WORD + 1, lengths[1]);
end = layout::THREADGROUP as usize + 8;
}
Ok(0..end)
}
}
}
}
fn require_length(bytes: &[u8]) -> Result<(), RecordError> {
if bytes.len() == COMMAND_BYTES {
Ok(())
@@ -973,6 +1023,152 @@ fn put_u64(bytes: &mut [u8], word: usize, value: u64) {
bytes[word * 4..word * 4 + 8].copy_from_slice(&value.to_le_bytes());
}
/// The tag and the argument words ([`layout::DRAW_ARGUMENT_WORDS`], zero past the action's) a
/// record of `action` holds.
fn action_words(action: &Action) -> (u32, [u32; layout::DRAW_ARGUMENT_WORDS]) {
match *action {
Action::Empty => (0, arguments([])),
Action::DispatchThreadgroups { grid, local_size } => (
1,
arguments([
grid[0],
grid[1],
grid[2],
local_size[0],
local_size[1],
local_size[2],
]),
),
Action::DispatchThreads { grid, local_size } => (
2,
arguments([
grid[0],
grid[1],
grid[2],
local_size[0],
local_size[1],
local_size[2],
]),
),
Action::DrawPrimitives {
primitive_type,
vertex_start,
vertex_count,
instance_count,
base_instance,
} => (
3,
arguments([
primitive_type,
vertex_start,
vertex_count,
instance_count,
base_instance,
]),
),
Action::DrawIndexedPrimitives {
primitive_type,
index_count,
index_type,
index_buffer,
instance_count,
base_vertex,
base_instance,
} => (
4,
arguments([
primitive_type,
index_count,
index_type,
instance_count,
index_buffer as u32,
(index_buffer >> 32) as u32,
base_vertex as u32,
base_instance,
]),
),
Action::DrawPatches {
control_points,
patch_start,
patch_count,
patch_index_buffer,
instance_count,
base_instance,
factor_buffer,
factor_instance_stride,
factor_scale,
} => (
5,
arguments([
control_points,
patch_start,
patch_count,
instance_count,
patch_index_buffer as u32,
(patch_index_buffer >> 32) as u32,
factor_buffer as u32,
(factor_buffer >> 32) as u32,
base_instance,
factor_instance_stride,
factor_scale,
]),
),
Action::DrawIndexedPatches {
control_points,
patch_start,
patch_count,
patch_index_buffer,
control_point_index_buffer: _,
instance_count,
base_instance,
factor_buffer,
factor_instance_stride,
factor_scale,
} => (
6,
arguments([
control_points,
patch_start,
patch_count,
instance_count,
patch_index_buffer as u32,
(patch_index_buffer >> 32) as u32,
factor_buffer as u32,
(factor_buffer >> 32) as u32,
base_instance,
factor_instance_stride,
factor_scale,
]),
),
Action::DrawMeshThreadgroups {
threadgroups: grid,
object_threads,
mesh_threads,
}
| Action::DrawMeshThreads {
threads: grid,
object_threads,
mesh_threads,
} => (
match action {
Action::DrawMeshThreadgroups { .. } => 7,
_ => 8,
},
arguments([
grid[0],
grid[1],
grid[2],
object_threads[0],
object_threads[1],
object_threads[2],
mesh_threads[0],
mesh_threads[1],
mesh_threads[2],
]),
),
}
}
/// An action's argument words, zero past them ([`layout::DRAW_ARGUMENT_WORDS`]).
fn arguments<const N: usize>(words: [u32; N]) -> [u32; layout::DRAW_ARGUMENT_WORDS] {
let mut all = [0; layout::DRAW_ARGUMENT_WORDS];
+130 -42
View File
@@ -4,8 +4,10 @@
//! use it; the binder's device replay decodes records on the device instead.
use super::descriptor::CommandDescriptor;
#[cfg(doc)]
use super::THREADGROUP_BUFFER_ARGUMENT_COUNT;
use super::{
layout, require_length, Action, Bindings, BufferBinding, BufferStage, CommandRecord,
layout, require_length, writes_of, Action, Bindings, BufferBinding, BufferStage, CommandRecord,
Inheritance, RecordError, StateSource, BINDING_COUNT, BUFFER_STAGES, BUFFER_WORDS,
COMMAND_BUFFER_HEADER_BYTES, COMMAND_BYTES, HEADER_WORDS, THREADGROUP_COUNT, THREADGROUP_WORD,
};
@@ -316,6 +318,28 @@ impl CommandRecord {
/// Decode persistent state without executing it or resolving its host resource identities.
pub fn decode(bytes: &[u8]) -> Result<Self, RecordError> {
RecordView::new(bytes).map(|view| view.record())
}
}
/// One record's bytes ([`COMMAND_BYTES`]), checked as [`CommandRecord::decode`] checks them, whose
/// fields read one at a time as `decode` reads them: a getter's read of one field, without
/// decoding the rest. `decode` is this view's [`record`](Self::record).
#[derive(Clone, Copy, Debug)]
pub struct RecordView<'a> {
bytes: &'a [u8],
action: Action,
barrier: bool,
/// The pipeline word: the pipeline the command executes with.
pipeline: Option<NonZeroU64>,
/// The state word says a reset retained it ([`CommandRecord::retained_pipeline`]).
retained: bool,
}
impl<'a> RecordView<'a> {
/// The record `bytes` hold, refused as [`CommandRecord::decode`] refuses them: its length, an
/// unknown action, a barrier flag other than 0 or 1, a malformed pipeline state word.
pub fn new(bytes: &'a [u8]) -> Result<RecordView<'a>, RecordError> {
let (action, barrier) = validate_record(bytes)?;
let pipeline = NonZeroU64::new(get_u64(bytes, 2));
let retained = match get_word(bytes, layout::STATE as usize / 4) {
@@ -323,52 +347,116 @@ impl CommandRecord {
layout::RETAINED if pipeline.is_some() => true,
_ => return Err(RecordError::PipelineState),
};
let mut record = Self {
Ok(RecordView {
bytes,
action,
barrier,
bindings: Bindings {
pipeline: pipeline.filter(|_| !retained),
..Default::default()
},
retained_pipeline: pipeline.filter(|_| retained),
..Default::default()
};
// An address and a stride of 0 are a slot no setter set, as Metal's getters answer a
// fresh slot's (and a nil buffer's set at offset 0 with stride 0, which is the same).
for (index, binding) in record.bindings.buffers.iter_mut().flatten().enumerate() {
let word = HEADER_WORDS + index * BUFFER_WORDS;
let address = get_u64(bytes, word);
let stride = get_u64(bytes, word + 2);
*binding = (address != 0 || stride != 0).then_some(BufferBinding {
address,
attribute_stride: (stride != u64::MAX).then_some(stride),
});
pipeline,
retained,
})
}
/// [`CommandRecord::action`].
pub fn action(&self) -> Action {
self.action
}
/// [`CommandRecord::barrier`].
pub fn barrier(&self) -> bool {
self.barrier
}
/// [`Bindings::pipeline`]: none where a reset retained the pipeline.
pub fn pipeline(&self) -> Option<NonZeroU64> {
self.pipeline.filter(|_| !self.retained)
}
/// [`CommandRecord::retained_pipeline`].
pub fn retained_pipeline(&self) -> Option<NonZeroU64> {
self.pipeline.filter(|_| self.retained)
}
/// Slot `slot` of `stage`'s buffers, as [`Bindings::buffers`] holds it; none past
/// [`BINDING_COUNT`].
pub fn buffer(&self, stage: BufferStage, slot: usize) -> Option<BufferBinding> {
(slot < BINDING_COUNT)
.then(|| binding_at(self.bytes, stage.index() * BINDING_COUNT + slot))
.flatten()
}
/// Threadgroup-memory length `index`, as [`CommandRecord::threadgroup_memory_lengths`] holds
/// it: 0 for the first two beside an indexed patch draw, whose control-point index buffer
/// takes their words; none past [`THREADGROUP_BUFFER_ARGUMENT_COUNT`].
pub fn threadgroup_memory_length(&self, index: usize) -> Option<u32> {
if index >= THREADGROUP_COUNT {
return None;
}
// An indexed patch draw's control-point index buffer takes the first two threadgroup
// lengths' words.
let lengths_from = match record.action {
Action::DrawIndexedPatches { .. } => 2,
_ => 0,
};
for (index, length) in record
.threadgroup_memory_lengths
.iter_mut()
.enumerate()
.skip(lengths_from)
{
*length = get_word(bytes, THREADGROUP_WORD + index);
}
// An indexed or patch draw's arguments take the stage-in region's words.
if !record.action.takes_stage_in_words() {
for (index, value) in record.stage_in_region.iter_mut().enumerate() {
*value = get_word(bytes, layout::STAGE_IN as usize / 4 + index);
let taken = matches!(self.action, Action::DrawIndexedPatches { .. }) && index < 2;
Some(match taken {
true => 0,
false => get_word(self.bytes, THREADGROUP_WORD + index),
})
}
/// [`CommandRecord::stage_in_region`]: all zero beside an indexed or patch draw, whose
/// arguments take its words.
pub fn stage_in_region(&self) -> [u32; 6] {
let mut region = [0; 6];
if !self.action.takes_stage_in_words() {
for (index, value) in region.iter_mut().enumerate() {
*value = get_word(self.bytes, layout::STAGE_IN as usize / 4 + index);
}
}
let imageblock = layout::IMAGEBLOCK as usize;
for (index, value) in record.imageblock_size.iter_mut().enumerate() {
let at = imageblock + 2 * index;
*value = u16::from_le_bytes([bytes[at], bytes[at + 1]]);
region
}
/// [`CommandRecord::imageblock_size`].
pub fn imageblock_size(&self) -> [u16; 2] {
let at = layout::IMAGEBLOCK as usize;
[
u16::from_le_bytes([self.bytes[at], self.bytes[at + 1]]),
u16::from_le_bytes([self.bytes[at + 2], self.bytes[at + 3]]),
]
}
/// [`CommandRecord::writes`] of the record.
pub fn writes(&self) -> crate::pipeline::CommandWrites {
writes_of(&self.action, self.barrier)
}
/// The whole record ([`CommandRecord::decode`]).
pub fn record(&self) -> CommandRecord {
let mut record = CommandRecord {
action: self.action,
barrier: self.barrier,
bindings: Bindings {
pipeline: self.pipeline(),
..Default::default()
},
retained_pipeline: self.retained_pipeline(),
stage_in_region: self.stage_in_region(),
imageblock_size: self.imageblock_size(),
..Default::default()
};
for (index, binding) in record.bindings.buffers.iter_mut().flatten().enumerate() {
*binding = binding_at(self.bytes, index);
}
Ok(record)
for (index, length) in record.threadgroup_memory_lengths.iter_mut().enumerate() {
*length = self.threadgroup_memory_length(index).unwrap_or(0);
}
record
}
}
/// The buffer binding at `index` of a record's four stages' slots, in their words' order: an
/// address and a stride of 0 are a slot no setter set, as Metal's getters answer a fresh slot's
/// (and a nil buffer's set at offset 0 with stride 0, which is the same).
fn binding_at(bytes: &[u8], index: usize) -> Option<BufferBinding> {
let word = HEADER_WORDS + index * BUFFER_WORDS;
let address = get_u64(bytes, word);
let stride = get_u64(bytes, word + 2);
(address != 0 || stride != 0).then_some(BufferBinding {
address,
attribute_stride: (stride != u64::MAX).then_some(stride),
})
}
@@ -16,22 +16,23 @@ mod buffer_views;
mod inheritance;
mod records;
/// Each resource ID's records lie at `2^63 + id * 2^40`, a range of 2^40 bytes of their own: ID 1's
/// starts at `2^63 + 2^40`, the last ID's range ends at 2^64, the null ID's lies below ID 1's, and
/// every one lies above every Metal address (below 2^63).
/// Each resource ID's records start at an address of their own, `2^63 + id * 2^31`, above every
/// Metal address (below 2^63): ID 1's at `2^63 + 2^31`, the null ID's below it, in the IDs' order,
/// and the last ID's 2^62 bytes below 2^64, so records of any length a device holds fit after it.
#[test]
fn each_records_id_has_a_range_of_its_own_above_the_metal_addresses() {
let span = 1u64 << RECORDS_ADDRESS_SHIFT;
fn each_records_id_has_a_start_of_its_own_above_the_metal_addresses() {
let stride = 1u64 << 31;
assert_eq!(records_address(0), 1 << 63);
assert_eq!(records_address(1), (1 << 63) + span);
assert_eq!(records_address(2) - records_address(1), span);
assert_eq!(records_address(1), (1 << 63) + stride);
assert_eq!(RECORDS_ID_LIMIT, 1 << 31);
let last = RECORDS_ID_LIMIT - 1;
assert_eq!(
u128::from(records_address(last)) + u128::from(span),
1u128 << 64
);
for id in [1, 2, 3, 65_536, 70_000, last] {
assert!(records_address(id) > records_address(id - 1), "{id}");
assert!(u128::from(records_address(last)) + (1u128 << 62) <= 1u128 << 64);
for id in [1, 2, 3, 65_536, 70_000, 1 << 26, (1 << 30) + 6, last] {
assert_eq!(
records_address(id) - records_address(id - 1),
stride,
"{id}"
);
assert_eq!(
(records_address(id) - RECORDS_ADDRESS_BASE) >> RECORDS_ADDRESS_SHIFT,
id
@@ -618,3 +618,322 @@ fn buffer_slots_hold_the_answers_of_metal_s_getters() {
None
);
}
/// A small deterministic generator for the field tests (xorshift64*).
struct Draws(u64);
impl Draws {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
/// A word that is often 0, else small or anything.
fn word(&mut self) -> u32 {
match self.below(4) {
0 => 0,
1 => self.below(8) as u32,
_ => self.next() as u32,
}
}
fn words<const N: usize>(&mut self) -> [u32; N] {
std::array::from_fn(|_| self.word())
}
fn action(&mut self) -> Action {
match self.below(9) {
0 => Action::Empty,
1 => Action::DispatchThreadgroups {
grid: self.words(),
local_size: self.words(),
},
2 => Action::DispatchThreads {
grid: self.words(),
local_size: self.words(),
},
3 => Action::DrawPrimitives {
primitive_type: self.word(),
vertex_start: self.word(),
vertex_count: self.word(),
instance_count: self.word(),
base_instance: self.word(),
},
4 => Action::DrawIndexedPrimitives {
primitive_type: self.word(),
index_count: self.word(),
index_type: self.word(),
index_buffer: self.next(),
instance_count: self.word(),
base_vertex: self.word() as i32,
base_instance: self.word(),
},
5 => Action::DrawPatches {
control_points: self.word(),
patch_start: self.word(),
patch_count: self.word(),
patch_index_buffer: self.next(),
instance_count: self.word(),
base_instance: self.word(),
factor_buffer: self.next(),
factor_instance_stride: self.word(),
factor_scale: self.word(),
},
6 => Action::DrawIndexedPatches {
control_points: self.word(),
patch_start: self.word(),
patch_count: self.word(),
patch_index_buffer: self.next(),
control_point_index_buffer: self.next(),
instance_count: self.word(),
base_instance: self.word(),
factor_buffer: self.next(),
factor_instance_stride: self.word(),
factor_scale: self.word(),
},
7 => Action::DrawMeshThreadgroups {
threadgroups: self.words(),
object_threads: self.words(),
mesh_threads: self.words(),
},
_ => Action::DrawMeshThreads {
threads: self.words(),
object_threads: self.words(),
mesh_threads: self.words(),
},
}
}
fn binding(&mut self) -> Option<BufferBinding> {
match self.below(4) {
0 => None,
_ => Some(BufferBinding {
address: match self.below(2) {
0 => u64::from(self.word()),
_ => self.next(),
},
attribute_stride: match self.below(3) {
0 => None,
1 => Some(u64::from(self.word())),
// All ones is reserved: the encoder refuses it.
_ => Some(self.next() | (u64::from(self.below(2) == 0) * u64::MAX)),
},
}),
}
}
fn stage(&mut self) -> BufferStage {
[
BufferStage::Kernel,
BufferStage::Vertex,
BufferStage::Fragment,
BufferStage::Object,
BufferStage::Mesh,
][self.below(5) as usize]
}
/// A record `encode_into` takes: random fields, a stage-in region only beside an action that
/// leaves its words, the first two lengths 0 beside an indexed patch draw, and a pipeline
/// set or retained, not both.
fn record(&mut self) -> CommandRecord {
let action = self.action();
let mut record = CommandRecord {
action,
barrier: self.below(2) == 0,
..Default::default()
};
let pipeline = NonZeroU64::new(self.next() * self.below(2));
match self.below(2) {
0 => record.bindings.pipeline = pipeline,
_ => record.retained_pipeline = pipeline,
}
for stage in BufferStage::of(false) {
for slot in record.bindings.buffers_mut(stage).iter_mut() {
*slot = self
.binding()
.filter(|b| b.attribute_stride != Some(u64::MAX));
}
}
for length in record.threadgroup_memory_lengths.iter_mut() {
*length = self.word();
}
if matches!(action, Action::DrawIndexedPatches { .. }) {
record.threadgroup_memory_lengths[..2].fill(0);
}
if !action.takes_stage_in_words() {
record.stage_in_region = self.words();
}
record.imageblock_size = [self.word() as u16, self.word() as u16];
record
}
fn field(&mut self) -> RecordField {
match self.below(7) {
0 => RecordField::Action(self.action()),
1 => RecordField::Barrier(self.below(2) == 0),
2 => RecordField::Pipeline(NonZeroU64::new(self.next() | 1).unwrap()),
3 => RecordField::Buffer {
stage: self.stage(),
slot: self.below(BINDING_COUNT as u64 + 2) as usize,
binding: self.binding(),
},
4 => RecordField::ThreadgroupMemoryLength {
index: self.below(THREADGROUP_COUNT as u64 + 2) as usize,
length: self.word(),
},
5 => RecordField::StageInRegion(match self.below(2) {
0 => [0; 6],
_ => self.words(),
}),
_ => RecordField::ImageblockSize([self.word() as u16, self.word() as u16]),
}
}
}
/// `record` with `field` set, as a setter of the field sets it; `None` past the record's slots.
fn with_field(mut record: CommandRecord, field: RecordField) -> Option<CommandRecord> {
match field {
RecordField::Action(action) => record.action = action,
RecordField::Barrier(barrier) => record.barrier = barrier,
RecordField::Pipeline(pipeline) => {
record.bindings.pipeline = Some(pipeline);
record.retained_pipeline = None;
}
RecordField::Buffer {
stage,
slot,
binding,
} => *record.bindings.buffers_mut(stage).get_mut(slot)? = binding,
RecordField::ThreadgroupMemoryLength { index, length } => {
*record.threadgroup_memory_lengths.get_mut(index)? = length
}
RecordField::StageInRegion(region) => record.stage_in_region = region,
RecordField::ImageblockSize(size) => record.imageblock_size = size,
}
Some(record)
}
/// A field written alone (`CommandRecord::write_field`) is the record decoded, the field set and
/// encoded again: over records `encode_into` wrote, byte for byte, and over bytes of any words
/// that decode, as what they decode to; where `encode_into` refuses the record with the field
/// set, or the field's index is past the record's, it refuses too and leaves the bytes as they
/// were. It writes nothing outside the bytes it answers. `RecordView` reads each field as
/// `decode` does.
#[test]
fn a_field_written_alone_is_the_record_encoded_again() {
let mut draws = Draws(0x9e37_79b9_7f4a_7c15);
let (mut written, mut refused) = (0, 0);
for round in 0..20_000 {
let mut bytes = vec![0u8; COMMAND_BYTES];
if round % 2 == 0 {
draws.record().encode_into(&mut bytes).unwrap();
} else {
// Words of any value, of a known action and barrier, with no state word.
for chunk in bytes.chunks_mut(8) {
chunk.copy_from_slice(&draws.next().to_le_bytes()[..chunk.len()]);
}
bytes[0..4].copy_from_slice(&(draws.below(9) as u32).to_le_bytes());
bytes[4..8].copy_from_slice(&(draws.below(2) as u32).to_le_bytes());
let state = layout::STATE as usize;
bytes[state..state + 4].fill(0);
}
let record = CommandRecord::decode(&bytes).unwrap();
let view = RecordView::new(&bytes).unwrap();
assert_eq!(view.record(), record, "round {round}: the view's record");
assert_eq!(view.writes(), record.writes(), "round {round}");
for stage in BufferStage::of(false)
.into_iter()
.chain([BufferStage::Mesh])
{
for slot in 0..BINDING_COUNT {
assert_eq!(
view.buffer(stage, slot),
record.bindings.buffers(stage)[slot],
"round {round}: {stage:?} slot {slot}"
);
}
assert_eq!(view.buffer(stage, BINDING_COUNT), None);
}
for index in 0..THREADGROUP_COUNT {
assert_eq!(
view.threadgroup_memory_length(index),
Some(record.threadgroup_memory_lengths[index])
);
}
assert_eq!(view.threadgroup_memory_length(THREADGROUP_COUNT), None);
let field = draws.field();
let mut expected = vec![0u8; COMMAND_BYTES];
let encoded =
with_field(record.clone(), field).map(|changed| changed.encode_into(&mut expected));
let before = bytes.clone();
let result = CommandRecord::write_field(&mut bytes, field);
match encoded {
Some(Ok(())) => {
let span = result
.unwrap_or_else(|error| panic!("round {round}: {field:?} refused: {error}"));
assert_eq!(
CommandRecord::decode(&bytes).unwrap(),
CommandRecord::decode(&expected).unwrap(),
"round {round}: {field:?} of {record:?}"
);
if round % 2 == 0 {
assert_eq!(bytes, expected, "round {round}: {field:?}, byte for byte");
}
for (at, (now, was)) in bytes.iter().zip(&before).enumerate() {
assert!(
now == was || span.contains(&at),
"round {round}: {field:?} wrote byte {at} outside {span:?}"
);
}
written += 1;
}
Some(Err(error)) => {
assert_eq!(result, Err(error), "round {round}: {field:?}");
assert_eq!(bytes, before, "round {round}: a refusal changes nothing");
refused += 1;
}
None => {
assert!(
matches!(result, Err(RecordError::Index { .. })),
"round {round}: {field:?}: {result:?}"
);
assert_eq!(bytes, before);
refused += 1;
}
}
}
assert!(
written > 15_000 && refused > 500,
"{written} written, {refused} refused"
);
}
/// A record that does not decode is refused as `decode` refuses it, by the view and by a field's
/// write, which changes nothing.
#[test]
fn a_field_of_a_record_that_does_not_decode_is_refused() {
let mut bytes = vec![0u8; COMMAND_BYTES];
bytes[0..4].copy_from_slice(&9u32.to_le_bytes());
assert_eq!(
RecordView::new(&bytes).map(|_| ()),
Err(RecordError::Action { value: 9 })
);
let before = bytes.clone();
assert_eq!(
CommandRecord::write_field(&mut bytes, RecordField::Barrier(true)),
Err(RecordError::Action { value: 9 })
);
assert_eq!(bytes, before);
assert_eq!(
RecordView::new(&bytes[1..]).map(|_| ()),
Err(RecordError::Length {
actual: COMMAND_BYTES - 1
})
);
}
@@ -1521,13 +1521,25 @@ pub(super) fn emit_word(
word.ok_or_else(|| cx.fail("an object word without a value"))
}
/// The wide pointer of guest address `guest` (a `u64`): the resident-set search ([`resolve`]).
pub(super) fn search(
/// The wide pointer of the resident allocation that starts at guest address `guest` (a `u64`):
/// the resident-set search ([`resolve`]), its hit kept only at the allocation's start, any other
/// address a miss, `(0, guest)`. Indirect command buffers' records are searched so: records longer
/// than the distance between two IDs' starts run past the next IDs' starts
/// (`indirect_commands::records_address`), and an ID whose own records are not resident then
/// misses rather than reaching into another's.
pub(super) fn search_start(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
guest: SValue,
) -> BResult<SValue> {
resolve(cx, fb, guest)
let p = resolve(cx, fb, guest)?;
let root = fb.composite_extract(p, &[0])?;
let off = fb.composite_extract(p, &[1])?;
let zero = k64(fb, 0)?;
let at_start = fb.binary(BinOp::IEqual, off, zero)?;
let root = fb.select(at_start, root, zero)?;
let off = fb.select(at_start, off, guest)?;
pair(fb, root, off)
}
/// The allocation of wide pointer `p` resolved for plain accesses in the function's coherence,
+10 -9
View File
@@ -5,7 +5,7 @@
//! indirect-command object. Its handle load (`memory::provenance::object_handle_load`) reads the
//! member's field, 8 bytes, as data ([`EncodeStrategy::Word`], a `u64`): a command buffer's word is
//! its resource ID, Metal's `gpuResourceID`, whose records lie at the guest address
//! `indirect_commands::records_address` of it, `2^63 + id * 2^40`; a pipeline state's word is the
//! `indirect_commands::records_address` of it, `2^63 + id * 2^31`; a pipeline state's word is the
//! template's host-registered token. A handle load is admitted only when every use of its value is
//! an encoder operand of its class ([`plan_objects`]): the command operand of an encoder operation,
//! or the pipeline operand of `air.set_pipeline_state_{compute,render}_command`. Any other use (an
@@ -13,9 +13,10 @@
//! (`ArgumentBufferObjects`, `pointer::select`), so no other instruction observes the word.
//!
//! **Operations** ([`EncodeStrategy::Command`]). The command word's records address is searched
//! in the resident set (`dynamic::search`), and the record buffer is accessed through its root
//! entry, contained: an access through root 0 (an address no resident allocation holds) is counted
//! under isolation and lands in the sink. Each operation reads the header's capacity, policy bits,
//! in the resident set for the allocation that starts there (`dynamic::search_start`), and the
//! record buffer is accessed through its root entry, contained: an access through root 0 (an
//! address at which no resident allocation starts) is counted under isolation and lands in the
//! sink. Each operation reads the header's capacity, policy bits,
//! and binding counts; when the write is valid by the descriptor policy
//! (`indirect_commands::Policy`) it writes the command's fields, and otherwise it sets the header's
//! sticky fault flag (a relaxed atomic store of 1) and writes nothing, exactly as the old engine's
@@ -672,9 +673,9 @@ fn k32(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<SValue> {
crate::memory::leaf::k32(fb, v)
}
/// The guest address of the records of the command buffer whose word (its resource ID, a `u64`)
/// is `word`: `indirect_commands::records_address`, the ID shifted up `RECORDS_ADDRESS_SHIFT`
/// bits past `RECORDS_ADDRESS_BASE`. No records lie at the null ID's.
/// The guest address the records of the command buffer whose word (its resource ID, a `u64`) is
/// `word` start at: `indirect_commands::records_address`, the ID shifted up
/// `RECORDS_ADDRESS_SHIFT` bits past `RECORDS_ADDRESS_BASE`. No records start at the null ID's.
fn records(fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
let shift = k64(fb, u64::from(RECORDS_ADDRESS_SHIFT))?;
let at = fb.binary(BinOp::ShiftLeftLogical, word, shift)?;
@@ -743,7 +744,7 @@ fn emit_command<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, c: &Comma
} = c.op.policy();
let word = cx.operand(fb, c.command)?;
let at = records(fb, word)?;
let p = dynamic::search(cx, fb, at)?;
let p = dynamic::search_start(cx, fb, at)?;
let b = dynamic::plain_base(cx, fb, p)?;
let capacity = header(cx, fb, b, layout::CAPACITY)?;
let policy = header(cx, fb, b, layout::POLICY)?;
@@ -925,7 +926,7 @@ fn emit_command<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, c: &Comma
} => {
let word = cx.operand(fb, *source)?;
let at = records(fb, word)?;
let p = dynamic::search(cx, fb, at)?;
let p = dynamic::search_start(cx, fb, at)?;
let base = dynamic::plain_base(cx, fb, p)?;
let source_capacity = header(cx, fb, base, layout::CAPACITY)?;
let source_policy = header(cx, fb, base, layout::POLICY)?;
+3 -1
View File
@@ -17,7 +17,9 @@
//! through it out of bounds). Entry 1 is the write-only sink (`host` its device address). Entry
//! `2 + n` is `[[buffer(n)]]`. The **resident set** (the bound arguments and
//! `BindState.used_resources`, overlaps coalesced into the outermost range) is the entries `R0 ..
//! R0 + N`, sorted by `guest` and disjoint, each with `bind_offset = 0`. The binder states `R0` and
//! R0 + N`, sorted by `guest` and disjoint but for indirect command buffers' records, which may
//! overlap (each found only at its start, `lower::access::dynamic::search_start`), each with
//! `bind_offset = 0`. The binder states `R0` and
//! `N` in the sink entry's otherwise unread `guest` and `size` fields ([`RESIDENT_FIRST`],
//! [`RESIDENT_COUNT`]); `N` is any count (At most 2¹⁶ before, a larger set
//! `BindError::ResidentSetTooLarge`). `R0` counts entries from the table's address modulo 2⁶⁴, so
+2 -1
View File
@@ -785,6 +785,8 @@ surface! {
enum ComputeDispatch E;
struct Inheritance E;
enum RecordError E;
enum RecordField E;
struct RecordView<'static> O;
struct RegisteredBuffer<'static, u8> O;
struct RenderDraws E;
struct ResolvedBindings O;
@@ -794,7 +796,6 @@ surface! {
const COMMAND_BUFFER_HEADER_BYTES;
const COMMAND_BYTES;
const RECORDS_ADDRESS_BASE;
const RECORDS_ADDRESS_SHIFT;
const RECORDS_ID_LIMIT;
const THREADGROUP_BUFFER_ARGUMENT_COUNT;
fn records_address;
+51 -39
View File
@@ -823,8 +823,10 @@ reads no buffer and no `[[primitive_id]]` may instead merge into one draw (`Draw
two merge passes (`draw_merge_module`) write each command's first vertex in the merged draw, and
the vertex function, compiled as its merged variant (`VariantKey::merged_draws`), finds its
command by that prefix and runs the command's vertex, instance and buffers, in the commands'
order. A kernel that encodes commands writes the records at
`bind::indirect_commands::records_address` of the buffer's ID, outside every Metal address.
order. A kernel that encodes commands writes the records that start at
`bind::indirect_commands::records_address` of the buffer's ID, outside every Metal address, and
finds them only at their start: records may run past later IDs' starts, and a resident set
(`bind::ResidentSet`) keeps each records range whole.
## 7. Caching
@@ -1397,25 +1399,28 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
records such an execution on the CPU then where the GPU cannot run it alone. A render execution:
where its records may hold, at the commit or as its batch is ready, more than draws of one
primitive type under the encoder's state, or what its check looks for; its notice names the first
rule that kept it from the GPU alone. A compute execution: with the caller's check
(`execute_commands_in_buffer_checked`); with its range read from a buffer; of a
buffer that inherits the encoder's buffers; where its records may name a pipeline state whose
kernel observes its threadgroup partition or fetches `[[stage_in]]` attributes, or a state the CPU
set that the program released since; and, on a device without `VK_EXT_device_generated_commands`,
where the host step is faster: where its commands run with no barrier between them and its
commands times the pipeline states its records may name past four pass 256 (the states: every live
one made with `supportIndirectCommandBuffers`, or the encoder's where the buffer inherits it),
where they run with one and its commands times the states past twelve pass 512, and where its
commands times its states pass 32,768. Every other execution runs on the GPU alone and announces
nothing. Cost: one GPU-to-CPU round trip per execution: its command buffer's work before it, and
every batch submitted before that on any queue, completes before the CPU records its commands from
their records and submits the rest; the device's scheduler submits nothing else while it records
them, and the first command of a threadgroup size or threadgroup lengths its pipeline state has
not dispatched makes that VkPipeline then. The commands run in the large-buffer form (their
range-limited buffer slots at device addresses, with in-shader bounds checks), whose variants the
commit compiles for every pipeline state a record may name (or, for an execution committed before
the buffer was made resident for writing, the use_resource call that made it so); without device
addresses, a command's first buffer shape compiles its variant then.
rule that kept it from the GPU alone. A compute execution: with a caller's check
(`execute_commands_in_buffer_checked`) that may see what it looks for
(`IndirectCommandCheckNeeds`: a state that may encode indirect commands, the encoder's where the
buffer inherits it, else one its records may name), at the commit or as its batch is ready; with
its range read from a buffer; of a buffer that inherits the encoder's buffers; where its records
may name a pipeline state whose kernel observes its threadgroup partition or fetches
`[[stage_in]]` attributes, or a state the CPU set that the program released since; and, on a
device without `VK_EXT_device_generated_commands`, where the host step is faster: where its
commands run with no barrier between them and its commands times the pipeline states its records
may name past four pass 256 (the states: every live one made with `supportIndirectCommandBuffers`,
or the encoder's where the buffer inherits it), where they run with one and its commands times the
states past twelve pass 512, and where its commands times its states pass 32,768. Every other
execution runs on the GPU alone and announces nothing. Cost: one GPU-to-CPU round trip per
execution: its command buffer's work before it, and every batch submitted before that on any
queue, completes before the CPU records its commands from their records and submits the rest; the
device's scheduler submits nothing else while it records them, and the first command of a
threadgroup size or threadgroup lengths its pipeline state has not dispatched makes that
VkPipeline then. The commands run in the large-buffer form (their range-limited buffer slots at
device addresses, with in-shader bounds checks), whose variants the commit compiles for every
pipeline state a record may name (or, for an execution committed before the buffer was made
resident for writing, the use_resource call that made it so); without device addresses, a
command's first buffer shape compiles its variant then.
- `metal2vulkan-degrade-uncalibrated-gpu-times` (precision). `UncalibratedGpuTimes`: A command
buffer's GPU times on a device that calibrates its timestamps against no host clock the runtime
reads (no `VK_KHR_calibrated_timestamps` or `VK_EXT_calibrated_timestamps` with the device's time
@@ -1837,10 +1842,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
(VUID-vkCreateDescriptorSetLayout-support-09582).
- `metal2vulkan-degrade-released-command-state` (precision). `ReleasedCommandState`: An indirect
command naming the ID of a pipeline state the program released is executed where the runtime
cannot run what Metal runs. Cost: a command naming another ID than the state set on it runs
nothing, where Metal runs the released state's program; one naming that state's ID runs its
program, as Metal runs a command the CPU encoded, where for a record the GPU wrote Metal runs the
ID's holder since (nothing, for a state of the other kind).
cannot run what Metal runs. A record the GPU wrote runs the state that held the ID as the GPU
last could write the buffer's records, released since or not, as Metal's does: a buffer the GPU
may write keeps the programs of the states released after a command buffer that may write it
was first encoded. Cost: a command whose record the GPU wrote naming a state released before its
buffer could be written runs nothing, where Metal runs that state's program; one naming the ID
of the state set on it runs its program, as Metal runs a command the CPU encoded, where for a
record the GPU wrote while another state held the ID Metal runs that state (nothing, for a
state of the other kind).
- `metal2vulkan-degrade-ycbcr-filter-not-exact` (precision). `YCbCrFilterNotExact`: A pipeline
stage's filtered sample of a texture slot bound to a two-plane YCbCr texture does not take Metal's
exact filter of the format: the stage records `PrecisionNote::HalfSampleFilter` or
@@ -1993,18 +2002,12 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
started alike, which the runtime's is not measured to be: a pipeline state's made with
`supportIndirectCommandBuffers` (`ComputePipelineState::unique_identifier`,
`RenderPipelineState::unique_identifier`, an indirect command's state identifier other than 0), or
an indirect command buffer's made after its device opened a command encoder
an indirect command buffer's made after a command buffer of its device that encoded a render
encoder was scheduled, or after a resource state encoder opened
(`IndirectCommandBuffer::unique_identifier`). Cost: the identifier is unique and fixed for its
holder's life, and a released one is reused as Metal reuses it, but it is not the number Metal
answers there, which follows how the process was started, what it made and Metal's own encoders'
allocations.
- `metal2vulkan-degrade-indirect-value-past-record` (precision). `IndirectValuePastRecord`: A
program set a buffer at a slot past 31, or a threadgroup memory length at an index past 30, of a
command of an indirect command buffer whose descriptor counts more: Metal's validation stops such
a descriptor, and plain Metal keeps the value for its private getters alone, as no function binds
past index 30. Cost: the command's read-back (Metal's private getters) answers a fresh command's
value for a buffer slot past 31 or a threadgroup length past 30, where Metal answers the value
set; no command runs otherwise.
- `metal2vulkan-degrade-cross-class-texture-neutral` (precision). `CrossClassTextureNeutral`: A draw
or dispatch that binds, at a texture slot, a texture whose format's numeric class (float, signed
or unsigned integer) is not the class the function declares there and that its plan has no exact
@@ -2822,7 +2825,8 @@ each item named states the rule in full.
buffer resident has not completed.
- **Resource IDs are numbered as Metal numbers them**: textures', sampler states', pipeline states'
and indirect command buffers' IDs follow Metal's allocator, around reservations
(`Device::reserve_resource_ids`) too. IDs that end Metal's process are refused.
(`Device::reserve_resource_ids`) too. IDs that end Metal's process, or whose reservation Metal
never returns from, are refused.
- **The device counts the sampler IDs it holds** (`Device::sampler_ids_live`,
`Device::sampler_id_pool_size`), runtime extensions for a consumer that models Metal's sampler
heap.
@@ -2842,7 +2846,10 @@ each item named states the rule in full.
**Indirect command buffers**
- **A command's read-back answers Metal's private getters**: `command_type`, the buffer addresses
and attribute strides, as Metal's `get*` getters answer them.
and attribute strides, as Metal's `get*` getters answer them. `IndirectComputeCommand` and
`IndirectRenderCommand` read one field of their record alone (`command_type`, `has_barrier`,
`dispatch` or `draw`, one buffer slot, `pipeline_unique_identifier`, and the rest), as
`IndirectCommandBuffer::commands` reads it, without decoding the whole command.
- **Whether the GPU may have written the records** (`IndirectCommandBuffer::gpu_written`, no Metal
counterpart) turns true at the first call that lets GPU work write them; from then on an
execution runs the records as they stand once the work before it completed.
@@ -2864,10 +2871,15 @@ each item named states the rule in full.
where what the records may hold grew by the time the pass's batch is ready to submit, a host step
records the pass.
- **A checked execution states what its check looks for**
(`execute_commands_in_buffer_checked`'s `IndirectCommandCheckNeeds`, no Metal counterpart): draws
of points, and commands under states that may encode indirect commands. Where what the records
may hold rules out every kind the check names (`IndirectCommandCheckNeeds::ALL` names both), the
check has nothing to see, is never called, and the execution may run on the GPU alone.
(`execute_commands_in_buffer_checked`'s and `execute_commands_in_buffer_indirect_checked`'s
`IndirectCommandCheckNeeds`, no Metal counterpart): draws of points, and commands under states
that may encode indirect commands. The check is called with each command the runtime records,
before it records any, wherever it reads the records: at `commit` for the CPU's records, in a
host step for records the GPU may have written. Where what the records may hold rules out every
kind the check names (`IndirectCommandCheckNeeds::ALL` names both; a record of no draw and no
dispatch runs nothing), the check has nothing to see, is not called, and the execution may run
on the GPU alone, render and compute alike; where that grows by the time the batch is ready, a
host step records it and calls the check.
- **Command predication** (`encode_start_if`, `encode_start_else`, `encode_end_if` and the
while and do-while loops) runs Metal's blocks and loops on every device, with or without
buffer device addresses, its unbalanced records answering `NO` and dropping their ranges, and
+8
View File
@@ -534,3 +534,11 @@ driver's. Each is open work.
`mesh_order_mesh` or `mesh_order_solo` ends the process inside lavapipe's compiler ("LLVM ERROR:
Cannot emit physreg copy instruction"); the validation case `mesh_order_mesh-payload-mesh-draw`
runs on a GPU only. The construct behind the abort is not isolated yet.
- **A record the GPU wrote before its ID changed holder, in a buffer the GPU wrote again since.**
A record the GPU wrote names the state that held its ID as the GPU last could write the
buffer's records (`released_programs.rs`). Where a command buffer wrote the record, another
state took its ID, and a later command buffer that may write the buffer completed without
rewriting it, the record runs and answers the later holder, where Metal's runs the state its
write resolved. No note announces it. The exact form needs the GPU's write to carry its
resolution: a word of the record the translated setter fills from a per-dispatch stamp of the
device's IDs, which the host step, the getter and the GPU-alone preprocess resolve.
+42 -32
View File
@@ -14,14 +14,14 @@ Columns:
- `none`: no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets;
- `?`: not assessed yet.
Generated at `0021bc8b1`.
Generated at `ce4b23e12`.
## Totals
| Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed |
|---|---|---|---|---|---|---|---|
| Translator and front-end refusals | 124 | 124 | 6 | 33 | 68 | 17 | 0 |
| Runtime gaps | 64 | 64 | 1 | 8 | 41 | 14 | 0 |
| Translator and front-end refusals | 125 | 125 | 6 | 33 | 68 | 18 | 0 |
| Runtime gaps | 68 | 68 | 1 | 8 | 41 | 18 | 0 |
| Apple-only calls | 9 | 9 | 1 | 0 | 0 | 8 | 0 |
| Binder refusals at a device limit | 9 | 9 | 0 | 1 | 7 | 1 | 0 |
| Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 |
@@ -54,7 +54,7 @@ Generated at `0021bc8b1`.
| `SimdgroupMatrix` | Simdgroup matrix operations | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/simd/matrix.rs:83` | `rare`: simdgroup matrix kernels |
| `ArgumentBufferPointers` | Argument buffers holding buffer pointers (dynamic roots) | devices without buffer device addresses (`addressed_needs`) | 1: `crates/metal2vulkan/src/device/metal.rs:236` | `app`: argument buffers holding buffer pointers |
| `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices short of a device limit the site names; devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`needs`); every device (not implemented) | 17: `crates/metal2vulkan-runtime/src/families/features.rs:1621`, `crates/metal2vulkan-runtime/src/pipeline/objects.rs:1036` (+15) | `app`: argument buffers holding textures and samplers (bindless) |
| `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | 5: `crates/metal2vulkan/src/lower/access/encode.rs:445`, `crates/metal2vulkan/src/lower/access/encode.rs:495` (+3) | `rare`: pipeline states and ICBs in argument buffers |
| `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | 5: `crates/metal2vulkan/src/lower/access/encode.rs:446`, `crates/metal2vulkan/src/lower/access/encode.rs:496` (+3) | `rare`: pipeline states and ICBs in argument buffers |
| `DereferenceLoadedPointer` | Dereferencing a pointer loaded from memory or made from an integer | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | 4: `crates/metal2vulkan/src/lower/access/dynamic.rs:407`, `crates/metal2vulkan/src/lower/access/local.rs:774` (+2) | `app`: pointers loaded from argument buffers |
| `PointerToInteger` | Storing a pointer or converting it to an integer | - | via a helper: 1: `crates/metal2vulkan/src/lower/access/dynamic.rs:347` | `rare`: pointer to integer casts |
| `PointerCompare` | Comparing pointers with different roots | - | via a helper: 1: `crates/metal2vulkan/src/lower/access/copy.rs:717` | `rare`: comparing pointers of different roots |
@@ -82,7 +82,7 @@ Generated at `0021bc8b1`.
| `SamplerLodBias` | Sampler LOD bias | devices short of a Vulkan feature the site names; devices without VkLimit::MaxSamplerLodBias; every device (no Vulkan mechanism) | 3: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:258`, `crates/metal2vulkan/src/lower/sampler/constexpr.rs:265` (+1) | `app`: constexpr samplers with an LOD bias |
| `SamplerCompare` | Sampler compare functions outside what Vulkan allows for the image | devices short of a Vulkan feature the site names | 1: `crates/metal2vulkan/src/metal/sampler.rs:260` | `app`: compare samplers a device cannot apply to the image |
| `PixelSamplerCompare` | A constexpr sampler with pixel coordinates and a compare function, which Apple's compiler rejects ("invalid values combination in sampler... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:115` | `none`: Apple's compiler rejects it |
| `TexelBuffer` | Texture buffers beyond the device's texel-buffer limits | devices without a format's usage; every device (no Vulkan mechanism) | 3: `crates/metal2vulkan/src/bind/instantiate.rs:879`, `crates/metal2vulkan/src/bind/instantiate.rs:885` (+1) | `app`: texture buffers past a device's texel-buffer limits |
| `TexelBuffer` | Texture buffers beyond the device's texel-buffer limits | devices without a format's usage; every device (no Vulkan mechanism) | 3: `crates/metal2vulkan/src/bind/instantiate.rs:880`, `crates/metal2vulkan/src/bind/instantiate.rs:886` (+1) | `app`: texture buffers past a device's texel-buffer limits |
| `RasterOrderGroups` | Raster order groups without fragment shader interlock | devices without VkFeature::FragmentShaderPixelInterlock; devices without VkFeature::FragmentShaderSampleInterlock; devices without a capability the site computes (`alternatives`); every device (not implemented) | 4: `crates/metal2vulkan/src/device/metal.rs:242`, `crates/metal2vulkan/src/lower/fragment/rog.rs:151` (+2) | `rare`: raster order groups |
| `FramebufferFetch` | Framebuffer fetch without an ordered form on the device (rasterization-order attachment access, or the pixel interlock's storage form where the... | devices short of a Vulkan property the site names; devices without VkFeature::FragmentShaderPixelInterlock; devices without VkFeature::RasterizationOrderColorAttachmentAccess; devices without VkFeature::SampleRateShading; devices without a capability the site computes; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); devices without a capability the site computes (`capability`); devices without a capability the site computes (`missing`); devices without a format's usage; drivers with a defect; every device (not implemented) | 26: `crates/metal2vulkan-runtime/src/families/features.rs:1007`, `crates/metal2vulkan-runtime/src/render.rs:5709` (+24) | `system`: programmable blending (framebuffer fetch); macOS 26.6.2's login reaches it (two WindowServer and RenderBox pipelines fetch RGB10A8_2P_XR10 attachments, the consumer's boots) |
| `PrimitiveId` | `[[primitive_id]]` in a fragment function | devices without a capability the site computes; every device (not implemented) | 3: `crates/metal2vulkan-runtime/src/families/features.rs:1115`, `crates/metal2vulkan/src/lower/stage_io/plan.rs:3112` (+1) | `rare`: primitive_id on a device without geometry or tessellation shaders, in an indexed draw or behind a mesh function |
@@ -96,7 +96,7 @@ Generated at `0021bc8b1`.
| `PixelCoverageAtSampleRate` | The pixel's coverage (`[[sample_mask]]` read) in a fragment function that runs once per sample | drivers with a defect; every device (no Vulkan mechanism); every device (not implemented) | 3: `crates/metal2vulkan/src/lower/fragment/coverage.rs:291`, `crates/metal2vulkan/src/lower/simd/mod.rs:754` (+1) | `rare`: coverage read at sample rate |
| `InterfaceComponents` | Too many interface components or locations | devices short of a device limit the site names; devices without VkLimit::MaxColorAttachments; devices without VkLimit::MaxVertexInputAttributes | 4: `crates/metal2vulkan/src/pipeline/compile/color_group.rs:202`, `crates/metal2vulkan/src/pipeline/link/graphics.rs:301` (+2) | `rare`: too many varyings or attachments for a device |
| `UnmatchedVarying` | A fragment input without a vertex producer (a Metal link error) | every device (no Vulkan mechanism) | 3: `crates/metal2vulkan/src/pipeline/link/varyings.rs:318`, `crates/metal2vulkan/src/pipeline/link/varyings.rs:537` (+1) | `none`: a Metal link error |
| `KernelStageIn` | Kernel `[[stage_in]]` | every device (not implemented) | 3: `crates/metal2vulkan-runtime/src/indirect_execute.rs:350`, `crates/metal2vulkan/src/bind/dispatch.rs:877` (+1) | `rare`: kernel stage-in combinations Metal leaves unestablished |
| `KernelStageIn` | Kernel `[[stage_in]]` | every device (not implemented) | 3: `crates/metal2vulkan-runtime/src/indirect_execute.rs:376`, `crates/metal2vulkan/src/bind/dispatch.rs:877` (+1) | `rare`: kernel stage-in combinations Metal leaves unestablished |
| `Tessellation` | Tessellation | devices without VkLimit::MaxPushConstantsSize; devices without VkLimit::MaxStorageBufferRange; devices without VkLimit::MaxTessellationGenerationLevel; every device (not implemented) | 13: `crates/metal2vulkan-air/src/canon/mod.rs:1256`, `crates/metal2vulkan-air/src/canon/mod.rs:1347` (+11) | `rare`: tessellation |
| `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxMeshOutputLayers; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | 7: `crates/metal2vulkan/src/bind/graphics.rs:1536`, `crates/metal2vulkan/src/bind/graphics.rs:2966` (+5) | `rare`: mesh pipelines |
| `TileShading` | | devices without VkLimit::MaxStorageBufferRange; devices without a format's usage; every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs:521`, `crates/metal2vulkan/src/bind/plan/compute.rs:237` (+3) | `rare`: tile shaders (Apple GPU families) |
@@ -134,7 +134,7 @@ Generated at `0021bc8b1`.
| `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | devices short of a Vulkan feature the site names; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/binding_view.rs:167`, `crates/metal2vulkan-runtime/src/texture.rs:980` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured |
| `MipmapGeneration` | `generateMipmapsForTexture:` where the device's filter is not shown to give Metal's answer | devices without VkFeature::ShaderInt64; devices without a format's usage; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/blit_texture.rs:1787`, `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37` (+5) | `app`: generateMipmapsForTexture: where the device's filter is not Metal's |
| `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/host_memory.rs:393`, `crates/metal2vulkan-runtime/src/host_memory.rs:433` (+3) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory |
| `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2546` | `rare`: GPU times on a queue without timestamps |
| `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2555` | `rare`: GPU times on a queue without timestamps |
| `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | devices without VkFeature::OcclusionQueryPrecise | 1: `crates/metal2vulkan-runtime/src/visibility.rs:452` | `rare`: counting occlusion queries on a device without precise queries |
| `ViewFormatReinterpretation` | A texture view whose format has other components, or components of other widths, than its texture's (`RGBA8Unorm` as `R32Uint`), on a device whose... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/view_plan.rs:568` | `app`: a view of another component layout on a portability subset (MoltenVK) |
| `SeparateMultisampledDepthStencil` | A render pass whose depth and stencil attachments are separate multisampled textures that it loads or may store, on a device without maintenance8,... | - | via a helper: 7: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:188`, `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:294` (+5) | `rare`: separate multisampled depth and stencil textures |
@@ -149,11 +149,12 @@ Generated at `0021bc8b1`.
| `ViewportDepthRange` | A viewport depth range past `[0, 1]` (`setViewport:`), which Metal takes and the runtime draws natively (`VK_EXT_depth_range_unrestricted`) or... | drivers with a defect | 1: `crates/metal2vulkan-runtime/src/render_state.rs:1186` | `rare`: viewport depth outside [0, 1] |
| `UndeclaredTextureUsage` | A shader write to a texture made without `ShaderWrite` (or `ShaderAtomic`), or a read of one made without `ShaderRead`, which plain Metal runs,... | every device (not implemented) | 2: `crates/metal2vulkan-runtime/src/binding_view.rs:141`, `crates/metal2vulkan-runtime/src/texture/usage_shadow.rs:72` | `app`: a shader write to a texture made without ShaderWrite, which plain Metal runs |
| `RenderTargetSize` | A render pass whose render area or layers are past the device's framebuffer limits (`Capability::Limit` names `MaxFramebufferWidth`,... | devices short of a device limit the site names | 1: `crates/metal2vulkan-runtime/src/render_pass.rs:1264` | `rare`: a render area past a device's framebuffer limits |
| `IndirectRenderState` | A render state a function sets on an indirect render command (`render_command::set_cull_mode`, `set_front_facing_winding`,... | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/access/encode.rs:567` | `rare`: render state set by a kernel on an indirect command |
| `IndirectRenderState` | A render state a function sets on an indirect render command (`render_command::set_cull_mode`, `set_front_facing_winding`,... | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/access/encode.rs:568` | `rare`: render state set by a kernel on an indirect command |
| `GlobalBuiltinInFragment` | A fragment function's read of a Metal 3.1 program-scope built-in variable that Metal does not lower there | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/select.rs:912` | `rare`: Metal 3.1 global built-ins in fragment functions |
| `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | every device (not implemented) | 4: `crates/metal2vulkan/src/bind/heap.rs:1300`, `crates/metal2vulkan/src/bind/plan/resources.rs:887` (+2) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) |
| `ExtendedRangeBlend` | Metal's blend into an extended-range attachment (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins), which the function computes... | every device (not implemented) | 4: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:305`, `crates/metal2vulkan/src/lower/fragment/fetch.rs:1553` (+2) | `system`: the parts of a blend into an extended-range (XR10) attachment the measured model does not hold (second-source factors, the color blend color difference, a one-color-channel mask, float4 and sRGB outside the measured forms); the consumer's guests blend RGB10A8_2P_XR10 attachments |
| `TileReach` | The tiles a render pass's primitives reach, binned on the device ([`tile_reach_module`](crate::bind::tile_reach_module)), on a device without what... | devices short of a Vulkan feature the site names; devices without a capability the site computes (`vec![int64]`); every device (not implemented) | 3: `crates/metal2vulkan/src/bind/tile_reach.rs:270`, `crates/metal2vulkan/src/lower/stage_io/plan.rs:2450` (+1) | `app`: the tiles a pass's draws reach, binned on a device without shaderInt64 |
| `CommandPredication` | Metal's private command predication (`encodeStartIf:offset:comparison:referenceValue:` and the rest), whose step module... | devices without buffer device addresses (`addressed_needs`) | 1: `crates/metal2vulkan/src/bind/replay/predication.rs:414` | `none`: Apple-private command predication on a device without buffer device addresses |
| `ProgramScopeBinding` | A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p [[buffer(n)]];` in Apple's `!air.global_bindings` list,... | - | via a helper: 2: `crates/metal2vulkan-air/src/abi/module.rs:77`, `crates/metal2vulkan/src/error/mod.rs:267` | `app`: MSL 3.2 program-scope buffer bindings (macOS 15 and later) |
| `SeqCstFence` | A sequentially consistent fence (`seq_cst` `atomic_thread_fence`, an LLVM `fence seq_cst`, or a `seq_cst` barrier ordering device memory), whose... | devices short of a Vulkan feature the site names | 1: `crates/metal2vulkan/src/lower/sync/barrier.rs:443` | `rare`: a seq_cst fence in a vertex or fragment stage without its stores and atomics |
@@ -169,9 +170,9 @@ Generated at `0021bc8b1`.
| `HeapTextureAlignment` | A heap texture whose image needs an alignment past the heap memory's base alignment (256 KiB) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:980` | `rare`: a heap texture needing more than 256 KiB alignment |
| `HeapTextureMemory` | A heap texture whose image the heap's memory type does not take | every device (runtime piece not built) | 5: `crates/metal2vulkan-runtime/src/texture/heap.rs:1418`, `crates/metal2vulkan-runtime/src/texture/heap.rs:1425` (+3) | `app`: a heap texture the heap's memory type does not take |
| `FunctionTablePastMaxBufferLength` | A visible-function table of more entries than one buffer of the device's `max_buffer_length` holds words for, or than its size word holds | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/function_table.rs:622` | `none`: a function table past one buffer |
| `IndirectCommandBufferPastMaxBufferLength` | An indirect command buffer of more commands than one buffer of the device's `max_buffer_length` holds the records of | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:516` | `none`: an ICB past one buffer |
| `IndirectRenderCommands` | What indirect command buffers lack of their render commands | every device (runtime piece not built) | 17: `crates/metal2vulkan-runtime/src/compute.rs:1103`, `crates/metal2vulkan-runtime/src/compute.rs:1183` (+15) | `rare`: indirect render commands' remaining pieces |
| `IndirectImageblockSize` | An indirect compute command's imageblock side past 65535, which Metal keeps | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:2757` | `none`: an imageblock side past 65535 |
| `IndirectCommandBufferPastMaxBufferLength` | An indirect command buffer of more commands than one buffer of the device's `max_buffer_length` holds the records of | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:522` | `none`: an ICB past one buffer |
| `IndirectRenderCommands` | What indirect command buffers lack of their render commands | every device (runtime piece not built) | 17: `crates/metal2vulkan-runtime/src/compute.rs:1091`, `crates/metal2vulkan-runtime/src/compute.rs:1171` (+15) | `rare`: indirect render commands' remaining pieces |
| `IndirectImageblockSize` | An indirect compute command's imageblock side past 65535, which Metal keeps | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:3351` | `none`: an imageblock side past 65535 |
| `CommandReplay` | The device replay of indirect command buffers | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/binding.rs:694`, `crates/metal2vulkan-runtime/src/binding.rs:697` | `rare`: the device replay of indirect command buffers |
| `RenderAttachments` | Render attachments and their binding forms | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/binding.rs:1839` | `rare`: render attachment forms not built |
| `AccelerationStructures` | Acceleration structures | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/binding.rs:1842` | `rare`: ray tracing (out of scope by ruling) |
@@ -222,7 +223,11 @@ Generated at `0021bc8b1`.
| `DetachedTexelAccess` | `Texture::replace_region` or `get_bytes` of a texture whose bytes (a no-copy buffer's or heap's) are detached (`detach_backing`) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture.rs:4820` | `none`: CPU texel access while a runtime extension detached the bytes |
| `SurfaceDepthStencil` | A use of a texture of a depth or stencil format (`Depth16Unorm`, `Depth32Float`, `Depth32Float_Stencil8`, `Stencil8`, `X32_Stencil8`) over a plane... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/blit_texture.rs:236`, `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:57` | `rare`: a blit of the stencil of a Depth32Float_Stencil8 texture over a plane of an IOSurface with planes, or a pass on an X32_Stencil8 one's view as Depth32Float_Stencil8 |
| `HostHeapUncompressedMultisample` | A multisample texture in a heap over host pages (`Device::new_heap_with_bytes_no_copy`) that Metal keeps uncompressed | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:1924` | `none`: a multisample texture Metal keeps uncompressed in a runtime extension's heap over host pages |
| `PredicationDropsUngatedWork` | An unbalanced command-predication record (`ComputeCommandEncoder::encode_end_if` and the other ends, or `encode_start_else`, with no block open;... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:730` | `none`: an unbalanced Apple-private command-predication record as its unit's first, after dispatches of the unit |
| `PredicationUnbalanced` | An unbalanced command-predication record (`ComputeCommandEncoder::encode_end_if` and the other ends, or `encode_start_else`, with no block open;... | every device (runtime piece not built) | 4: `crates/metal2vulkan-runtime/src/predication.rs:371`, `crates/metal2vulkan-runtime/src/predication.rs:403` (+2) | `none`: an unbalanced Apple-private command-predication record, whose dropped work Metal decides by no rule measured |
| `PredicationOpenAtUnitEnd` | A command buffer one of whose units of predication ended with an If still open that no misused record killed, refused at `CommandBuffer::commit` | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/predication.rs:280`, `crates/metal2vulkan-runtime/src/predication.rs:296` | `none`: an Apple-private predication If left open, live, where its unit ends |
| `PredicationWordPastBuffer` | A predication condition word (`encode_start_if`'s offset, rounded down to a multiple of 4) past its buffer's end | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:139` | `none`: an Apple-private predication condition word past its buffer |
| `PredicatedLoopDepth` | A predicated loop started (`ComputeCommandEncoder::encode_start_while`, `encode_start_do_while`) with three loops already open in its unit | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:483` | `none`: an Apple-private predicated loop four deep |
| `PredicatedLoopAcrossEncoders` | A command buffer one of whose live predicated loops started in one compute encoder and ended in a later one of its unit, refused at... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/predication.rs:284`, `crates/metal2vulkan-runtime/src/predication.rs:300` | `none`: a live Apple-private predicated loop spanning compute encoders |
| `MultisampledBufferCopy` | A blit copy between a buffer and a multisampled texture (`copyFromBuffer:...toTexture:` into, or `copyFromTexture:...toBuffer:` out of, a texture... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/blit_texture.rs:485`, `crates/metal2vulkan-runtime/src/blit_texture.rs:641` | `rare`: a buffer<->multisampled-texture copy on a device without sample-rate shading, an integer multisample attachment at the count, or the copy format's storage; and, where maintenance8's depth/colour copies are missing or wrong, what the sample-rate draws cannot move: a 16-bit depth, or a depth or stencil texture they cannot sample or render to (emulated elsewhere; the consumer's Maps pans and screensaver make the copy) |
| `ColorAttachmentGroups` | What a render pass the device draws in color groups does not build | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/render/color_groups.rs:106` | `app`: in a render pass of more color attachments than the device draws at once (five or more on a device of four), or one at an index past them: a pipeline state of other colors, a tile state, an execution of render commands, a draw reading another group's attachment |
@@ -244,14 +249,14 @@ Generated at `0021bc8b1`.
| Variant | What it blocks | Where | Sites | Reach |
|---|---|---|---|---|
| `DescriptorRangeExceeded` | A descriptor-form slot's window exceeds the descriptor range limit (Profile F) | at the device's limit | 1: `crates/metal2vulkan/src/bind/instantiate.rs:652` | `app`: a buffer window past a device's descriptor range |
| `TexelBufferTooLarge` | A texel buffer exceeds `maxTexelBufferElements` | at the device's limit | 1: `crates/metal2vulkan/src/bind/instantiate.rs:891` | `rare`: a texture buffer past maxTexelBufferElements |
| `DescriptorRangeExceeded` | A descriptor-form slot's window exceeds the descriptor range limit (Profile F) | at the device's limit | 1: `crates/metal2vulkan/src/bind/instantiate.rs:653` | `app`: a buffer window past a device's descriptor range |
| `TexelBufferTooLarge` | A texel buffer exceeds `maxTexelBufferElements` | at the device's limit | 1: `crates/metal2vulkan/src/bind/instantiate.rs:892` | `rare`: a texture buffer past maxTexelBufferElements |
| `HeapTooLarge` | The set-1 heap's elements (one per resident texture a handle can name, plus the null element) exceed the pipeline's heap capacity | at the device's limit | 7: `crates/metal2vulkan/src/bind/heap.rs:1014`, `crates/metal2vulkan/src/bind/heap.rs:1748` (+5) | `rare`: more resident textures than the pipeline's heap holds (bindless at scale) |
| `TessellationFactorRange` | The tessellation factors a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`),... | at the device's limit | 1: `crates/metal2vulkan/src/bind/graphics.rs:3551` | `rare`: tessellation factors past one storage descriptor |
| `PatchIndexRange` | The patch indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | 1: `crates/metal2vulkan/src/bind/graphics.rs:3595` | `rare`: patch indices past one storage descriptor |
| `ControlPointIndexRange` | The control-point indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | 1: `crates/metal2vulkan/src/bind/graphics.rs:3633` | `rare`: control-point indices past one storage descriptor |
| `MissingStageInRegion` | The kernel reads the compute encoder's stage-in region (a `[[stage_in]]` attribute stepping by thread position, or `[[grid_origin]]` or... | at the device's limit | 1: `crates/metal2vulkan/src/bind/dispatch.rs:802` | `none`: a stage-in region never set, which Metal leaves undefined |
| `UniformViewAliased` | A `device` buffer slot the pipeline reads through a uniform view (Profile F's per-stage storage-buffer fallback,... | at the device's limit | 1: `crates/metal2vulkan/src/bind/instantiate.rs:606` | `rare`: Profile F's uniform-view fallback aliased by a write |
| `UniformViewAliased` | A `device` buffer slot the pipeline reads through a uniform view (Profile F's per-stage storage-buffer fallback,... | at the device's limit | 1: `crates/metal2vulkan/src/bind/instantiate.rs:607` | `rare`: Profile F's uniform-view fallback aliased by a write |
| `MissingDeviceAddress` | A device-address slot received a buffer without a device address | at the device's limit | 1: `crates/metal2vulkan/src/bind/plan/slots.rs:133` | `rare`: a slot reached through a pointer loaded from memory, bound with inline bytes or on a device without device addresses |
## 5. Translation caps (`Error::LimitExceeded(Limit)`)
@@ -314,8 +319,8 @@ Each refusal's sites, with the function that builds it.
- `feature::QuadOperations`: `crates/metal2vulkan/src/device/subgroup.rs:371 (subgroup_tier)`; `crates/metal2vulkan/src/device/subgroup.rs:405 (subgroup_tier)`
- `feature::SimdgroupMatrix`: `crates/metal2vulkan/src/lower/simd/matrix.rs:83 (not_implemented)`
- `feature::ArgumentBufferPointers`: `crates/metal2vulkan/src/device/metal.rs:236 (unsupported_features)`
- `feature::ArgumentBufferTextures`: `crates/metal2vulkan-runtime/src/families/features.rs:1621 (tier2)`; `crates/metal2vulkan-runtime/src/pipeline/objects.rs:1036 (create_set_layout)`; `crates/metal2vulkan-runtime/src/resource_ids.rs:1097 (check_capacity)`; `crates/metal2vulkan/src/bind/heap.rs:1325 (array)`; `crates/metal2vulkan/src/bind/heap.rs:415 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:423 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:467 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:472 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:485 (member_view)`; `crates/metal2vulkan/src/lower/access/handle.rs:708 (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2362 (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs:308 (select_sampling)`; `crates/metal2vulkan/src/lower/sampler/select.rs:469 (select_heap_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs:140 (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs:465 (declare_heap)`; `crates/metal2vulkan/src/lower/texture/slot.rs:534 (declare_heap)`; `crates/metal2vulkan/src/pipeline/link.rs:977 (heap_set)`
- `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/encode.rs:445 (select_command)`; `crates/metal2vulkan/src/lower/access/encode.rs:495 (select_command)`; `crates/metal2vulkan/src/lower/access/encode.rs:623 (select_command)`; `crates/metal2vulkan/src/memory/provenance.rs:2185 (classify)`; `crates/metal2vulkan/src/memory/provenance.rs:2547 (access)`
- `feature::ArgumentBufferTextures`: `crates/metal2vulkan-runtime/src/families/features.rs:1621 (tier2)`; `crates/metal2vulkan-runtime/src/pipeline/objects.rs:1036 (create_set_layout)`; `crates/metal2vulkan-runtime/src/resource_ids.rs:1243 (check_capacity)`; `crates/metal2vulkan/src/bind/heap.rs:1325 (array)`; `crates/metal2vulkan/src/bind/heap.rs:415 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:423 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:467 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:472 (member_view)`; `crates/metal2vulkan/src/bind/heap.rs:485 (member_view)`; `crates/metal2vulkan/src/lower/access/handle.rs:708 (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2362 (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs:308 (select_sampling)`; `crates/metal2vulkan/src/lower/sampler/select.rs:469 (select_heap_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs:140 (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs:465 (declare_heap)`; `crates/metal2vulkan/src/lower/texture/slot.rs:534 (declare_heap)`; `crates/metal2vulkan/src/pipeline/link.rs:977 (heap_set)`
- `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/encode.rs:446 (select_command)`; `crates/metal2vulkan/src/lower/access/encode.rs:496 (select_command)`; `crates/metal2vulkan/src/lower/access/encode.rs:624 (select_command)`; `crates/metal2vulkan/src/memory/provenance.rs:2185 (classify)`; `crates/metal2vulkan/src/memory/provenance.rs:2547 (access)`
- `feature::DereferenceLoadedPointer`: `crates/metal2vulkan/src/lower/access/dynamic.rs:407 (plan_misses)`; `crates/metal2vulkan/src/lower/access/local.rs:774 (access_ptr)`; `crates/metal2vulkan/src/lower/access/local.rs:796 (threadgroup_constant_refusal)`; `crates/metal2vulkan/src/memory/plan.rs:593 (analyze)`
- `feature::PointerToInteger`: `crates/metal2vulkan/src/lower/access/dynamic.rs:347 (require_addresses)`
- `feature::PointerCompare`: `crates/metal2vulkan/src/lower/access/copy.rs:717 (addressed)`
@@ -326,7 +331,7 @@ Each refusal's sites, with the function that builds it.
- `feature::Int64Atomics`: `crates/metal2vulkan/src/lower/access/atomic.rs:624 (select)`; `crates/metal2vulkan/src/lower/access/atomic.rs:633 (select)`
- `feature::ImageAtomics`: `crates/metal2vulkan-runtime/src/families/formats.rs:464 (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs:468 (atomic_gap)`; `crates/metal2vulkan/src/lower/texture/slot.rs:900 (atomic_format)`
- `feature::DescriptorCount`: `crates/metal2vulkan/src/lower/access/mod.rs:1684 (accept_placement)`; `crates/metal2vulkan/src/lower/select.rs:1641 (finish)`; `crates/metal2vulkan/src/pipeline/link.rs:1135 (limit_error)`
- `feature::BufferRange`: `crates/metal2vulkan-runtime/src/function_table.rs:569 (past_storage_buffer_range)`; `crates/metal2vulkan/src/bind/graphics.rs:3556 (patch_binding)`; `crates/metal2vulkan/src/bind/graphics.rs:3600 (patch_binding)`; `crates/metal2vulkan/src/bind/graphics.rs:3638 (patch_binding)`; `crates/metal2vulkan/src/bind/instantiate.rs:658 (bind_buffers)`; `crates/metal2vulkan/src/lower/access/function_table.rs:226 (select)`; `crates/metal2vulkan/src/lower/access/mod.rs:1184 (place_slots)`
- `feature::BufferRange`: `crates/metal2vulkan-runtime/src/function_table.rs:569 (past_storage_buffer_range)`; `crates/metal2vulkan/src/bind/graphics.rs:3556 (patch_binding)`; `crates/metal2vulkan/src/bind/graphics.rs:3600 (patch_binding)`; `crates/metal2vulkan/src/bind/graphics.rs:3638 (patch_binding)`; `crates/metal2vulkan/src/bind/instantiate.rs:659 (bind_buffers)`; `crates/metal2vulkan/src/lower/access/function_table.rs:226 (select)`; `crates/metal2vulkan/src/lower/access/mod.rs:1184 (place_slots)`
- `feature::Int64Arithmetic`: `crates/metal2vulkan/src/lower/arith/legal.rs:582 (check_scalar)`; `crates/metal2vulkan/src/lower/select.rs:1133 (selector_form)`
- `feature::Float64Arithmetic`: `crates/metal2vulkan/src/device/metal.rs:230 (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/legal.rs:587 (check_scalar)`
- `feature::Format`: `crates/metal2vulkan-runtime/src/binding_view.rs:146 (binding_view)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:462 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:469 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:484 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:541 (pair_unit)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:633 (plan_levels_copy)`; `crates/metal2vulkan-runtime/src/blit_texture.rs:2087 (through_buffer)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:519 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:582 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:614 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:851 (texture_buffer_texel)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:269 (colour_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:297 (copy_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:343 (copy_unit)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:346 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:526 (usable_twin)`; `crates/metal2vulkan-runtime/src/families/features.rs:1598 (read_write_tier)`; `crates/metal2vulkan-runtime/src/families/formats.rs:1628 (sparse_missing)`; `crates/metal2vulkan-runtime/src/families/formats.rs:227 (none)`; `crates/metal2vulkan-runtime/src/families/formats.rs:271 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:291 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:306 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:353 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:392 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:474 (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs:508 (lacking)`; `crates/metal2vulkan-runtime/src/families/formats.rs:522 (unsupported)`; `crates/metal2vulkan-runtime/src/image_plan.rs:544 (check_own_memory)`; `crates/metal2vulkan-runtime/src/image_plan.rs:670 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:787 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:907 (plan_held)`; `crates/metal2vulkan-runtime/src/render.rs:2155 (viewing)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1024 (check_target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1362 (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1698 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1791 (attachment_format)`; `crates/metal2vulkan-runtime/src/resolve.rs:392 (unmodelled_resolve)`; `crates/metal2vulkan-runtime/src/resolve.rs:482 (color)`; `crates/metal2vulkan-runtime/src/sample_copy.rs:177 (checked_twin)`; `crates/metal2vulkan-runtime/src/sample_copy.rs:205 (plan)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs:296 (interleave_merge)`; `crates/metal2vulkan-runtime/src/shadow.rs:644 (unmerged)`; `crates/metal2vulkan-runtime/src/shadow.rs:651 (unmerged)`; `crates/metal2vulkan-runtime/src/texture.rs:2000 (texture_as)`; `crates/metal2vulkan-runtime/src/texture.rs:3540 (two_planes_refused)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs:498 (astc_texels)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs:534 (etc_texels)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1810 (planned_heap_texture)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:80 (refused)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:115 (converted_storage)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:278 (ycbcr_write_shadow)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:384 (new_render_shadow)`; `crates/metal2vulkan-runtime/src/two_planes.rs:114 (unmeasured)`; `crates/metal2vulkan-runtime/src/view_plan.rs:380 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:393 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:400 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:410 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:420 (check_format)`; `crates/metal2vulkan-runtime/src/ycbcr.rs:285 (refused)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:184 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1134 (plain_texture)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1814 (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs:193 (require_filter_features)`; `crates/metal2vulkan/src/bind/plan/resources.rs:959 (plain_texture)`; `crates/metal2vulkan/src/bind/sample_interleave.rs:304 (finish)`; `crates/metal2vulkan/src/bind/sample_interleave.rs:328 (interleave_split_module)`; `crates/metal2vulkan/src/bind/shadow_copy_in.rs:259 (shadow_copy_in_module)`; `crates/metal2vulkan/src/bind/unused_bits.rs:657 (unused_bits_module)`; `crates/metal2vulkan/src/lower/access/tile.rs:1029 (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs:160 (select_param)`; `crates/metal2vulkan/src/lower/fraLine truncated
@@ -343,7 +348,7 @@ Each refusal's sites, with the function that builds it.
- `feature::SamplerLodBias`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:258 (constexpr_desc)`; `crates/metal2vulkan/src/lower/sampler/constexpr.rs:265 (constexpr_desc)`; `crates/metal2vulkan/src/lower/sampler/constexpr.rs:271 (constexpr_desc)`
- `feature::SamplerCompare`: `crates/metal2vulkan/src/metal/sampler.rs:260 (check_sampler)`
- `feature::PixelSamplerCompare`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:115 (lowered)`
- `feature::TexelBuffer`: `crates/metal2vulkan/src/bind/instantiate.rs:879 (texel_ranges)`; `crates/metal2vulkan/src/bind/instantiate.rs:885 (texel_ranges)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1147 (plain_texture)`
- `feature::TexelBuffer`: `crates/metal2vulkan/src/bind/instantiate.rs:880 (texel_ranges)`; `crates/metal2vulkan/src/bind/instantiate.rs:886 (texel_ranges)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1147 (plain_texture)`
- `feature::RasterOrderGroups`: `crates/metal2vulkan/src/device/metal.rs:242 (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/rog.rs:151 (mode)`; `crates/metal2vulkan/src/lower/fragment/rog.rs:172 (mode)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs:158 (finish)`
- `feature::FramebufferFetch`: `crates/metal2vulkan-runtime/src/families/features.rs:1007 (state)`; `crates/metal2vulkan-runtime/src/render.rs:5709 (next_instance)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:116 (lacks)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:143 (new)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:514 (planes_merge)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:190 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/graphics.rs:1453 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1490 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1509 (plan)`; `crates/metal2vulkan/src/bind/sample_planes.rs:477 (finish)`; `crates/metal2vulkan/src/device/metal.rs:252 (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:1198 (unorm8)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:1216 (unorm8)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:1230 (unorm8)`; `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:1273 (packed16)`; `crates/metal2vulkan/src/lower/fragment/color.rs:215 (select_param)`; `crates/metal2vulkan/src/lower/fragment/color.rs:279 (unordered)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:195 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:272 (depth_test_form)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:318 (stencil_test_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1024 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1114 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1151 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1716 (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:749 (not_implemented)`; `crates/metal2vulkan/src/pipeline/link/fetch.rs:164 (storage_attachments)`
- `feature::PrimitiveId`: `crates/metal2vulkan-runtime/src/families/features.rs:1115 (state)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:3112 (finish)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:240 (check_primitive_id)`
@@ -357,7 +362,7 @@ Each refusal's sites, with the function that builds it.
- `feature::PixelCoverageAtSampleRate`: `crates/metal2vulkan/src/lower/fragment/coverage.rs:291 (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs:754 (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:867 (sample_invocations)`
- `feature::InterfaceComponents`: `crates/metal2vulkan/src/pipeline/compile/color_group.rs:202 (refusal)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:301 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:409 (assign)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:90 (limit_error)`
- `feature::UnmatchedVarying`: `crates/metal2vulkan/src/pipeline/link/varyings.rs:318 (mesh_fragment)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:537 (varyings)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:548 (varyings)`
- `feature::KernelStageIn`: `crates/metal2vulkan-runtime/src/indirect_execute.rs:350 (record)`; `crates/metal2vulkan/src/bind/dispatch.rs:877 (instantiate)`; `crates/metal2vulkan/src/lower/stage_io/stage_in.rs:133 (select)`
- `feature::KernelStageIn`: `crates/metal2vulkan-runtime/src/indirect_execute.rs:376 (record)`; `crates/metal2vulkan/src/bind/dispatch.rs:877 (instantiate)`; `crates/metal2vulkan/src/lower/stage_io/stage_in.rs:133 (select)`
- `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs:1256 (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs:1347 (post_check)`; `crates/metal2vulkan/src/bind/graphics.rs:3754 (tessellation_dispatch)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:519 (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1457 (primitive_id_output)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1750 (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:799 (param)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:150 (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:489 (plan_entry)`; `crates/metal2vulkan/src/metal/vertex.rs:219 (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:212 (control_plan)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:292 (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:316 (push_offset)`
- `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs:1536 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:2966 (mesh_limit)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:499 (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:538 (plan_entry)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:572 (plan_entry)`; `crates/metal2vulkan/src/memory/plan.rs:2056 (reprs)`; `crates/metal2vulkan/src/pipeline/link/mesh.rs:95 (records)`
- `feature::TileShading`: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs:521 (scratch)`; `crates/metal2vulkan/src/bind/plan/compute.rs:237 (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs:151 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:275 (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs:687 (tile_pipeline)`
@@ -365,7 +370,7 @@ Each refusal's sites, with the function that builds it.
- `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs:202 (instance_record)`; `crates/metal2vulkan/src/bind/acceleration.rs:216 (instance_record)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1087 (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1202 (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1245 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1257 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1282 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1297 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1312 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:344 (slot_of)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:385 (select_param)`; `crates/metal2vulkan/src/lower/select.rs:899 (route_air)`
- `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs:32 (refuse)`; `crates/metal2vulkan/src/lower/select.rs:903 (route_air)`
- `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/fragment/mod.rs:925 (select)`
- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs:556 (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs:796 (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs:280 (draw_replay_preprocess)`; `crates/metal2vulkan/src/bind/replay/draws.rs:482 (draw_replay_module)`; `crates/metal2vulkan/src/bind/replay/flat.rs:247 (flat_dispatch_module)`; `crates/metal2vulkan/src/bind/replay/merged.rs:242 (draw_merge_module)`; `crates/metal2vulkan/src/lower/access/encode.rs:393 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:409 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:526 (select_command)`; `crates/metal2vulkan/src/lower/access/mod.rs:1539 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1562 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1565 (plan_replay)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2613 (merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2669 (finish_merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:455 (param)`; `crates/metal2vulkan/src/pipeline/compile.rs:2110 (plan_one)`; `crates/metal2vulkan/src/pipeline/compile.rs:2115 (plan_one)`
- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs:556 (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs:796 (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/draws.rs:280 (draw_replay_preprocess)`; `crates/metal2vulkan/src/bind/replay/draws.rs:482 (draw_replay_module)`; `crates/metal2vulkan/src/bind/replay/flat.rs:247 (flat_dispatch_module)`; `crates/metal2vulkan/src/bind/replay/merged.rs:242 (draw_merge_module)`; `crates/metal2vulkan/src/lower/access/encode.rs:394 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:410 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:527 (select_command)`; `crates/metal2vulkan/src/lower/access/mod.rs:1539 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1562 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1565 (plan_replay)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2613 (merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2669 (finish_merged)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:455 (param)`; `crates/metal2vulkan/src/pipeline/compile.rs:2110 (plan_one)`; `crates/metal2vulkan/src/pipeline/compile.rs:2115 (plan_one)`
- `feature::VulkanVersion`: `crates/metal2vulkan/src/ash_interop/query.rs:915 (query)`; `crates/metal2vulkan/src/device/derive.rs:105 (with_deviations)`
- `feature::Constant`: `crates/metal2vulkan-air/src/bitcode/constants.rs:210 (record)`; `crates/metal2vulkan-air/src/bitcode/constants.rs:268 (record)`; `crates/metal2vulkan/src/error/mod.rs:255 (from)`
- `feature::Attribute`: `crates/metal2vulkan-air/src/bitcode/attrs.rs:493 (known)`; `crates/metal2vulkan/src/error/mod.rs:256 (from)`
@@ -395,7 +400,7 @@ Each refusal's sites, with the function that builds it.
- `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs:167 (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs:980 (may_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1102 (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2587 (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3391 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3738 (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs:307 (select)`
- `feature::MipmapGeneration`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1787 (mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37 (pick_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:262 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:270 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:275 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:304 (plan_mipmaps)`; `crates/metal2vulkan/src/bind/mipmap_filter.rs:973 (mipmap_filter_module)`
- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs:393 (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:433 (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:652 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:657 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:675 (new)`
- `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2546 (gpu_times)`
- `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2555 (gpu_times)`
- `feature::CountingVisibility`: `crates/metal2vulkan-runtime/src/visibility.rs:452 (check_mode)`
- `feature::ViewFormatReinterpretation`: `crates/metal2vulkan-runtime/src/view_plan.rs:568 (reinterpretation_refused)`
- `feature::SeparateMultisampledDepthStencil`: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:188 (sampled_candidate)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:294 (by_draws)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:336 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:376 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:777 (plan)`; `crates/metal2vulkan-runtime/src/nan_clear.rs:651 (nan_write)`; `crates/metal2vulkan-runtime/src/texture/signed_depth.rs:191 (sample_strip)`
@@ -410,14 +415,15 @@ Each refusal's sites, with the function that builds it.
- `feature::ViewportDepthRange`: `crates/metal2vulkan-runtime/src/render_state.rs:1186 (depth_ranges_refused)`
- `feature::UndeclaredTextureUsage`: `crates/metal2vulkan-runtime/src/binding_view.rs:141 (binding_view)`; `crates/metal2vulkan-runtime/src/texture/usage_shadow.rs:72 (refused)`
- `feature::RenderTargetSize`: `crates/metal2vulkan-runtime/src/render_pass.rs:1264 (framebuffer_fits)`
- `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/encode.rs:567 (select_command)`
- `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/encode.rs:568 (select_command)`
- `feature::GlobalBuiltinInFragment`: `crates/metal2vulkan/src/lower/select.rs:912 (route_air)`
- `feature::PrivateRenderState`: `crates/metal2vulkan/src/bind/heap.rs:1300 (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs:887 (write_rounding)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2902 (mode_rounded_write)`; `crates/metal2vulkan/src/pipeline/private_state.rs:46 (refused)`
- `feature::ExtendedRangeBlend`: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:305 (refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1553 (plan)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1556 (plan)`; `crates/metal2vulkan/src/lower/fragment/input_blend.rs:153 (plan)`
- `feature::TileReach`: `crates/metal2vulkan/src/bind/tile_reach.rs:270 (tile_reach_module)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2450 (capture)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2476 (capture)`
- `feature::CommandPredication`: `crates/metal2vulkan/src/bind/replay/predication.rs:414 (predication_step_module)`
- `feature::ProgramScopeBinding`: `crates/metal2vulkan-air/src/abi/module.rs:77 (decode)`; `crates/metal2vulkan/src/error/mod.rs:267 (from)`
- `feature::SeqCstFence`: `crates/metal2vulkan/src/lower/sync/barrier.rs:443 (require_seq_cst)`
- `gap::Textures`: `crates/metal2vulkan-runtime/src/blit_texture.rs:163 (check_depth_view)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:1554 (view_usage)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1499 (compile_error)`; `crates/metal2vulkan-runtime/src/texture.rs:1445 (image_error)`; `crates/metal2vulkan-runtime/src/texture.rs:2174 (storage_over_buffer)`; `crates/metal2vulkan-runtime/src/texture.rs:2986 (new_image_starting)`; `crates/metal2vulkan-runtime/src/texture.rs:4030 (image)`; `crates/metal2vulkan-runtime/src/texture.rs:5503 (host_copy)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:207 (new_surface_planes_texture)`
- `gap::Textures`: `crates/metal2vulkan-runtime/src/blit_texture.rs:163 (check_depth_view)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:1554 (view_usage)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1522 (compile_error)`; `crates/metal2vulkan-runtime/src/texture.rs:1445 (image_error)`; `crates/metal2vulkan-runtime/src/texture.rs:2174 (storage_over_buffer)`; `crates/metal2vulkan-runtime/src/texture.rs:2986 (new_image_starting)`; `crates/metal2vulkan-runtime/src/texture.rs:4030 (image)`; `crates/metal2vulkan-runtime/src/texture.rs:5503 (host_copy)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:207 (new_surface_planes_texture)`
- `gap::ResourceHeap`: `crates/metal2vulkan-runtime/src/binding.rs:2016 (descriptor)`
- `gap::SparseHeaps`: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:458 (first_slice)`; `crates/metal2vulkan-runtime/src/texture.rs:1629 (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture.rs:4722 (make_aliasable)`
- `gap::SparseTileMaps`: `crates/metal2vulkan-runtime/src/binding.rs:553 (slot_tile_map)`; `crates/metal2vulkan-runtime/src/sparse/texture.rs:30 (sparse_refusal)`; `crates/metal2vulkan-runtime/src/texture.rs:1662 (plan_sparse_texture)`
@@ -425,15 +431,15 @@ Each refusal's sites, with the function that builds it.
- `gap::HeapTextureAlignment`: `crates/metal2vulkan-runtime/src/texture/heap.rs:980 (check_heap_base)`
- `gap::HeapTextureMemory`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1418 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1425 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1919 (host_heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2132 (memory_shadow)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:489 (memory_refusal)`
- `gap::FunctionTablePastMaxBufferLength`: `crates/metal2vulkan-runtime/src/function_table.rs:622 (past_limit)`
- `gap::IndirectCommandBufferPastMaxBufferLength`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:516 (new_indirect_command_buffer)`
- `gap::IndirectRenderCommands`: `crates/metal2vulkan-runtime/src/compute.rs:1103 (execute_range)`; `crates/metal2vulkan-runtime/src/compute.rs:1183 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/depth_stencil.rs:85 (gpu_resource_id)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:3638 (render_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:511 (new_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1506 (compile_error)`; `crates/metal2vulkan-runtime/src/render.rs:6979 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:7342 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:7747 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:8196 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/executions.rs:1086 (back_memoryless)`; `crates/metal2vulkan-runtime/src/render/executions.rs:1989 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2032 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2827 (record_forms)`; `crates/metal2vulkan-runtime/src/render/executions.rs:375 (execute_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:434 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:449 (execute_indirect_range)`
- `gap::IndirectImageblockSize`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:2757 (set_imageblock_size)`
- `gap::IndirectCommandBufferPastMaxBufferLength`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:522 (new_indirect_command_buffer)`
- `gap::IndirectRenderCommands`: `crates/metal2vulkan-runtime/src/compute.rs:1091 (execute_range)`; `crates/metal2vulkan-runtime/src/compute.rs:1171 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/depth_stencil.rs:85 (gpu_resource_id)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:4344 (render_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:517 (new_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1529 (compile_error)`; `crates/metal2vulkan-runtime/src/render.rs:6979 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:7342 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:7747 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:8196 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/executions.rs:1100 (back_memoryless)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2003 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2046 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2894 (record_forms)`; `crates/metal2vulkan-runtime/src/render/executions.rs:380 (execute_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:439 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:454 (execute_indirect_range)`
- `gap::IndirectImageblockSize`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:3351 (set_imageblock_size)`
- `gap::CommandReplay`: `crates/metal2vulkan-runtime/src/binding.rs:694 (bind)`; `crates/metal2vulkan-runtime/src/binding.rs:697 (bind)`
- `gap::RenderAttachments`: `crates/metal2vulkan-runtime/src/binding.rs:1839 (unexpected)`
- `gap::AccelerationStructures`: `crates/metal2vulkan-runtime/src/binding.rs:1842 (unexpected)`
- `gap::FeatureEnable`: `crates/metal2vulkan-runtime/src/enables.rs:1155 (of)`
- `gap::ExtensionEnable`: `crates/metal2vulkan-runtime/src/enables.rs:1146 (of)`
- `gap::Render`: `crates/metal2vulkan-runtime/src/attachment_stand_in.rs:404 (stand_in_as)`; `crates/metal2vulkan-runtime/src/attachment_stand_in.rs:460 (stand_in_as)`; `crates/metal2vulkan-runtime/src/attachment_stand_in.rs:684 (check_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:796 (attachment_twin)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:283 (check_sizes)`; `crates/metal2vulkan-runtime/src/kept_bytes.rs:138 (settle)`; `crates/metal2vulkan-runtime/src/linear_attachment.rs:293 (settle)`; `crates/metal2vulkan-runtime/src/nan_clear.rs:197 (plan)`; `crates/metal2vulkan-runtime/src/pipeline/render.rs:1131 (imageblock_sample_length)`; `crates/metal2vulkan-runtime/src/render.rs:2086 (check_pipeline)`; `crates/metal2vulkan-runtime/src/render.rs:5755 (next_instance)`; `crates/metal2vulkan-runtime/src/render.rs:7436 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs:517 (scratch)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1306 (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1665 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1719 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1780 (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs:2013 (depth_stencil)`; `crates/metal2vulkan-runtime/src/resolve.rs:1010 (destination)`; `crates/metal2vulkan-runtime/src/resolve.rs:1027 (destination)`; `crates/metal2vulkan-runtime/src/resolve.rs:1091 (destination)`; `crates/metal2vulkan-runtime/src/resolve.rs:901 (attach)`; `crates/metal2vulkan-runtime/src/resolve.rs:969 (color_copy)`
- `gap::Render`: `crates/metal2vulkan-runtime/src/attachment_stand_in.rs:404 (stand_in_as)`; `crates/metal2vulkan-runtime/src/attachment_stand_in.rs:460 (stand_in_as)`; `crates/metal2vulkan-runtime/src/attachment_stand_in.rs:684 (check_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:796 (attachment_twin)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:283 (check_sizes)`; `crates/metal2vulkan-runtime/src/kept_bytes.rs:138 (settle)`; `crates/metal2vulkan-runtime/src/linear_attachment.rs:293 (settle)`; `crates/metal2vulkan-runtime/src/nan_clear.rs:197 (plan)`; `crates/metal2vulkan-runtime/src/pipeline/render.rs:1150 (imageblock_sample_length)`; `crates/metal2vulkan-runtime/src/render.rs:2086 (check_pipeline)`; `crates/metal2vulkan-runtime/src/render.rs:5755 (next_instance)`; `crates/metal2vulkan-runtime/src/render.rs:7436 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs:517 (scratch)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1306 (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1665 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1719 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1780 (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs:2013 (depth_stencil)`; `crates/metal2vulkan-runtime/src/resolve.rs:1010 (destination)`; `crates/metal2vulkan-runtime/src/resolve.rs:1027 (destination)`; `crates/metal2vulkan-runtime/src/resolve.rs:1091 (destination)`; `crates/metal2vulkan-runtime/src/resolve.rs:901 (attach)`; `crates/metal2vulkan-runtime/src/resolve.rs:969 (color_copy)`
- `gap::TexelsPastBufferLength`: `crates/metal2vulkan-runtime/src/buffer_texture.rs:261 (refusal_error)`; `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:105 (surface_depth_twin)`
- `gap::OverlappingSurfaceRows`: `crates/metal2vulkan-runtime/src/buffer_texture.rs:263 (refusal_error)`
- `gap::SamplePositionsAtBegin`: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:145 (stencil_scratch)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1850 (positioned_stand_in)`; `crates/metal2vulkan-runtime/src/sample_positions.rs:185 (grid)`
@@ -478,7 +484,11 @@ Each refusal's sites, with the function that builds it.
- `gap::DetachedTexelAccess`: `crates/metal2vulkan-runtime/src/texture.rs:4820 (refuse_detached_texels)`
- `gap::SurfaceDepthStencil`: `crates/metal2vulkan-runtime/src/blit_texture.rs:236 (unit)`; `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:57 (surface_depth_twin)`
- `gap::HostHeapUncompressedMultisample`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1924 (host_heap_plan)`
- `gap::PredicationDropsUngatedWork`: `crates/metal2vulkan-runtime/src/predication.rs:730 (unbalanced)`
- `gap::PredicationUnbalanced`: `crates/metal2vulkan-runtime/src/predication.rs:371 (nil)`; `crates/metal2vulkan-runtime/src/predication.rs:403 (start_else)`; `crates/metal2vulkan-runtime/src/predication.rs:455 (end_if)`; `crates/metal2vulkan-runtime/src/predication.rs:575 (end_loop)`
- `gap::PredicationOpenAtUnitEnd`: `crates/metal2vulkan-runtime/src/predication.rs:280 (commit_refusal)`; `crates/metal2vulkan-runtime/src/predication.rs:296 (commit)`
- `gap::PredicationWordPastBuffer`: `crates/metal2vulkan-runtime/src/predication.rs:139 (new)`
- `gap::PredicatedLoopDepth`: `crates/metal2vulkan-runtime/src/predication.rs:483 (start_loop)`
- `gap::PredicatedLoopAcrossEncoders`: `crates/metal2vulkan-runtime/src/predication.rs:284 (commit_refusal)`; `crates/metal2vulkan-runtime/src/predication.rs:300 (commit)`
- `gap::MultisampledBufferCopy`: `crates/metal2vulkan-runtime/src/blit_texture.rs:485 (copy_from_buffer_to_texture)`; `crates/metal2vulkan-runtime/src/blit_texture.rs:641 (copy_from_texture_to_buffer)`
- `gap::ColorAttachmentGroups`: `crates/metal2vulkan-runtime/src/render/color_groups.rs:106 (gap)`
- `apple::ProtectedContent`: `crates/metal2vulkan-runtime/src/apple_only.rs:200 (check)`
@@ -490,14 +500,14 @@ Each refusal's sites, with the function that builds it.
- `apple::StencilCleared`: `crates/metal2vulkan-runtime/src/apple_only.rs:213 (check)`
- `apple::SurfaceClientDirection`: `crates/metal2vulkan-runtime/src/buffer_texture.rs:417 (new_texture_with_iosurface_plane)`
- `apple::FillUnmeasured`: `crates/metal2vulkan-runtime/src/blit_fill.rs:149 (unmeasured)`
- `bind::DescriptorRangeExceeded`: `crates/metal2vulkan/src/bind/instantiate.rs:652 (bind_buffers)`
- `bind::TexelBufferTooLarge`: `crates/metal2vulkan/src/bind/instantiate.rs:891 (texel_ranges)`
- `bind::DescriptorRangeExceeded`: `crates/metal2vulkan/src/bind/instantiate.rs:653 (bind_buffers)`
- `bind::TexelBufferTooLarge`: `crates/metal2vulkan/src/bind/instantiate.rs:892 (texel_ranges)`
- `bind::HeapTooLarge`: `crates/metal2vulkan/src/bind/heap.rs:1014 (new)`; `crates/metal2vulkan/src/bind/heap.rs:1748 (directory_bytes)`; `crates/metal2vulkan/src/bind/heap.rs:1863 (listed_sampler_tables)`; `crates/metal2vulkan/src/bind/heap.rs:1913 (placed)`; `crates/metal2vulkan/src/bind/heap.rs:2069 (heap_elements)`; `crates/metal2vulkan/src/bind/heap.rs:949 (new)`; `crates/metal2vulkan/src/bind/heap.rs:965 (new)`
- `bind::TessellationFactorRange`: `crates/metal2vulkan/src/bind/graphics.rs:3551 (patch_binding)`
- `bind::PatchIndexRange`: `crates/metal2vulkan/src/bind/graphics.rs:3595 (patch_binding)`
- `bind::ControlPointIndexRange`: `crates/metal2vulkan/src/bind/graphics.rs:3633 (patch_binding)`
- `bind::MissingStageInRegion`: `crates/metal2vulkan/src/bind/dispatch.rs:802 (instantiate)`
- `bind::UniformViewAliased`: `crates/metal2vulkan/src/bind/instantiate.rs:606 (check_uniform_aliasing)`
- `bind::UniformViewAliased`: `crates/metal2vulkan/src/bind/instantiate.rs:607 (check_uniform_aliasing)`
- `bind::MissingDeviceAddress`: `crates/metal2vulkan/src/bind/plan/slots.rs:133 (plan_buffer)`
- `limit::InlinedInstructions`: `crates/metal2vulkan-air/src/canon/inline.rs:330 (u32_of)`; `crates/metal2vulkan-air/src/canon/inline.rs:334 (usize_of)`; `crates/metal2vulkan-air/src/canon/inline.rs:61 (inline)`
- `limit::OutputBlocks`: `crates/metal2vulkan/src/structurize/irreducible.rs:90 (round)`; `crates/metal2vulkan/src/structurize/mod.rs:187 (structure_prepared)`; `crates/metal2vulkan/src/structurize/structurizer_properties/mod.rs:423 (output_cap_is_checked_before_allocating)`; `crates/metal2vulkan/src/structurize/structurizer_properties/trees.rs:232 (the_output_cap_is_checked_before_emission)`
+8 -8
View File
@@ -166,8 +166,8 @@ narrow refusal that the call's rustdoc describes.
| `EncodeStartIf` | `encodeStartIf:offset:comparison:referenceValue:` (SPI) | `ComputeCommandEncoder::encode_start_if`, as Metal runs it, on a counter the runtime's step kernel moves; a live block open where its unit ends fails the command buffer where its commands skip there, as Metal's GPU recovery does (`PredicationOpenAtUnitEnd`); a word past its buffer reads as Metal reads it (the heap's bytes, or zero; zero announced where Metal reads unrelated memory); refused: a nil buffer with no block open where `encode_start_else` refuses *(partial)* |
| `EncodeStartWhile` | `encodeStartWhile:offset:comparison:referenceValue:` (SPI) | `ComputeCommandEncoder::encode_start_while`, as Metal runs it, laid down as `encode_start_do_while`'s loops are; refused as `encode_start_if` refuses *(partial)* |
| `EndEncoding` | `endEncoding` | `ComputeCommandEncoder::end_encoding` |
| `ExecuteCommandsIndirect` | `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:` | `ComputeCommandEncoder::execute_commands_in_buffer_indirect`; `_checked` adds an `IndirectCommandCheck` its host step calls on each command first |
| `ExecuteCommandsInBuffer` | `executeCommandsInBuffer:withRange:` | `ComputeCommandEncoder::execute_commands_in_buffer`; `_checked` adds an `IndirectCommandCheck` a host step calls on each command first, and the `IndirectCommandCheckNeeds` it looks for |
| `ExecuteCommandsIndirect` | `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:` | `ComputeCommandEncoder::execute_commands_in_buffer_indirect`; `_checked` adds an `IndirectCommandCheck` its host step calls on each command first, and the `IndirectCommandCheckNeeds` it looks for |
| `ExecuteCommandsInBuffer` | `executeCommandsInBuffer:withRange:` | `ComputeCommandEncoder::execute_commands_in_buffer`; `_checked` adds an `IndirectCommandCheck` that `commit` (for the CPU's records) or a host step calls on each command first, and the `IndirectCommandCheckNeeds` it looks for, which may rule it out (then it runs on the GPU alone where it can) |
| `CompressedTextureReinterpretationFlush` | `insertCompressedTextureReinterpretationFlush` (SPI) | `ComputeCommandEncoder::insert_compressed_texture_reinterpretation_flush`: a no-op |
| `MemoryBarrierWithResources` | `memoryBarrierWithResources:count:` | `ComputeCommandEncoder::memory_barrier_with_resources` |
| `MemoryBarrierWithScope` | `memoryBarrierWithScope:` | `ComputeCommandEncoder::memory_barrier_with_scope` |
@@ -312,8 +312,8 @@ narrow refusal that the call's rustdoc describes.
| Item | Metal | Runtime |
|---|---|---|
| `encode` | | one `IndirectRenderCommand` method per `IcbRenderCmd` (above) |
| `command_type`, `fragment_buffer_address`, `vertex_attribute_stride`, `vertex_buffer_address`, `has_barrier`, `draw_args`, `draw_indexed_args`, `draw_patches_args`, `draw_indexed_patches_args`, `tessellation_factor_args` | the getters (SPI) | `IndirectCommandBuffer::commands`: each render command decoded as an `EncodedRenderCommand` |
| `pipeline_state_unique_identifier` | `getPipelineStateUniqueIdentifier` (SPI) | `pipeline_unique_identifier` of the command read back (`IndirectCommandBuffer::commands`) *(partial)* |
| `command_type`, `fragment_buffer_address`, `vertex_attribute_stride`, `vertex_buffer_address`, `has_barrier`, `draw_args`, `draw_indexed_args`, `draw_patches_args`, `draw_indexed_patches_args`, `tessellation_factor_args` | the getters (SPI) | `IndirectRenderCommand::command_type`, `vertex_buffer`, `fragment_buffer`, `has_barrier`, `draw`: each reads its field of the record alone; or `IndirectCommandBuffer::commands`, each render command decoded as an `EncodedRenderCommand` |
| `pipeline_state_unique_identifier` | `getPipelineStateUniqueIdentifier` (SPI) | `IndirectRenderCommand::pipeline_unique_identifier` (with `pipeline_state` and `pipeline_id`), or that of the command read back (`IndirectCommandBuffer::commands`) *(partial)* |
### `IcbComputeCmd`: `MTLIndirectComputeCommand` commands
@@ -336,8 +336,8 @@ narrow refusal that the call's rustdoc describes.
| Item | Metal | Runtime |
|---|---|---|
| `encode` | | one `IndirectComputeCommand` method per `IcbComputeCmd` (above) |
| `command_type`, `kernel_attribute_stride`, `kernel_buffer_address`, `stage_in_region`, `threadgroup_memory_length`, `has_barrier`, `dispatch_threadgroups_args`, `dispatch_threads_args`, `image_block_args` | the getters (SPI) | `IndirectCommandBuffer::commands`: each compute command decoded as an `EncodedComputeCommand` |
| `pipeline_state_unique_identifier` | `getPipelineStateUniqueIdentifier` (SPI) | `pipeline_unique_identifier` of the command read back (`IndirectCommandBuffer::commands`) *(partial)* |
| `command_type`, `kernel_attribute_stride`, `kernel_buffer_address`, `stage_in_region`, `threadgroup_memory_length`, `has_barrier`, `dispatch_threadgroups_args`, `dispatch_threads_args`, `image_block_args` | the getters (SPI) | `IndirectComputeCommand::command_type`, `kernel_buffer`, `stage_in_region`, `threadgroup_memory_length`, `has_barrier`, `dispatch`, `imageblock_size`: each reads its field of the record alone; or `IndirectCommandBuffer::commands`, each compute command decoded as an `EncodedComputeCommand` |
| `pipeline_state_unique_identifier` | `getPipelineStateUniqueIdentifier` (SPI) | `IndirectComputeCommand::pipeline_unique_identifier` (with `pipeline_state` and `pipeline_id`), or that of the command read back (`IndirectCommandBuffer::commands`) *(partial)* |
### `RateMap`: `MTLRasterizationRateMap`
@@ -387,8 +387,8 @@ narrow refusal that the call's rustdoc describes.
| `DrawPrimitivesInstances` | `drawPrimitives:vertexStart:vertexCount:instanceCount:` | `RenderCommandEncoder::draw_primitives` *(partial)* |
| `DrawPrimitivesBase` | `drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:` | `RenderCommandEncoder::draw_primitives` *(partial)* |
| `EndEncoding` | `endEncoding` | `RenderCommandEncoder::end_encoding` |
| `ExecuteCommandsIndirect` | `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:` | `RenderCommandEncoder::execute_commands_in_buffer_indirect`: the pass is recorded at a host step (announced once); `_checked` adds an `IndirectCommandCheck` the step calls on each command first *(partial)* |
| `ExecuteCommandsInBuffer` | `executeCommandsInBuffer:withRange:` | `RenderCommandEncoder::execute_commands_in_buffer`: the records as they stand at commit, on the GPU alone where the commit can tell every command draws one primitive type under the inherited state (one merged draw for points, lines or triangles), or at a host step where the GPU writes them otherwise; `_checked` adds an `IndirectCommandCheck` that step calls on each command first, and the `IndirectCommandCheckNeeds` it looks for, which the GPU alone may rule out *(partial)* |
| `ExecuteCommandsIndirect` | `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:` | `RenderCommandEncoder::execute_commands_in_buffer_indirect`: the pass is recorded at a host step (announced once); `_checked` adds an `IndirectCommandCheck` the step calls on each command first, and the `IndirectCommandCheckNeeds` it looks for *(partial)* |
| `ExecuteCommandsInBuffer` | `executeCommandsInBuffer:withRange:` | `RenderCommandEncoder::execute_commands_in_buffer`: the records as they stand at commit, on the GPU alone where the commit can tell every command draws one primitive type under the inherited state (one merged draw for points, lines or triangles), or at a host step where the GPU writes them otherwise; `_checked` adds an `IndirectCommandCheck` that `commit` (for the CPU's records) or that step calls on each command first, and the `IndirectCommandCheckNeeds` it looks for, which may rule it out *(partial)* |
| `MemoryBarrierWithScope` | `memoryBarrierWithScope:afterStages:beforeStages:` | `RenderCommandEncoder::memory_barrier_with_scope` |
| `SetAlphaTestReferenceValue` | `setAlphaTestReferenceValue:` (SPI) | `RenderCommandEncoder::set_alpha_test_reference_value`: a no-op (no runtime pipeline has an alpha test) |
| `SetBlendColorRed` | `setBlendColorRed:green:blue:alpha:` | `RenderCommandEncoder::set_blend_color` |