From 9bec8a977ece3e3469ab06ae49218ec63ec5a465 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 23:56:45 -0800 Subject: [PATCH] rt: a dispatch that reaches a buffer bound off its argument's alignment is refused The planner ruled that the bind-offset mask becomes a typed refusal. The binder pushed a bound buffer's address, its gpuAddress plus the offset, rounded down to the alignment the kernel takes it to have (FieldValue::BufferAddress's mask, from RuntimeFact::AddressAlignment), where Metal's API validation refuses the bind offset ("must be a multiple of 4 but was set to 2" for a uint * argument, probe vector_access_placement.m in the conformance crate). Plain Metal runs such a dispatch at addresses of its own: an M3 Max reaches each element at its address rounded down to the smaller of its alignment and 4. That is not the rounding the binder did for 8- and 16-byte arguments. The dispatch now refuses it with Refusal::BufferOffsetAlignment { index, offset, alignment } before it records or keeps anything. check_alignment runs after the threadgroup size check and before a kernel without effects returns, so both direct and indirect dispatches take it. fill_parameters pushes each address as it is. A set_bytes copy sits at a multiple of 16 in the ring, which every mask divides, so it is never refused. Docs: - docs/API.md: the identity-domain paragraph and the section 10 entry (renamed: "A dispatch that reaches a buffer bound off its argument's alignment is refused"); no case names its slug. - RuntimeFact::AddressAlignment's doc and the mechanism comment. - The rt README paragraph and FieldValue::BufferAddress's doc. - docs/REFUSALS.md regenerated (44 rt refusals); api_signatures.tsv gains the variant's row. Tests (device, under --cfg m2v_gpu or m2v_cpu_icd): - every_device_refuses_a_bound_address_off_its_alignment (was ..._rounds_a_bound_address_down_...): at alignments 2, 4, 8 and 16, each of 17 binds 1 to 15 bytes past a multiple of 16 that the alignment does not divide is refused and leaves the buffer unchanged, and the same buffer bound at 48 runs. Without the check every one of the 17 dispatches returns Ok. - an_argument_bound_off_its_alignment_is_refused (was ..._runs_at_the_address_rounded_down): the translated vector_word_phases kernels with one argument off its alignment are refused, naming the index, offset and alignment, and the command buffer completes with every buffer unchanged. --- crates/metal2vulkan-rt/README.md | 9 +- crates/metal2vulkan-rt/src/encoder.rs | 43 ++++++-- crates/metal2vulkan-rt/src/error.rs | 26 +++++ crates/metal2vulkan-rt/src/pipeline.rs | 9 +- crates/metal2vulkan-rt/src/tests/compute.rs | 97 +++++++++++-------- crates/metal2vulkan-rt/src/tests/translate.rs | 65 +++++++------ crates/metal2vulkan/src/device/mechanism.rs | 2 +- crates/metal2vulkan/src/pipeline/facts.rs | 5 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 27 +++--- docs/REFUSALS.md | 6 +- 11 files changed, 184 insertions(+), 106 deletions(-) diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 1cc224849..01e5a7e19 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -682,10 +682,11 @@ that touch blocks first. before indirect argument reads gets one that does, in either kind of encoder. The other commands a segment records that touch memory, blit copies, order themselves against everything before and after them; the barrier at a segment's end takes every command and the host. -- A buffer bound where its address, its `gpuAddress` plus the offset, is not a multiple of its - kernel argument's alignment (`air.arg_type_align_size`, at most 16) is pushed rounded down to - that alignment, where Metal's API validation refuses the bind; `docs/API.md` section 10 says - where that differs from Metal without validation. +- A dispatch whose kernel reaches a buffer bound where its address, its `gpuAddress` plus the + offset, is not a multiple of the kernel argument's alignment (`air.arg_type_align_size`, at + most 16) is refused (`Refusal::BufferOffsetAlignment`) before anything is recorded, as Metal's + API validation refuses the bind offset. Plain Metal runs such a dispatch at addresses of its + own; `docs/API.md` section 10 says which. - Parameters: fields in the push window, `[0, 256)` on every device, are pushed: the dispatch region and up to 28 buffer addresses, each kernel pushing only the bytes it reads. Fields past it go to a 16-byte aligned block in the parameter ring, whose address is a field in the window: a diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index ddafbc0d0..b6611c956 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -540,8 +540,8 @@ impl ComputeCommandEncoder { /// each reading Metal's whole grid from its region. /// /// A kernel that writes no memory (`PipelineInterface::writes_memory`) has no effect a program - /// can observe: once the threadgroup size is checked, its dispatch, direct or indirect, records - /// nothing, binds nothing and reads no indirect buffer + /// can observe: once the threadgroup size and the bound buffers' alignment are checked, its + /// dispatch, direct or indirect, records nothing, binds nothing and reads no indirect buffer /// ([`Metrics::dispatches_without_effects`](crate::Metrics::dispatches_without_effects)). /// /// A threadgroup that is not whole subgroups of a kernel whose tier runs only whole ones (32 @@ -549,7 +549,9 @@ impl ComputeCommandEncoder { /// the kernel's emulated-SIMD-group module, waiting for the reaper's lowering of it where /// that is not done. /// - /// Err: [`Refusal::NoPipeline`]; [`Refusal::ThreadgroupSize`]; [`Limit::ThreadgroupShape`]; + /// Err: [`Refusal::NoPipeline`]; [`Refusal::ThreadgroupSize`]; + /// [`Refusal::BufferOffsetAlignment`] for a buffer the kernel reaches bound off its argument's + /// alignment, which nothing records; [`Limit::ThreadgroupShape`]; /// [`Limit::ThreadgroupMemory`]; [`Gap::PartialSimdgroups`] for a threadgroup that is not /// whole SIMD groups of a kernel whose tier needs them and that has no emulated module; /// [`Error::Quiesced`] where the device was quiesced before that module was lowered; @@ -670,11 +672,14 @@ impl ComputeCommandEncoder { if total == 0 || total > u64::from(max) { return Err(Error::Refused(Refusal::ThreadgroupSize { size, max })); } + // Every module of a state is the same function, with the same arguments and alignments, + // so the whole module answers this check and the next. + self.check_alignment(&inner.whole.interface)?; let core = Arc::clone(self.building().device.core()); let limits = &core.limits; // A kernel that writes no memory has no effect a program can observe: once checked as // Metal checks it, the dispatch records nothing, binds nothing and reads no indirect - // buffer. Every module of a state is the same function, so the whole module answers. + // buffer. if !inner.whole.interface.has_effects { core.counters.count(Metric::DispatchesWithoutEffects); return Ok(()); @@ -910,6 +915,28 @@ impl ComputeCommandEncoder { building.record_dispatch(pipeline, &mut self.parameters, &launch) } + /// [`Refusal::BufferOffsetAlignment`] where a buffer `interface` reaches is bound at an + /// address, its `gpuAddress` plus the offset, that is not a multiple of the alignment the + /// module takes it to have (`FieldValue::BufferAddress`'s mask). A `set_bytes` copy is at a + /// multiple of 16 in the ring, which every mask divides. + fn check_alignment(&self, interface: &Interface) -> Result<(), Error> { + for field in &interface.fields { + let FieldValue::BufferAddress { slot, mask } = field.value else { + continue; + }; + if let Some(Slot::Buffer { buffer, offset }) = self.slots.get(slot as usize) { + if buffer.gpu_address().wrapping_add(*offset) & mask != 0 { + return Err(Error::Refused(Refusal::BufferOffsetAlignment { + index: slot, + offset: *offset, + alignment: mask + 1, + })); + } + } + } + Ok(()) + } + /// The length set for threadgroup memory index `index`, 0 where none was. fn threadgroup_length(&self, index: u32) -> u32 { self.threadgroup_lengths @@ -923,8 +950,8 @@ impl ComputeCommandEncoder { /// samplers `sampler_ids`. The block's address is written by [`Building::record_dispatch`] /// once the block is in the ring. /// - /// A buffer's address that is not a multiple of the alignment the module takes it to have - /// goes rounded down to that alignment, where Metal's API validation refuses the bind offset. + /// Every buffer address is a multiple of the alignment the module takes it to have, which the + /// dispatch checked first (`check_alignment`). fn fill_parameters(&mut self, kernel: &Kernel, sampler_ids: &[u32], region: &[u8; 32]) { let interface: &Interface = &kernel.interface; let parameters = &mut self.parameters; @@ -940,14 +967,14 @@ impl ComputeCommandEncoder { Place::Block(offset) => (&mut parameters.block, offset as usize), }; match field.value { - FieldValue::BufferAddress { slot, mask } => { + FieldValue::BufferAddress { slot, .. } => { let address = match self.slots.get(slot as usize) { Some(Slot::Buffer { buffer, offset }) => { buffer.gpu_address().wrapping_add(*offset) } Some(Slot::Bytes(address)) => *address, Some(Slot::Empty) | None => 0, - } & !mask; + }; bytes[at..at + 8].copy_from_slice(&address.to_le_bytes()); } FieldValue::TextureId(slot) => { diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index b059c451d..9ec159678 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -206,6 +206,24 @@ pub enum Refusal { /// The buffer's length. length: u64, }, + /// A dispatch whose kernel reaches a buffer bound where its address, the buffer's + /// `gpuAddress` plus the bind offset, is not a multiple of the kernel argument's alignment + /// (`air.arg_type_align_size`, at most 16). Plain Metal runs such a dispatch at addresses of + /// its own: an Apple M3 Max reaches each element at its address rounded down to the smaller of + /// the element's alignment and 4 (`probes/misaligned_buffer_binds.m` in the conformance + /// crate). + /// + /// Basis: metal-documented (Metal's API validation refuses the bind offset: "must be a + /// multiple of 4 but was set to 2" for a `uint *` argument bound at offset 2, an Apple M3 Max, + /// macOS 27.0.1, `probes/vector_access_placement.m` in the conformance crate). + BufferOffsetAlignment { + /// The buffer argument index. + index: u32, + /// The bind offset. + offset: u64, + /// The argument's alignment in bytes. + alignment: u64, + }, /// A grant of an index already granted ([`Device::grant_indices`](crate::Device::grant_indices)). /// Metal has no counterpart: Metal chooses its resource IDs itself. /// @@ -1070,6 +1088,14 @@ impl fmt::Display for Refusal { f, "indirect arguments at offset {offset} of a {length}-byte buffer are misaligned or past its end" ), + Refusal::BufferOffsetAlignment { + index, + offset, + alignment, + } => write!( + f, + "the buffer at index {index}, bound at offset {offset}, is not at a multiple of its argument's {alignment}-byte alignment" + ), Refusal::IndicesGranted { class, index } => { write!(f, "{class:?} index {index} is granted already") } diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 6c34b66f6..d5b4dba47 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -374,9 +374,10 @@ pub(crate) enum Place { #[derive(Clone, Copy)] pub(crate) enum FieldValue { /// A `u64`: the address of the buffer bound at the slot plus its offset, the address of the - /// slot's `set_bytes` copy, or 0 where nothing is bound, rounded down to a multiple of the - /// alignment the module takes that address to have. `mask` is that alignment less 1 - /// (`RuntimeFact::AddressAlignment`), 0 where it takes none. + /// slot's `set_bytes` copy, or 0 where nothing is bound. `mask` is the alignment the module + /// takes that address to have, less 1 (`RuntimeFact::AddressAlignment`), 0 where it takes + /// none: a dispatch whose bound buffer's address it does not divide is refused + /// (`Refusal::BufferOffsetAlignment`). BufferAddress { slot: u32, mask: u64 }, /// A `u64`: the `gpuResourceID` of the texture bound at the slot, 0 where none is. TextureId(u32), @@ -778,7 +779,7 @@ fn interface( for dependency in &pipeline.dependencies { match dependency.fact { RuntimeFact::LocalSizeConstraint { multiple } => multiples.push(multiple), - // The slot's address, rounded down to a multiple of its argument's alignment. + // The slot's address, a multiple of its argument's alignment. RuntimeFact::AddressAlignment { slot: SlotRef { diff --git a/crates/metal2vulkan-rt/src/tests/compute.rs b/crates/metal2vulkan-rt/src/tests/compute.rs index 8374c4250..26462f8d6 100644 --- a/crates/metal2vulkan-rt/src/tests/compute.rs +++ b/crates/metal2vulkan-rt/src/tests/compute.rs @@ -140,20 +140,20 @@ pub(crate) mod on_device { }); } - /// The binder pushes a bound buffer's address rounded down to a multiple of the alignment the - /// kernel takes it to have (`FieldValue::BufferAddress`'s mask, `RuntimeFact::AddressAlignment` - /// in a translated kernel), where Metal's API validation refuses the bind offset. At each - /// alignment, 2, 4, 8 and 16, a buffer bound 1, 3, 4, 8, 12 or 15 bytes past a multiple of 16 - /// (each offset that is not a multiple of the alignment and rounds down to a word: 15 binds) - /// is stepped from its address rounded down to the alignment, and no other word changes. An - /// 8- or 16-byte alignment's bind 4, 8 or 12 bytes past a multiple of 16 is a word apart from - /// its rounded address, so a bind not rounded steps other words on every device. + /// A dispatch whose kernel takes a bound buffer's address to be a multiple of an alignment + /// (`FieldValue::BufferAddress`'s mask, `RuntimeFact::AddressAlignment` in a translated + /// kernel) that the address, the buffer's `gpuAddress` plus the offset, is not is refused, as + /// Metal's API validation refuses the bind offset (`Refusal::BufferOffsetAlignment`), and + /// records nothing. At each alignment, 2, 4, 8 and 16, every bind 1, 3, 4, 8, 12 or 15 bytes + /// past a multiple of 16 that is not a multiple of the alignment is refused (17 binds) and + /// leaves every word as it was; the same buffer bound 16 bytes past one then runs, stepping + /// the 16 words from its address. #[test] - fn every_device_rounds_a_bound_address_down_to_its_alignment() { - each_device("compute_rounded_address", |name, _, device| { + fn every_device_refuses_a_bound_address_off_its_alignment() { + each_device("compute_misaligned_address", |name, _, device| { let mut arena = Arena::new(&device); let queue = device.new_command_queue(4).expect("a queue"); - let mut runs = 0; + let mut refusals = 0; for align in [2u64, 4, 8, 16] { let fields = vec![ region(), @@ -172,42 +172,61 @@ pub(crate) mod on_device { interface(buffers, fields, 40), ) .expect("the step kernel"); + let x = arena.buffer(); + assert_eq!(x.gpu_address() % 16, 0, "{name}: the buffer's address"); + write_words(&x, |index| index); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); for at in [1u64, 3, 4, 8, 12, 15] { - let rounded = (32 + at) & !(align - 1); - if at % align == 0 || rounded % 4 != 0 { + if at % align == 0 { continue; } - let x = arena.buffer(); - assert_eq!(x.gpu_address() % 16, 0, "{name}: the buffer's address"); - write_words(&x, |index| index); - let command_buffer = queue.command_buffer().expect("a command buffer"); - let mut encoder = command_buffer - .compute_command_encoder(DispatchType::Serial) - .expect("an encoder"); - encoder.set_compute_pipeline_state(&state).expect("a state"); encoder.set_buffer(Some(&x), 32 + at, 0).expect("a buffer"); - encoder - .dispatch_threadgroups([1, 1, 1], [16, 1, 1]) - .expect("a dispatch"); - encoder.end_encoding(); - run(name, &command_buffer); - let stepped = rounded as u32 / 4..rounded as u32 / 4 + 16; - let expected: Vec = (0..WORDS as u32) - .map(|index| match stepped.contains(&index) { - true => index * 2 + 1, - false => index, - }) - .collect(); - assert_eq!( - words(&x), - expected, + assert!( + matches!( + encoder.dispatch_threadgroups([1, 1, 1], [16, 1, 1]), + Err(Error::Refused(Refusal::BufferOffsetAlignment { + index: 0, + offset, + alignment, + })) if offset == 32 + at && alignment == align + ), "{name}: alignment {align}, bound at 32 + {at}" ); - runs += 1; + refusals += 1; } + encoder.end_encoding(); + run(name, &command_buffer); + let unchanged: Vec = (0..WORDS as u32).collect(); + assert_eq!(words(&x), unchanged, "{name}: alignment {align}, refused"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + encoder.set_buffer(Some(&x), 48, 0).expect("a buffer"); + encoder + .dispatch_threadgroups([1, 1, 1], [16, 1, 1]) + .expect("an aligned dispatch"); + encoder.end_encoding(); + run(name, &command_buffer); + let expected: Vec = (0..WORDS as u32) + .map(|index| match (12..28).contains(&index) { + true => index * 2 + 1, + false => index, + }) + .collect(); + assert_eq!( + words(&x), + expected, + "{name}: alignment {align}, bound at 48" + ); } - assert_eq!(runs, 15, "{name}: the binds"); - println!("{name}: {runs} binds off their alignment, each run at the rounded address"); + assert_eq!(refusals, 17, "{name}: the binds"); + println!("{name}: {refusals} binds off their alignment refused, each aligned bind run"); }); } diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 2267bdbaa..fb1dcfeeb 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -19,7 +19,7 @@ mod on_device { use crate::{ host_time, Block, Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DeviceOptions, DispatchType, Error, FunctionDescriptor, Gauges, Instance, Library, Limit, - MemoryClass, PrecisionNote, StageSource, MAX_BUFFER_LENGTH, + MemoryClass, PrecisionNote, Refusal, StageSource, MAX_BUFFER_LENGTH, }; use metal2vulkan::pipeline::{RuntimeFact, StageEntries}; use metal2vulkan::Budget; @@ -1305,23 +1305,23 @@ mod on_device { } /// `vwp_vec16` takes its `float4 *` arguments' addresses to be multiples of 16 and `vwp_words` - /// its `uint *` arguments' multiples of 4 (`RuntimeFact::AddressAlignment`). Each argument - /// bound off that alignment (`vwp_words`'s 1 and 3 bytes past each word phase, `vwp_vec16`'s - /// 4 and 12 bytes past its multiples of 16) runs at the address rounded down to it, where - /// Metal's API validation refuses the bind: all four buffers hold Metal's words for the binds - /// at the rounded addresses (`vector_word_phases`' answer), and the command buffer completes - /// without error. + /// its `uint *` arguments' multiples of 4 (`RuntimeFact::AddressAlignment`). A dispatch with + /// either argument bound off that alignment (`vwp_words`'s 1 and 3 bytes past each word phase, + /// `vwp_vec16`'s 4 and 12 bytes past its multiples of 16) is refused, as Metal's API + /// validation refuses the bind (`Refusal::BufferOffsetAlignment`, naming the index, the offset + /// and the alignment), and records nothing: the command buffer completes without error and + /// every buffer holds its bytes as they were. #[test] - fn an_argument_bound_off_its_alignment_runs_at_the_address_rounded_down() { + fn an_argument_bound_off_its_alignment_is_refused() { use metal2vulkan_devtools::vector_word_phases::{ - answer, inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, WORDS, + inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, WORDS, }; let (Some(phased), Some(aligned)) = (descriptor_of(FIXTURE, WORDS), descriptor_of(FIXTURE, VEC16)) else { return; }; - each_device("compute_rounded_binds", |name, _, device| { + each_device("compute_misaligned_binds", |name, _, device| { let before = inputs(); let (phased, aligned) = ( state(name, &device, &phased), @@ -1338,6 +1338,7 @@ mod on_device { "{name}: the buffers' addresses" ); let queue = device.new_command_queue(4).expect("a queue"); + let mut refusals = 0; for offset in OFFSETS { for (buffer, bytes) in &held { write(buffer, 0, bytes); @@ -1347,9 +1348,12 @@ mod on_device { let mut encoder = command_buffer .compute_command_encoder(DispatchType::Serial) .expect("an encoder"); - for (state, binds) in [ - (&phased, [(0, offset + 1), (1, offset + 3)]), - (&aligned, [(2, a_at + 4), (3, b_at + 12)]), + // Each case binds one argument off its alignment and the other on it. + for (state, binds, off, alignment) in [ + (&phased, [(0, offset + 1), (1, offset)], 0, 4), + (&phased, [(0, offset), (1, offset + 3)], 1, 4), + (&aligned, [(2, a_at + 4), (3, b_at)], 0, 16), + (&aligned, [(2, a_at), (3, b_at + 12)], 1, 16), ] { encoder.set_compute_pipeline_state(state).expect("a state"); for (index, (buffer, at)) in binds.into_iter().enumerate() { @@ -1357,36 +1361,37 @@ mod on_device { .set_buffer(Some(&held[buffer].0), at, index as u32) .expect("a buffer"); } - encoder - .dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1]) - .unwrap_or_else(|error| panic!("{name}: offset {offset}: {error}")); + let at = binds[off as usize].1; + assert!( + matches!( + encoder.dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1]), + Err(Error::Refused(Refusal::BufferOffsetAlignment { + index, + offset: refused, + alignment: refused_alignment, + })) if index == off && refused == at && refused_alignment == alignment + ), + "{name}: offset {offset}: index {off} bound at {at}" + ); + refusals += 1; } encoder.end_encoding(); command_buffer.commit().expect("a commit"); finished(name, &command_buffer); assert_eq!(command_buffer.error(), None, "{name}: offset {offset}"); - let want = answer(offset); - for ((buffer, bytes), (which, want)) in held.iter().zip([ - ("src", &want.src), - ("dst", &want.dst), - ("a", &want.a), - ("b", &want.b), - ]) { + for ((buffer, bytes), which) in held.iter().zip(["src", "dst", "a", "b"]) { let got = words(buffer, 0, bytes.len() / 4); - let want: Vec = want + let want: Vec = bytes .as_chunks::<4>() .0 .iter() .map(|w| u32::from_le_bytes(*w)) .collect(); - let first = got.iter().zip(&want).position(|(x, y)| x != y); - assert_eq!( - first, None, - "{name}: offset {offset}: {which} differs from Metal's words at the rounded binds" - ); + assert_eq!(got, want, "{name}: offset {offset}: {which} changed"); } } - println!("{name}: each argument bound off its alignment ran at the rounded address"); + assert_eq!(refusals, 4 * OFFSETS.len(), "{name}: the binds"); + println!("{name}: {refusals} dispatches with an argument off its alignment refused"); }); } diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 66f5b30f2..788f3e3fd 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -206,7 +206,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::TexelRows { .. } => Mechanism::Variant, // Keyed by the slots bound to a texture buffer of more texels than one view holds. RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, - // The binder rounds the slot's address down to a multiple of the alignment. + // The runtime refuses a dispatch whose slot address is not a multiple of the alignment. RuntimeFact::AddressAlignment { .. } => Mechanism::PlanTimeCheck, // The function marks the `ExecutionStatus` buffer its `ExecutionStatus` fact binds; the // consumer reads the bit after the command buffer. diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 0ece159d4..3faf6b4fe 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -877,9 +877,8 @@ pub enum RuntimeFact { /// bind offset, is a multiple of `align` (2, 4, 8 or 16): its argument's alignment /// (`air.arg_type_align_size`, at most 16). Metal's API validation refuses a bind offset that /// is not a multiple of it ("must be a multiple of 4 but was set to 2" for a `uint *` argument, - /// `probes/vector_access_placement.m` in the conformance crate), and the binder rounds such an - /// address down to a multiple of it before the work runs. Where `align` is at least 4 the - /// function reaches the slot from + /// `probes/vector_access_placement.m` in the conformance crate), and the runtime refuses a + /// dispatch at such an address. Where `align` is at least 4 the function reaches the slot from /// that address as it is: no access rounds it to a word, and an 8- or 16-byte access at an /// offset proven a multiple of its size is one `uvec2` or `uvec4`. AddressAlignment { slot: SlotRef, align: u32 }, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6816207ea..f0ffa3bf0 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13569,6 +13569,7 @@ variant metal2vulkan-rt::Refusal::BufferCopyOverlap BufferCopyOverlap { source_o variant metal2vulkan-rt::Refusal::BufferCopyRange BufferCopyRange { offset: u64, size: u64, len: u64 } variant metal2vulkan-rt::Refusal::BufferCopyUnaligned BufferCopyUnaligned { source_offset: u64, destination_offset: u64, size: u64 } variant metal2vulkan-rt::Refusal::BufferIndex BufferIndex { index: u32 } +variant metal2vulkan-rt::Refusal::BufferOffsetAlignment BufferOffsetAlignment { index: u32, offset: u64, alignment: u64 } variant metal2vulkan-rt::Refusal::BufferPastBlock BufferPastBlock { offset: u64, length: u64, block_len: u64 } variant metal2vulkan-rt::Refusal::BufferTextureLayout BufferTextureLayout { offset: u64, bytes_per_row: u64, len: u64 } variant metal2vulkan-rt::Refusal::BufferTooLong BufferTooLong { length: u64, max: u64 } diff --git a/docs/API.md b/docs/API.md index fb739f910..42b18c161 100644 --- a/docs/API.md +++ b/docs/API.md @@ -117,9 +117,9 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: address plus its 32-bit byte offset, sign-extended, which is exact as the new runtime makes no buffer longer than 2 GiB (`MAX_BUFFER_LENGTH`), and an access of 8 or 16 bytes at an offset proven a multiple of its size is one `uvec2` or `uvec4`. The function states - `RuntimeFact::AddressAlignment` with that alignment (at most 16), and a binder rounds a bound - address down to a multiple of it, where Metal's API validation refuses the bind offset (an - accepted difference, section 10). A + `RuntimeFact::AddressAlignment` with that alignment (at most 16), and the new runtime refuses + a dispatch whose bound address is not a multiple of it, as Metal's API validation refuses the + bind offset (an accepted difference, section 10). A slot whose argument states an alignment below 4, or none, is reached the same way where each of its accesses is one 1- or 2-byte unit no wider than that alignment (an `i8` access of a `uchar` buffer, an `i16` one of a `ushort` buffer) on a device with that width's storage access. Any @@ -6415,18 +6415,15 @@ each item named states the rule in full. an argument the kernel writes may read those bytes as they were before its own writes, where the device reads read-only memory through another path (RADV reads a uniform address of it with a scalar load). The attribute states that no other argument reaches that memory. -- **A buffer bound off its argument's alignment is reached at the address rounded down to that - alignment** (the alignment the kernel's AIR states for the argument, `air.arg_type_align_size`, - at most 16; `RuntimeFact::AddressAlignment`): the new runtime's binder rounds the bound address, - the buffer's `gpuAddress` plus the offset, before the dispatch runs. Metal's API validation - refuses such a bind offset ("must be a multiple of 4 but was set to 2" for a `uint *` argument). - Without validation an Apple M3 Max (macOS 27.0.1) reaches each element at its address rounded - down to the smaller of the element's alignment and 4, for loads, stores and pointers stored in a - buffer alike (`crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m`). The two agree - for arguments of alignment 2 and 4, and for 8- and 16-byte ones bound 1 to 3 bytes off a - multiple of 4; an 8- or 16-byte argument bound at a multiple of 4 that is not a multiple of its - alignment is reached at the address rounded down to 8 or 16, where the M3 reaches it exactly - there. +- **A dispatch that reaches a buffer bound off its argument's alignment is refused** (the + alignment the kernel's AIR states for the argument, `air.arg_type_align_size`, at most 16; + `RuntimeFact::AddressAlignment`): the new runtime refuses the dispatch + (`Refusal::BufferOffsetAlignment`) where the bound address, the buffer's `gpuAddress` plus the + offset, is not a multiple of it, before anything is recorded, as Metal's API validation refuses + such a bind offset ("must be a multiple of 4 but was set to 2" for a `uint *` argument). + Without validation an Apple M3 Max (macOS 27.0.1) runs it, reaching each element at its address + rounded down to the smaller of the element's alignment and 4, for loads, stores and pointers + stored in a buffer alike (`crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m`). - **An imageblock's length rounds its cell as an M4 does** (`ComputePipelineState::imageblock_memory_length_for_dimensions`), never less than what a dispatch counts against the device's threadgroup memory. diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index cf1a5c56c..6a0ac5631 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,7 +37,7 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 46 | 46 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 47 | 47 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 11 | 11 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 19 | 19 | 0 | 0 | 0 | 0 | 0 | @@ -55,7 +55,7 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 14 | 12 | 0 | 0 | 20 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 14 | 13 | 0 | 0 | 20 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 8 | 3 | 0 | 0 | 0 | | The new runtime's `Gap` | 0 | 0 | 0 | 0 | 19 | 0 | 0 | 0 | @@ -631,6 +631,7 @@ Columns: | `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` | `-` | | `ThreadgroupSize` | A threadgroup of no threads, or of more than the pipeline state's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` | `-` | | `IndirectOffset` | An indirect dispatch's argument offset that is not a multiple of 4, or that leaves fewer than 12 bytes (three 32-bit counts) in the buffer | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads three 32-bit counts at a 4-byte aligned offset inside the buffer | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` | `-` | +| `BufferOffsetAlignment` | A dispatch whose kernel reaches a buffer bound where its address, the buffer's `gpuAddress` plus the bind offset, is not a multiple of the kernel... | every device (a public call's own check of its arguments) | `metal-documented`: Metal's API validation refuses the bind offset: "must be a multiple of 4 but was set to 2" for a `uint *` argument bound at offset 2, an Apple M3 Max, macOS 27.0.1, `probes/vector_access_placement.m` in the conformance crate | 1: `crates/metal2vulkan-rt/src/encoder.rs (check_alignment)` | `-` | | `IndicesGranted` | A grant of an index already granted (`Device::grant_indices`) | every device (a public call's own check of its arguments) | `ours`: each index has one grant, so each resource ID names one object | 1: `crates/metal2vulkan-rt/src/arrays.rs (grant)` | `-` | | `IndicesNotGranted` | A release of an index that is not granted (`Device::release_indices`) | every device (a public call's own check of its arguments) | `ours`: a grant is returned once | 2: `crates/metal2vulkan-rt/src/arrays.rs (occupy)`, `crates/metal2vulkan-rt/src/arrays.rs (release)` | `-` | | `IndexInUse` | A texture, a sampler state or a pipeline state's constexpr sampler at an index where another object lives already (`Device::new_texture`,... | every device (a public call's own check of its arguments) | `ours`: an index names one object at a time, and its elements are that object's | 2: `crates/metal2vulkan-rt/src/arrays.rs (occupy)`, `crates/metal2vulkan-rt/src/sampler.rs (hold_constexpr)` | `-` | @@ -1206,6 +1207,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` - `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` - `rt:Refusal::IndirectOffset`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` +- `rt:Refusal::BufferOffsetAlignment`: `crates/metal2vulkan-rt/src/encoder.rs (check_alignment)` - `rt:Refusal::IndicesGranted`: `crates/metal2vulkan-rt/src/arrays.rs (grant)` - `rt:Refusal::IndicesNotGranted`: `crates/metal2vulkan-rt/src/arrays.rs (occupy)`; `crates/metal2vulkan-rt/src/arrays.rs (release)` - `rt:Refusal::IndexInUse`: `crates/metal2vulkan-rt/src/arrays.rs (occupy)`; `crates/metal2vulkan-rt/src/sampler.rs (hold_constexpr)`