From b2df1add01007c8f5a6ec575e2e035729c117d4a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 14:31:54 -0800 Subject: [PATCH] Bind a storage view of a whole buffer from its space's start, so draws that move only an offset keep their set 0 What: `bind::instantiate::planned_range` gives a descriptor-form slot read through a storage view of its `Whole` window the range from the start of the bound buffer's space to its padded end, whatever the bind offset, and the bind offset as its `SlotBindOffset` residual. `bind_buffers` (every draw's and dispatch's instantiation) and `rebind_slots` (`rebind_draw_slots_into`) take it. Every other slot keeps `descriptor_range`'s range: uniform views (whose `RangeAtBindOffset` specialization reads a range from the bind offset), bounded windows, and a storage view whose range from 0 would pass the view's `maxStorageBufferRange` (`PlannedBuffer::max_range`) or 2^32 bytes (a 32-bit residual and offset), or whose bind offset lies at or past the padded end. The tessellation factor and index bindings keep it too. Why: `EncoderCore::set_zero_of` was 14.3% (draws.10k) and 8.8% (WS-like) of the encoding thread's samples: every draw allocated, wrote and bound a set 0 of its own. A `device T *` slot's range started at the bind offset aligned down, so each new offset wrote another descriptor and neither `LastSetZero` nor `SetCache` could match. Vulkan: the descriptor's offset is the space's start (256-aligned, as a bind at offset 0 has it today) and its range ends where today's ends (the padded end), so offset + range, and a dynamic binding's effective offset + range (VUID-vkCmdBindDescriptorSets-pDescriptorSets-01979), are what they were. dynamic_writes moves that same start into the dynamic offset for every bind offset. The range is explicit, never VK_WHOLE_SIZE (06715 does not apply). Hazard ranges are untouched: they come from the plan's use ranges from the bind offset (`binding::bytes_use`). Behaviour: a Metal offset m from the bind offset reads byte residual + m of the range, the same byte as before for every access inside the window. An access that reaches back before the bind offset (a negative index, the 32-bit offset wrapping) and lands in the buffer's space now reads and writes the buffer's bytes there, as Metal's does; before, it lay outside the descriptor range unless it stayed within the alignment's residue. On a device with robustBufferAccess (or under in-shader containment against the view's size) accesses are bounded by the larger range [space start, padded end) instead of [bind offset aligned down, padded end): such an access before the bind offset is in range and reaches the buffer's bytes where it was a robust out-of-bounds access (a zero, a value from within the buffer, or a dropped write). Accesses past the end are bounded as before. SEMANTICS_VERSION 1957 -> 1958: instantiated descriptor ranges and residuals change. golden_hashes_match_the_table passed unchanged here (it hashes compiled modules, which this does not change); the re-bless on development decides. Tests: planned_range's unit tests (the range from 0 and the residual at every 4-byte offset for base alignments 16, 64 and 256, and a 2^32-byte buffer at its last word; each fallback equal to descriptor_range's answer). A device test, set_zero_at_offsets: 9 draws of colored_vertex moving only two device buffers' offsets reuse 8 sets and bind 1, and draw what 9 draws of buffers of their own draw (0 reused, 9 bound). dynamic_multi_variable's moved-offset dispatches now reuse their predecessor's set (7 of 8) and still answer Metal's values from each dispatch's own offset. docs/API.md states the range. Verified: the translator suite, 3324 of 3324 (plain). On the M3 Max (MoltenVK 1.4.2), debug, --cfg m2v_gpu, under maclock and memcap: 96 of 96 runtime tests (fix 1's set plus set_zero_at_offsets, dynamic_multi_variable, uniform_bind_offsets, binding_view, range, rebind_descriptor_slip, rebind_behind_a_wait, depth_ranges, attributes), and 220 of 220 validation lanes under the validation layer (fix 1's set plus stage_in_regions, stage_in_strides, padded_loads, escaped_slots, absent_reads, chosen_pointers, dispatch_*, read_through_views, guarded_effects, index_fetches, first_vertex, vertex_strides, host_bytes, pointer_uploads, commands_recorded, runtime_lane::tests, among them renders::public_render_cases_match_metal and tests::stage_in_region_cases_match_metal). Negative control: planned_range forced to fall back fails set_zero_at_offsets ((0, 9) against (8, 1)) and both dynamic_multi_variable moved-offset tests ((0, 0) against (7, 0)). clippy plain and with --cfg m2v_gpu clean. Per draw on the encoding thread, release with thin LTO, 3 interleaved rounds against the parent build, medians: draws.10k 11201.7 -> 9212.4 instructions (-17.8%), 616-661 -> 485-495 ns WS-like 23121.1 -> 21752.5 instructions (-5.9%) One round's counts: draws.10k 0 -> 29880 sets reused, 30000 -> 120 vkCmdBindDescriptorSets, 6 -> 60000 vkCmdPushConstants (the residuals; both stages' writes are pushed where either changes); WS-like 0 -> 3744 sets found in the command buffer's cache, binds unchanged at 4000. (cherry picked from commit b875660ecbad7dd6f9dfa9f976ef1c2b32bded1e) (cherry picked from commit b09293e9c22d80e4ae4c505b00ba0e07e6a8165c) --- .../src/tests/dynamic_multi_variable.rs | 26 +-- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/set_zero_at_offsets.rs | 208 ++++++++++++++++++ crates/metal2vulkan/src/bind/graphics.rs | 22 +- crates/metal2vulkan/src/bind/instantiate.rs | 55 ++++- .../src/bind/instantiate/tests.rs | 127 +++++++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- docs/API.md | 9 + 8 files changed, 410 insertions(+), 41 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/set_zero_at_offsets.rs diff --git a/crates/metal2vulkan-runtime/src/tests/dynamic_multi_variable.rs b/crates/metal2vulkan-runtime/src/tests/dynamic_multi_variable.rs index 07418c1ae..2bdde0a9f 100644 --- a/crates/metal2vulkan-runtime/src/tests/dynamic_multi_variable.rs +++ b/crates/metal2vulkan-runtime/src/tests/dynamic_multi_variable.rs @@ -16,10 +16,9 @@ //! offsets move: where its three-variable binding is dynamic, the dynamic offset reaches every //! variable at it; //! - and the sets its dispatches take are the ones the variant's own choice calls for -//! (`ComputePipelineState::set_zero_choice`): where it pushes set 0 every dispatch pushes; where -//! each dispatch binds its buffers at the offsets its predecessor did, every dispatch after the -//! first binds its predecessor's set; and where the offsets move, none does, dynamic or not -//! ([`Ran::holds_the_choice`]); +//! (`ComputePipelineState::set_zero_choice`): where it pushes set 0 every dispatch pushes; else +//! every dispatch after the first binds its predecessor's set, its offsets moved or not, dynamic +//! or not ([`Ran::holds_the_choice`]); //! - and a self-check the driver refuses reaches the device's sink as at most one informational //! line, never as the driver's errors of the runtime's own question. //! @@ -390,14 +389,12 @@ impl Ran { /// binding the device would have taken. /// /// - Where its dispatches push set 0, all of them push and none allocates. - /// - Else, where every dispatch binds its buffers at its predecessor's offsets, it binds the - /// set its predecessor wrote, whatever its bindings' forms: the writes are the same. - /// - Else, the offsets moving, each dispatch allocates and writes its own, whatever its - /// bindings' forms: `record_stride_not_a_multiple_of_four` reads both its buffers by thread, - /// so each descriptor's range runs from its offset to the buffer's end - /// (`bind::instantiate::descriptor_range`'s whole window), and a moved offset changes a - /// static binding's offset and a dynamic one's range alike (`binding::LastSetZero` compares - /// the writes by value). + /// - Else every dispatch binds the set its predecessor wrote, whatever its bindings' forms, + /// its offsets moved or not: the writes are the same (`binding::LastSetZero` compares them + /// by value). `record_stride_not_a_multiple_of_four` reads both its buffers by thread + /// through storage views of their whole windows, so each descriptor's range runs from the + /// buffer's space start to its end at every bind offset, the offset in the slot's residual + /// push field (`metal2vulkan`'s `bind::instantiate::planned_range`). /// /// And the device's answer bounds the choice in the one direction it implies: a device that /// does not take a binding of several variables dynamically has none of them dynamic. @@ -441,10 +438,7 @@ impl Ran { "{what}: its variant pushes no set 0, yet {} of {dispatches} dispatches pushed one", self.pushed ); - let want = match self.moved { - false => dispatches as u64 - 1, - true => 0, - }; + let want = dispatches as u64 - 1; assert_eq!( (self.reused, self.found), (want, 0), diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index a0b812379..4a597fdc5 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -303,6 +303,8 @@ mod sampler_sets; mod scheduler; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod scheduler_wakes; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod set_zero_at_offsets; mod shader_cache; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod shader_cache_off_thread; diff --git a/crates/metal2vulkan-runtime/src/tests/set_zero_at_offsets.rs b/crates/metal2vulkan-runtime/src/tests/set_zero_at_offsets.rs new file mode 100644 index 000000000..0d35a951c --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/set_zero_at_offsets.rs @@ -0,0 +1,208 @@ +//! Draws that bind one buffer at other offsets, at `device` slots read through storage views of +//! their whole windows, bind the set 0 their encoder's first draw wrote +//! (`WorkCounts::set_zero_sets_reused`), and bind it once: each such slot's descriptor range runs +//! from the buffer's space start to its padded end whatever the bind offset, which its residual +//! push field holds (`metal2vulkan`'s `bind::instantiate::planned_range`). They draw what the same +//! draws draw from buffers of their own each, which write and bind a set each. +//! +//! Device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). The functions +//! are `colored_vertex` and `colored_fragment` of the owned fixture +//! `validation/fixtures/public/examples/runtime_examples.ll`. + +use super::blit_holds::{device, Scratch, WAIT}; +use super::encoder_holds::{bytes_of, pass, render_state, words_of}; +use crate::{ + BlitOption, Buffer, CommandBufferStatus, Device, Origin, RenderCommandEncoder, + RenderPipelineState, ResourceOptions, Size, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; + +/// The side of the target, and the columns of it the draws fill: one each. +const SIDE: u64 = 16; + +/// The draws of a run. +const DRAWS: u64 = 9; + +/// A draw's vertices: a rectangle of two triangles. +const VERTICES: u32 = 6; + +/// The bytes of a draw's positions (`float2` each) and of its colours (`float4` each). +const POSITION_BYTES: u64 = VERTICES as u64 * 8; +const COLOR_BYTES: u64 = VERTICES as u64 * 16; + +/// The colour of draw `at`, in `RGBA8Unorm` codes, each exact in `float`. +fn codes(at: u64) -> [u8; 4] { + let red = 16 * (at as u8 + 1); + [red, 128, 255 - red, 255] +} + +/// Draw `at`'s positions: the rectangle over column `at` of the target, top to bottom. +fn positions(at: u64) -> Vec { + let x = |column: u64| -1.0 + 2.0 * column as f32 / SIDE as f32; + let (left, right) = (x(at), x(at + 1)); + [ + [left, -1.0], + [right, -1.0], + [left, 1.0], + [left, 1.0], + [right, -1.0], + [right, 1.0], + ] + .concat() +} + +/// Draw `at`'s colours: its colour at each vertex. +fn colors(at: u64) -> Vec { + let color = codes(at).map(|code| f32::from(code) / 255.0); + color.repeat(VERTICES as usize) +} + +/// A shared buffer of `values`. +fn buffer_of(device: &Device, values: &[f32]) -> Buffer { + let bytes = bytes_of(values, f32::to_le_bytes); + device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap() +} + +/// What a run drew and counted: the target's words, its `set_zero_sets_reused`, and its +/// `vkCmdBindDescriptorSets` and `vkCmdDraw` calls. +struct Ran { + words: Vec, + reused: u64, + binds: u64, + draws: u64, +} + +/// Encode `encode` with `state` set in one pass into a new cleared `RGBA8Unorm` target, commit and +/// wait: what it drew, and what its encoder counted. +fn run( + device: &Device, + state: &RenderPipelineState, + encode: impl Fn(&mut RenderCommandEncoder), +) -> Ran { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + let target = device.new_texture(&descriptor).unwrap(); + let back = device + .new_buffer(SIDE * SIDE * 4, ResourceOptions::shared()) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let before = device.work_counts(); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + encoder.set_render_pipeline_state(state).unwrap(); + encode(&mut encoder); + encoder.end_encoding().unwrap(); + let after = device.work_counts(); + let grew = |count: fn(&WorkCounts) -> u64| count(&after) - count(&before); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &back, + 0, + SIDE * 4, + SIDE * SIDE * 4, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + Ran { + words: words_of(&back), + reused: grew(|counts| counts.set_zero_sets_reused), + binds: grew(|counts| counts.commands_recorded.cmd_bind_descriptor_sets), + draws: grew(|counts| counts.commands_recorded.cmd_draw), + } +} + +/// The draw of the rectangle at the bound offsets. +fn rectangle(encoder: &mut RenderCommandEncoder) { + let drawn = encoder.draw_primitives(PrimitiveType::Triangle, 0, VERTICES, 1, 0); + assert_eq!(drawn, Ok(())); +} + +#[test] +fn draws_that_move_only_a_device_buffer_s_offset_bind_one_set_zero() { + let scratch = Scratch::new("set-zero-at-offsets"); + let device = device(&scratch.0); + let state = render_state( + &device, + "examples/runtime_examples.ll", + "colored_vertex", + "colored_fragment", + ); + let (all_positions, all_colors): (Vec, Vec) = + (0..DRAWS).fold(Default::default(), |(mut p, mut c), at| { + p.extend(positions(at)); + c.extend(colors(at)); + (p, c) + }); + let shared = ( + buffer_of(&device, &all_positions), + buffer_of(&device, &all_colors), + ); + let own: Vec<(Buffer, Buffer)> = (0..DRAWS) + .map(|at| { + ( + buffer_of(&device, &positions(at)), + buffer_of(&device, &colors(at)), + ) + }) + .collect(); + // One buffer each for the positions and the colours, the draws' offsets set between them. + let at_offsets = run(&device, &state, |encoder| { + encoder.set_vertex_buffer(Some(&shared.0), 0, 0).unwrap(); + encoder.set_vertex_buffer(Some(&shared.1), 0, 1).unwrap(); + for at in 0..DRAWS { + if at > 0 { + encoder + .set_vertex_buffer_offset(POSITION_BYTES * at, 0) + .unwrap(); + encoder + .set_vertex_buffer_offset(COLOR_BYTES * at, 1) + .unwrap(); + } + rectangle(encoder); + } + }); + // Buffers of their own each, at offset 0. + let own_buffers = run(&device, &state, |encoder| { + for (positions, colors) in &own { + encoder.set_vertex_buffer(Some(positions), 0, 0).unwrap(); + encoder.set_vertex_buffer(Some(colors), 0, 1).unwrap(); + rectangle(encoder); + } + }); + let expected: Vec = (0..SIDE * SIDE) + .map(|texel| match texel % SIDE { + column if column < DRAWS => u32::from_le_bytes(codes(column)), + _ => 0, + }) + .collect(); + assert_eq!(at_offsets.words, expected, "the draws at offsets"); + assert_eq!( + own_buffers.words, expected, + "the draws of their own buffers" + ); + assert_eq!((at_offsets.draws, own_buffers.draws), (DRAWS, DRAWS)); + assert_eq!( + (at_offsets.reused, at_offsets.binds), + (DRAWS - 1, 1), + "the draws at offsets bind their first draw's set 0, once" + ); + assert_eq!( + (own_buffers.reused, own_buffers.binds), + (0, DRAWS), + "the draws of their own buffers write and bind a set 0 each" + ); +} diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 947b5564a..d9d3fb637 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -4756,19 +4756,17 @@ fn rebind_slots( if !changed(pb.slot) { continue; } - let (range, residual) = - descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range).map_err( - |e| match e { - RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { - slot: pb.slot, - needed, - limit: pb.max_range, - }, - RangeError::Empty => { - BindError::Unsupported(Unsupported::not_representable(Feature::BufferRange)) - } + let (range, residual) = crate::bind::instantiate::planned_range(pb, bind_offset, length) + .map_err(|e| match e { + RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { + slot: pb.slot, + needed, + limit: pb.max_range, }, - )?; + RangeError::Empty => { + BindError::Unsupported(Unsupported::not_representable(Feature::BufferRange)) + } + })?; let Some(written) = out .descriptor_ranges .get_mut(place) diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index 4feedd889..b39461880 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -12,7 +12,7 @@ use crate::error::{BindError, Feature, Unsupported}; use crate::memory::roots::{ BIND_OFFSET, ENTRY_BYTES, GUEST, HOST, RESIDENT_COUNT, RESIDENT_FIRST, SINK_ROOT, SIZE, }; -use crate::pipeline::interface::{BufferForm, PushLoc, Window}; +use crate::pipeline::interface::{BufferForm, DescriptorView, PushLoc, Window}; use crate::pipeline::sym::{PushField, SlotRef}; use crate::vk; @@ -492,6 +492,38 @@ pub(crate) fn descriptor_range( )) } +/// The descriptor range and the `SlotBindOffset` residual of planned buffer slot `pb` bound at +/// `bind_offset` of an allocation of `length` bytes: a storage view of a `Whole` window takes its +/// range from the start of the bound buffer's space (offset 0) to the padded end, its residual the +/// bind offset, so every bind offset of one buffer binds one descriptor and a draw or dispatch that +/// moves only the offset keeps its set 0 (a dynamic one's offset moves with the space alone). +/// Its function reads byte `residual + m` of the range for the Metal offset `m`, the byte it read +/// of the range from the bind offset; the bytes before the bind offset, which the window does not +/// state, are reachable as Metal's own memory is. Every other slot, and one whose range from 0 +/// would exceed the view's `max_range` or reach past `2^32` (a `u32` residual and offset), or whose +/// bind offset lies at or past the padded end, takes [`descriptor_range`]'s range. +pub(crate) fn planned_range( + pb: &PlannedBuffer, + bind_offset: u64, + length: u64, +) -> Result<(BufferRange, u32), RangeError> { + let end = padded(length); + let from_start = pb.window == Window::Whole + && pb.form == BufferForm::Descriptor(DescriptorView::Storage) + && bind_offset < end + && end <= pb.max_range + && end <= 1 << 32; + if !from_start { + return descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range); + } + // `bind_offset < end <= 2^32`: the residual is the bind offset. + let range = BufferRange { + offset: 0, + range: end, + }; + Ok((range, bind_offset as u32)) +} + /// The bound buffer at `slot` of `state`, checked against the plan's shape. pub(crate) fn bound_buffer( state: &BindState, @@ -637,17 +669,16 @@ pub(crate) fn bind_buffers( match (pb.form, pb.binding) { (BufferForm::Descriptor(_), Some((set, binding))) => { let (range, residual) = - descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range) - .map_err(|e| match e { - RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { - slot: pb.slot, - needed, - limit: pb.max_range, - }, - RangeError::Empty => BindError::Unsupported( - Unsupported::not_representable(Feature::BufferRange), - ), - })?; + planned_range(pb, bind_offset, length).map_err(|e| match e { + RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded { + slot: pb.slot, + needed, + limit: pb.max_range, + }, + RangeError::Empty => BindError::Unsupported( + Unsupported::not_representable(Feature::BufferRange), + ), + })?; descriptor_ranges.push(DescriptorRange { set, binding, diff --git a/crates/metal2vulkan/src/bind/instantiate/tests.rs b/crates/metal2vulkan/src/bind/instantiate/tests.rs index 5f2ec1a8e..aba5557ba 100644 --- a/crates/metal2vulkan/src/bind/instantiate/tests.rs +++ b/crates/metal2vulkan/src/bind/instantiate/tests.rs @@ -187,6 +187,133 @@ fn ranges_above_the_descriptor_limit_are_refused() { ); } +/// A planned buffer slot of `window`, read through `view`, under a view base alignment of +/// `alignment` and a range limit of `max_range`. +fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64) -> PlannedBuffer { + use crate::pipeline::sym::{SlotClass, Stage}; + PlannedBuffer { + slot: SlotRef { + stage: Stage::Vertex, + class: SlotClass::Buffer, + index: 0, + }, + window, + form: BufferForm::Descriptor(view), + access: crate::pipeline::interface::AccessSet::READ_WRITE, + binding: Some((0, 0)), + alignment, + max_range, + bound: BoundKind::Buffer { + device_address: false, + length_class: crate::bind::state::length_class(1 << 12), + }, + disjoint: false, + } +} + +/// A storage view of a whole buffer binds its space from 0 to the padded end at every bind offset +/// before the end, its residual the bind offset, so a draw that moves only the offset binds the +/// same descriptor; every byte from the bind offset to the end is at `residual + m`, inside the +/// range, as `descriptor_range` places it. +#[test] +fn a_storage_view_of_a_whole_buffer_binds_its_space_from_its_start() { + const LENGTH: u64 = 4096; + for alignment in [16, 64, 256] { + let pb = planned(Window::Whole, DescriptorView::Storage, alignment, MAX); + for bind_offset in (0..LENGTH).step_by(4).chain([1, 15, LENGTH - 1]) { + let what = format!("{alignment} {bind_offset}"); + let (range, residual) = + planned_range(&pb, bind_offset, LENGTH).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let whole = BufferRange { + offset: 0, + range: LENGTH, + }; + assert_eq!((range, u64::from(residual)), (whole, bind_offset), "{what}"); + // The byte `descriptor_range`'s range holds at `residual + m` for the Metal offset + // `m` is the same byte of the space here. + let (from_bind, at) = + descriptor_range(bind_offset, LENGTH, Window::Whole, alignment, MAX).unwrap(); + for m in [0, (LENGTH - bind_offset) / 2, LENGTH - bind_offset - 1] { + let byte = range.offset + u64::from(residual) + m; + assert!( + byte < range.offset + range.range, + "{what} {m}: inside the range" + ); + assert_eq!(byte, from_bind.offset + u64::from(at) + m, "{what} {m}"); + } + } + } + // A buffer of 2^32 bytes, bound at its last word: the residual still fits. + let pb = planned(Window::Whole, DescriptorView::Storage, 16, MAX); + let last = (1 << 32) - 4; + let (range, residual) = planned_range(&pb, last, 1 << 32).unwrap(); + assert_eq!( + (range.offset, range.range, residual), + (0, 1 << 32, u32::MAX - 3) + ); +} + +/// Every other slot takes `descriptor_range`'s range: a range from 0 past the view's limit or +/// past `2^32`, a bind offset at or past the padded end, a uniform view, a bounded window. A limit +/// the range from the bind offset meets binds; one it does not is refused as before. +#[test] +fn other_slots_bind_the_range_from_their_bind_offset() { + let same = |pb: &PlannedBuffer, bind_offset: u64, length: u64| { + assert_eq!( + planned_range(pb, bind_offset, length), + descriptor_range(bind_offset, length, pb.window, pb.alignment, pb.max_range), + "{:?} {:?} {bind_offset} {length}", + pb.window, + pb.form + ); + }; + let storage = |max_range| planned(Window::Whole, DescriptorView::Storage, 64, max_range); + // Past the view's limit: the tail from the bind offset fits; the whole buffer from 0 is + // refused as before, at the range from the bind offset. + let limited = storage(1 << 16); + let length = 1 << 20; + same(&limited, length - 4096, length); + assert!(planned_range(&limited, length - 4096, length).is_ok()); + same(&limited, 64, length); + assert_eq!( + planned_range(&limited, 64, length), + Err(RangeError::TooLarge { + needed: length - 64 + }) + ); + // At the limit exactly, from 0. + let (range, _) = planned_range(&storage(length), 64, length).unwrap(); + assert_eq!(range.offset, 0); + // Past 2^32 bytes: a residual and an offset of 32 bits could not state the bind offset. + for length in [(1 << 32) + 16, 1 << 33] { + for bind_offset in [0, 64, 1 << 31, (1 << 32) - 64, 1 << 32] { + same(&storage(MAX), bind_offset, length); + } + } + // At or past the padded end, where the range is widened down into the allocation. + for bind_offset in [4096, 4100, 8192, MAX] { + same(&storage(MAX), bind_offset, 4096); + same(&storage(MAX), bind_offset, 4090); + } + // A uniform view, whose `RangeAtBindOffset` reads a range from the bind offset; a bounded + // window of a storage view. + for bind_offset in (0..4096).step_by(4) { + for view in [DescriptorView::UniformWords, DescriptorView::UniformVec4] { + same(&planned(Window::Whole, view, 256, MAX), bind_offset, 4096); + } + for window in [ + Window::Bounded { start: 0, len: 64 }, + Window::Bounded { start: -8, len: 40 }, + ] { + same( + &planned(window, DescriptorView::Storage, 64, MAX), + bind_offset, + 4096, + ); + } + } +} + fn entry(host: u64, guest: u64, size: u64) -> RootEntry { RootEntry { host, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 20cabd916..8cad0f05a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1957; +pub const SEMANTICS_VERSION: u32 = 1958; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/docs/API.md b/docs/API.md index 74837e0b7..23993d7c3 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1053,6 +1053,15 @@ let draw = DrawCall::Primitives { let commands = plan.instantiate_draw(&state, &draw)?; ``` +A buffer slot read through a storage view of its whole window (a `device` pointer the function +indexes) takes the descriptor range from the start of the bound buffer's space to its end padded +to 16 bytes, whatever its bind offset, which its `SlotBindOffset` push field holds: draws and +dispatches that bind one buffer at other offsets write the same descriptors, and only push data +differs. Where that range would pass the view's `maxStorageBufferRange` or 4 GiB, or the offset +lies at or past the padded end, the range starts at the bind offset aligned down to the +descriptor base alignment, as every other descriptor-form slot's does. An access that reaches +back before the bind offset, inside the buffer, reads the buffer's bytes there, as Metal's does. + `instantiate_draw_into` writes the same commands over a `DrawCommands` you keep, in the storage its vectors already hold: keep one from draw to draw (`DrawCommands::default()` to start) and the draws allocate none of it again once it holds as much.