rt: a draw through buffers bound at a multiple of 4 below their alignment draws the state's word-bound content

Row L97 (the draw residual). A dispatch of a function's kernel whose buffer
argument of 8 or 16 is bound at a multiple of 4 below that alignment runs a
variant of its kernel that holds the slot to 4 (8 where a 64-bit atomic may
reach it). A draw refused such a bind (Refusal::BufferOffsetAlignment). It
now draws the same way.

- RenderPipelineState::for_words(device, words) makes the state's content
  with LoweringInputs::word_bound_buffers set for its vertex function (bits
  0..31) and fragment function (bits 32..63). The device's map of contents
  keeps it under the state's key with that mask (KernelKey.words widens to
  u64). Like a pass's 2D-array content, it has no cache record of its own.
  Its samplers are numbered at the state's indices; a mismatch is
  Gap::KernelInput (ConstexprSampler).
- RenderCommandEncoder keeps the state set (`base`) apart from the state it
  draws through (`pipeline`). Where a draw's facts are not held (a bind or
  the state changed), bind_words reads the base's buffer address fields. A
  slot of mask 7 or 15 whose bound address is a multiple of 4 but not of
  its alignment sets its bit. The mask is ANDed with the slots the state
  lowers from AIR (word_slots: a function the consumer compiled has none,
  and its bind stays refused). A new mask switches `pipeline` to that
  content, or back to `base`. An execution of an indirect command buffer
  draws through `base`.
- The draw's own checks then hold each slot to the content's alignment: an
  address off a multiple of 4 is still refused, as is one off 8 that a
  64-bit atomic may reach.

Cost: a draw bound aligned keeps the state it was set with, and the scan of
its address fields runs only where the draw's facts are found again
(expected from the code, not measured). The first draw of a new mask lowers
both functions again and makes the content's VkPipeline (a first-use wait),
as the compute variant does. A later draw of that mask finds the content.

Docs: the runtime README (Render encoders: the draw bullet; Compute
encoders: the variant's paragraph); error.rs's BufferOffsetAlignment;
docs/API.md section 1 and its accepted differences. REFUSALS.md unchanged
(refusal_surface --check 0); api signatures --check 0.

Verified:
- Green on lavapipe, m3-max-79015 (at this commit's tree before its rebase
  onto 8dd00ec58c). Over tests::draw, render_offsets and indirect: 67 of 67
  passed, 838 skipped. The new test draws every case through the content,
  and the second draw of a bind finds it.
- The two draw-alignment tests on a card per vendor, 2 of 2 passed on each:
  - Radeon 780M (RADV PHOENIX, Mesa 26.2.6), m3-max-79076, at this commit;
  - RTX 3090 (NVIDIA 620.70.06), m3-max-79043, and Iris Xe (ANV, Mesa
    26.2.6), m3-max-79051, both before the rebase.
- m3-max-79086, at this commit: workspace clippy (all targets, all
  features, -D warnings) EXIT=0 in all three configurations (plain,
  --cfg m2v_cpu_icd, --cfg m2v_gpu); Rustdoc EXIT=0; the runtime's private
  Rustdoc EXIT=0. The runtime suite on lavapipe: 903 tests run, 903 passed,
  3 skipped.
This commit is contained in:
Anees Iqbal committed 2026-12-02 09:30:59 -08:00
1 parent d8c04db088
commit 7a1da6cb22
7 files changed
+204 -34

No files matched your search

+15 -1
View File
@@ -2979,7 +2979,8 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
(`LoweringInputs::word_bound_buffers`), lowered at its first such dispatch and kept in the
device's map of contents under the state's key with the mask of those slots. The variant
holds a buffer a 64-bit atomic may reach to 8, and refuses it off a multiple of 8. A kernel the
consumer compiled has no variant and refuses such a bind; a draw refuses it too.
consumer compiled has no variant and refuses such a bind. A draw takes such a bind of its
vertex or fragment function the same way (render encoders).
- Parameters: fields in the push window, `[0, W)`, are pushed, `W` the device's
`maxPushConstantsSize` up to 256 bytes (`DeviceProfile::push_window`: 256 on every lab device,
128 on a device that reports Vulkan's least): the dispatch region and up to 24 buffer addresses
@@ -4775,6 +4776,19 @@ cache is answered compile-required on both.
A draw takes no barrier, as Metal orders none between the draws of one encoder, so a pass of
any number of draws records the barriers a pass of one does. A draw of no vertices, indices or instances
records nothing.
- A draw whose vertex or fragment function reaches a buffer bound where its address, its
`gpuAddress` plus the offset, is not a multiple of the argument's alignment
(`air.arg_type_align_size`, at most 16) is refused (`Refusal::BufferOffsetAlignment`) before
anything is recorded, as a dispatch's is (compute encoders), but for a function the state lowers
from its AIR whose argument of 8- or 16-byte alignment is bound at a multiple of 4 below it:
plain Metal reaches each element at its own address there, and the draw draws through the
state's content that holds those buffers to 4 (`LoweringInputs::word_bound_buffers`), kept
in the device's map of contents under the state's key with the mask of those slots of both
functions. The first such draw lowers both functions again and makes
the content's `VkPipeline` (a first-use wait); a draw after it finds the content. The encoder
looks at its buffers again only after a change. A buffer a 64-bit atomic may reach is held to
8 and refused off a multiple of 8. An execution of an indirect command buffer's commands
draws through the state itself.
- `set_tessellation_factor_buffer` is `setTessellationFactorBuffer:offset:instanceStride:`, and
`draw_patches` is `drawPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:instanceCount:baseInstance:`
with a post-tessellation vertex function's state: one `vkCmdDraw` of `patchCount` vertices from
+9 -8
View File
@@ -483,14 +483,15 @@ pub enum Refusal {
/// A dispatch whose kernel, or a draw whose vertex or fragment function, reaches a buffer
/// bound where its address, the buffer's `gpuAddress` plus the bind offset, is not a multiple
/// of the alignment the function holds it to: the argument's (`air.arg_type_align_size`, at
/// most 16), but 4 for an argument of 8 or 16 that a dispatch of a function's kernel binds at
/// a multiple of 4, or 8 where a 64-bit atomic may reach that buffer. 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), which is not emulated. At a
/// multiple of 4 that is each element's own address, which the dispatch reaches through a
/// variant of its kernel that holds the buffer to 4 (`LoweringInputs::word_bound_buffers`); a
/// draw, and a kernel the consumer compiled, have no such variant.
/// most 16), but 4 for an argument of 8 or 16 that a dispatch of a function's kernel, or a
/// draw of a function's vertex or fragment function, binds at a multiple of 4, or 8 where a
/// 64-bit atomic may reach that buffer. Plain Metal runs such a dispatch or draw 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), which is not emulated. At a multiple of 4 that is each element's own
/// address, which the dispatch or draw reaches through a variant of its functions that holds
/// the buffer to 4 (`LoweringInputs::word_bound_buffers`); a function the consumer compiled
/// has no such variant.
///
/// 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,
@@ -28,15 +28,18 @@ pub(crate) const KERNEL_ENTRIES: usize = 1024;
/// and the translator's key leaves out (`None` for a render pipeline); for a compute state's
/// variant, its texture slots that hold an 8-bit sRGB texture's UNORM twin and its buffer slots
/// bound at a multiple of 4 below their argument's alignment, bit `i` slot `i` in each
/// (`PipelineInner::variant`); and for a render state's content for a pass, the colours its
/// (`PipelineInner::variant`); for a render state's content for a pass, the colours its
/// fragment function fetches through an element holding a 2D array view, bit `i` colour `i`
/// (`RenderPipelineState::for_pass`). Each is 0 for every other content.
/// (`RenderPipelineState::for_pass`); and for a render state's content for its draws' buffers,
/// the buffer slots bound at a multiple of 4 below their argument's alignment, bit `i` the vertex
/// function's slot `i` and bit `32 + i` the fragment function's
/// (`RenderPipelineState::for_words`). Each is 0 for every other content.
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct KernelKey {
pub(crate) pipeline: PipelineKey,
pub(crate) required: Option<[u32; 3]>,
pub(crate) srgb: u128,
pub(crate) words: u32,
pub(crate) words: u64,
pub(crate) arrays: u8,
}
+1 -1
View File
@@ -2435,7 +2435,7 @@ impl PipelineInner {
let (descriptor, key) = self.source.as_ref()?;
let key = KernelKey {
srgb,
words,
words: u64::from(words),
..key.clone()
};
if let Some(compiled) = core.kernels.find(&key) {
+78 -11
View File
@@ -639,20 +639,22 @@ impl crate::Device {
sampler_ids: impl FnOnce(&[NumberedSampler]) -> Result<Vec<u32>, Error>,
) -> Result<RenderPipelineState, Error> {
let stages = std::iter::once(&descriptor.vertex).chain(&descriptor.fragment);
(self.render_pipeline_state(descriptor, 0, sampler_ids))
(self.render_pipeline_state(descriptor, (0, 0), sampler_ids))
.map_err(|error| error.of_stages(stages))
}
/// [`new_render_pipeline_state`](Self::new_render_pipeline_state), its translator's error
/// naming no function; with `arrays` (bit `i` colour `i`), the content whose fragment
/// function fetches those colours through an element holding a 2D array view
/// (`LoweringInputs::arrayed_fetches`), which the device's map of contents keeps under the
/// descriptor's key with them, and whose record the cache directory neither reads nor keeps
/// (the record is the descriptor's own content's).
/// (`LoweringInputs::arrayed_fetches`), and with `words` (bit `i` the vertex function's buffer
/// slot `i`, bit `32 + i` the fragment function's), the content that holds those slots to
/// what their accesses need (`LoweringInputs::word_bound_buffers`), which the device's map of
/// contents keeps under the descriptor's key with them, and whose record the cache directory
/// neither reads nor keeps (the record is the descriptor's own content's).
fn render_pipeline_state(
&self,
descriptor: &RenderPipelineDescriptor,
arrays: u8,
(arrays, words): (u8, u64),
sampler_ids: impl FnOnce(&[NumberedSampler]) -> Result<Vec<u32>, Error>,
) -> Result<RenderPipelineState, Error> {
refuse(descriptor)?;
@@ -661,7 +663,7 @@ impl crate::Device {
pipeline: core.translator.queried_render_descriptor_key(descriptor),
required: None,
srgb: 0,
words: 0,
words,
arrays,
};
let compiled = match core.kernels.find_render(&key) {
@@ -669,9 +671,10 @@ impl crate::Device {
None => {
let budget = Budget::standard();
let content = key.pipeline.digest();
// A content for a pass's 2D arrays has no record of its own.
let record = match arrays {
0 => recorded(core, descriptor, content),
// A content for a pass's 2D arrays or for its draws' buffers has no record of its
// own.
let record = match (arrays, words) {
(0, 0) => recorded(core, descriptor, content),
_ => None,
};
let lowered = match record {
@@ -687,14 +690,28 @@ impl crate::Device {
)
})
.map_err(Error::translation)?;
let word_bound = |stage, first: u32| {
(0..BUFFER_SLOTS)
.filter(|&index| words >> (first + index) & 1 == 1)
.map(|index| SlotRef {
stage,
class: SlotClass::Buffer,
index,
})
.collect()
};
if let Some(inputs) = keys.vertex_inputs.as_mut() {
inputs.word_bound_buffers = word_bound(Stage::Vertex, 0);
}
if let Some(inputs) = keys.fragment_inputs.as_mut() {
inputs.arrayed_fetches =
(0..8).filter(|&color| arrays >> color & 1 == 1).collect();
inputs.word_bound_buffers = word_bound(Stage::Fragment, 32);
}
let lowered = lower_stages(core, descriptor, &keys, &budget, entries);
core.note_entries();
let (lowered, lowerings) = lowered?;
if arrays == 0 {
if (arrays, words) == (0, 0) {
cache::keep_record(core, content, &lowerings);
}
lowered
@@ -1793,7 +1810,7 @@ impl RenderPipelineState {
}
}
let numbered = (&self.inner.compiled.numbered, &self.inner.numbered.ids);
let state = device.render_pipeline_state(&descriptor, arrays, |samplers| {
let state = device.render_pipeline_state(&descriptor, (arrays, 0), |samplers| {
match samplers == numbered.0.as_slice() {
true => Ok(numbered.1.clone()),
false => Err(refused()),
@@ -1805,6 +1822,56 @@ impl RenderPipelineState {
}
}
/// The buffer slots a content for its draws' buffers can hold to 4
/// ([`for_words`](Self::for_words)): bit `i` the vertex function's slot `i`, bit `32 + i` the
/// fragment function's, of each function the state lowers from its AIR. None of a function
/// the consumer compiled, which has no function to lower again: its own module's checks
/// refuse such a bind.
pub(crate) fn word_slots(&self) -> u64 {
let all = (1u64 << BUFFER_SLOTS) - 1;
let d = &self.inner.descriptor;
let vertex = match d.vertex {
StageSource::Function(_) => all,
_ => 0,
};
let fragment = match d.fragment {
Some(StageSource::Function(_)) => all << 32,
_ => 0,
};
vertex | fragment
}
/// The state of this state's content for draws whose buffer slots of `words` (bit `i` the
/// vertex function's slot `i`, bit `32 + i` the fragment function's) are bound at a multiple
/// of 4 below their argument's alignment, 8 or 16: its functions lowered again with those
/// slots held to what their accesses need, 4, or 8 where a 64-bit atomic may reach one
/// (`LoweringInputs::word_bound_buffers`), each element read and written at its own address,
/// as plain Metal draws (Metal's API validation stops the bind). A content of its own, which
/// the device's map of contents holds as any content, and which the calling thread makes
/// where the device holds none. Its samplers are numbered at this state's indices; its
/// `VkPipeline` is made by its first draw (a first-use wait,
/// `Metrics::first_use_unfinished_waits`).
///
/// Err: as [`new_render_pipeline_state`](crate::Device::new_render_pipeline_state);
/// [`Gap::KernelInput`] of a constexpr sampler where that content numbers other samplers.
pub(crate) fn for_words(
&self,
device: &crate::Device,
words: u64,
) -> Result<RenderPipelineState, Error> {
let numbered = (&self.inner.compiled.numbered, &self.inner.numbered.ids);
let arrays = self.inner.compiled.draws.arrays;
let descriptor = &self.inner.descriptor;
device.render_pipeline_state(descriptor, (arrays, words), |samplers| {
match samplers == numbered.0.as_slice() {
true => Ok(numbered.1.clone()),
false => Err(crate::pipeline::gap(
crate::error::KernelInputKind::ConstexprSampler,
)),
}
})
}
/// No Metal counterpart: makes the state's main `VkPipeline`s on the calling thread, through
/// the device's pipeline cache, once the state's creation has answered. Metal compiles a
/// render state when the state is made. Here the creation does everything up to the driver's
@@ -740,8 +740,18 @@ pub struct RenderCommandEncoder {
command: vk::CommandBuffer,
/// The vertex function's argument tables, then the fragment function's.
tables: [Tables; 2],
/// The state set, borrowed from what the command buffer keeps (`crate::kept`).
/// The state a draw draws through, borrowed from what the command buffer keeps
/// (`crate::kept`): `base`, or its content for the buffers bound
/// ([`RenderPipelineState::for_words`]).
pipeline: Option<Lent<RenderPipelineState>>,
/// The state set, or its content for the pass ([`set_render_pipeline_state`]), borrowed
/// likewise.
///
/// [`set_render_pipeline_state`]: Self::set_render_pipeline_state
base: Option<Lent<RenderPipelineState>>,
/// The buffer slots `pipeline`'s content holds to 4, as
/// [`RenderPipelineState::for_words`] takes them; 0 where it is `base`.
words: u64,
/// The tessellation factor buffer and its offset, borrowed likewise.
factors: Option<(Lent<Buffer>, u64)>,
/// Whether the pipeline state renders into the pass's attachments' formats.
@@ -854,6 +864,8 @@ impl CommandBuffer {
command,
tables: [Tables::new(), Tables::new()],
pipeline: None,
base: None,
words: 0,
factors: None,
renders_into: false,
tests: Tests::of(&DepthStencilDescriptor::default()),
@@ -1099,7 +1111,7 @@ impl RenderCommandEncoder {
if !state.is_of(self.building().device.core()) {
return Err(Error::Refused(Refusal::OtherDevice));
}
if self.pipeline.as_ref().is_some_and(|set| set.is(state)) {
if self.base.as_ref().is_some_and(|set| set.is(state)) {
return Ok(());
}
let compiled = &state.inner.compiled;
@@ -1111,8 +1123,8 @@ impl RenderCommandEncoder {
let arrays = compiled.arrayed_fetches(&self.pass);
let Some(lacked) = lacked.filter(|&lacked| lacked != 0 || arrays != 0) else {
// SAFETY: the encoder holds the borrow, and it ends before its command buffer commits.
self.pipeline = Some(unsafe { self.building().lend_render_pipeline(state) });
self.changed();
let lent = unsafe { self.building().lend_render_pipeline(state) };
self.set_base(lent);
return Ok(());
};
let building = (self.building.as_ref())
@@ -1125,11 +1137,73 @@ impl RenderCommandEncoder {
// no colour.
self.renders_into = failed.is_none() || lacked == 0;
// SAFETY: as above.
self.pipeline = Some(unsafe { self.building().lend_render_pipeline(&drawn) });
self.changed();
let lent = unsafe { self.building().lend_render_pipeline(&drawn) };
self.set_base(lent);
failed.map_or(Ok(()), Err)
}
/// `state` drawn through, its draws' buffers to be looked at again.
fn set_base(&mut self, state: Lent<RenderPipelineState>) {
self.pipeline = Some(state.clone());
self.base = Some(state);
self.words = 0;
self.changed();
}
/// Where the buffers bound change what a draw draws through: `base`, or where a buffer
/// argument of a function the state lowers whose alignment is 8 or 16 is bound at a multiple
/// of 4 below it, the state's content that holds those slots to what their accesses need
/// ([`RenderPipelineState::for_words`]), found in the device's map of contents or made now,
/// which plain Metal draws, each element at its own address. A bind off a multiple of 4 is
/// left to the draw's checks, which refuse it. An execution's commands bind their own slots:
/// it draws through `base`.
///
/// Err: as [`RenderPipelineState::for_words`].
fn bind_words(&mut self, executes: bool) -> Result<(), Error> {
let Some(base) = self.base.clone() else {
return Ok(());
};
let lowers = base.word_slots();
let mut words = 0;
for &(_, table, value) in (!executes)
.then_some(&base.inner.compiled.draws.fields)
.into_iter()
.flatten()
{
let FieldValue::BufferAddress { slot, mask } = value else {
continue;
};
if let Some(Bound::Buffer { buffer, offset }) =
self.tables[table].buffers.get(slot as usize)
{
let at = buffer.gpu_address().wrapping_add(*offset);
if mask > 3 && at & mask != 0 && at & 3 == 0 {
words |= 1 << (32 * table as u32 + slot);
}
}
}
let words = words & lowers;
if words == self.words {
return Ok(());
}
let drawn = match words {
0 => base,
_ => {
let device = &(self.building.as_ref())
.expect("an encoder holds its command buffer's recording until it ends")
.device;
let made = base.for_words(device, words)?;
// SAFETY: the encoder holds the borrow, and it ends before its command buffer
// commits.
unsafe { self.building().lend_render_pipeline(&made) }
}
};
self.pipeline = Some(drawn);
self.words = words;
self.push_filled = false;
Ok(())
}
/// `setVertexBuffer:offset:atIndex:` (`setVertexBuffers:offsets:withRange:` is a loop of it).
/// `None` unbinds the slot. The slot serves the vertex function's buffer argument of its index
/// and the vertex descriptor's layout of its index alike. The command buffer keeps the buffer,
@@ -2669,6 +2743,16 @@ impl RenderCommandEncoder {
self.push_filled = false;
}
}
// The buffers bound, looked at again, may ask the state's content that holds some of
// them to 4: the draw draws through it from here.
if !self.facts.held {
self.bind_words(matches!(call, Call::Commands { .. }))?;
}
let Some(state) = &self.pipeline else {
return Err(Error::Refused(Refusal::NoPipeline));
};
let compiled = &state.inner.compiled;
let draws = &compiled.draws;
if !self.facts.held {
self.facts
.find(draws, &self.tables, &self.pass, &self.declared)?;
@@ -3219,7 +3303,7 @@ impl RenderCommandEncoder {
///
/// Err: as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) for the state.
pub(crate) fn execution_part(&self, buffer: &IndirectCommandBuffer) -> Result<u32, Error> {
let Some(state) = &self.pipeline else {
let Some(state) = &self.base else {
return Err(Error::Refused(Refusal::NoPipeline));
};
let compiled = &state.inner.compiled;
+4 -3
View File
@@ -145,7 +145,7 @@ and so do the command line, the compile worker and every validation tool. It hol
such a slot in `LoweringInputs::word_bound_buffers` states the argument's alignment up to what
the slot's accesses need, 4, or 8 where a 64-bit atomic may reach it (any slot, where one goes
through a pointer loaded from memory), and its accesses through the address claim no more
`Aligned` than that; the runtime's dispatch of such a bind runs that variant. A slot whose argument states an alignment below 4, or none, is reached the same way where each of
`Aligned` than that; the runtime's dispatch or draw of such a bind runs that variant. 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
other slot is reached from the word below each access, its offset sign-extended, so an access
@@ -2832,8 +2832,9 @@ named states the rule in full.
A function kernel's argument of 8- or 16-byte alignment bound at a multiple of 4 below it is not
refused: that rule reaches each of its elements at its own address, and the dispatch runs a
variant of the kernel that reaches them there (section 1, `LoweringInputs::word_bound_buffers`),
though Metal's API validation refuses that bind offset too. Such a buffer that a 64-bit atomic
may reach off a multiple of 8, a draw's, and a consumer-compiled kernel's are still refused.
though Metal's API validation refuses that bind offset too; a draw's vertex or fragment
function bound so runs the state's content lowered the same way. Such a buffer that a 64-bit
atomic may reach off a multiple of 8, and a consumer-compiled function's, are still refused.
- **A bound kernel buffer's out-of-bounds reach is its descriptor's, a few bytes wider than the
buffer** on a device that binds a kernel's buffers (section 1,
`DeviceProfile::binds_kernel_buffers`). Out-of-bounds accesses of a buffer are undefined in