From 2d0c57661db6da978c681e16ac27a6eef423e5f3 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 01:31:41 -0800 Subject: [PATCH] rt tests: two GPU hazards, memory read by address and heap textures read by index, released under the work that reads them What: two device tests under the GPU-hazard cfg (docs/VALIDATION.md: compiled on a GPU only under --cfg m2v_gpu_hazards, run always under m2v_cpu_icd), and the runtime's check-cfg list gains m2v_gpu_hazards. - argument_sampling: hs_sample's two textures placed in one Private heap at indices of their own, sampled through set 1 by the resource IDs its argument buffer holds, by a pass that names only the heap (use_heap). Their last handles drop right after the commit, in two forms: while the command buffer waits on an event (committed, not submitted), and while about 200 ms of work committed ahead of it on its queue runs. Each form records the device's loss, the command buffer's error and whether the pass read the textures as they were, then the test asserts all three. hs_sample's state and texel bytes move into helpers the first test shares; gpu_span's long-work helpers become crate-visible for it. - argument_tier: a 17 MiB Shared block, an allocation of its own, read only by address through a constant buffer (ab_address) by a command buffer that waits on an event first and names nothing of the block; the block's last handle drops right after the commit and the event is set past twice the idle age. Why: today a texture's release nulls its set-1 elements and destroys its views and image at once, and an idle allocation is freed after the idle age, whatever committed work still reads them. The tests show what that does on a device; the fix (one commit-order mark for every release) follows in the next commit, and the tests land with it, since a CPU device runs them always. Verified: cargo fmt at this commit. It is the base of one hazard archive build and one run of both tests on ms01's RTX 3090; the fix's commit names those jobs and what they showed. --- crates/metal2vulkan-runtime/Cargo.toml | 2 +- .../src/tests/argument_sampling.rs | 219 ++++++++++++++++-- .../src/tests/argument_tier.rs | 68 ++++++ .../src/tests/gpu_span.rs | 8 +- 4 files changed, 267 insertions(+), 30 deletions(-) diff --git a/crates/metal2vulkan-runtime/Cargo.toml b/crates/metal2vulkan-runtime/Cargo.toml index 4c60cf3f1..6ea65d5df 100644 --- a/crates/metal2vulkan-runtime/Cargo.toml +++ b/crates/metal2vulkan-runtime/Cargo.toml @@ -40,4 +40,4 @@ serde_json.workspace = true # The device tests compile only under the validation crate's device cfgs (docs/VALIDATION.md). [lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)"] } +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)", "cfg(m2v_gpu_hazards)"] } diff --git a/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs b/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs index cafe2291e..dc39b577d 100644 --- a/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs +++ b/crates/metal2vulkan-runtime/src/tests/argument_sampling.rs @@ -7,7 +7,9 @@ //! it, at texel edges, so a linear sampler's answer differs from the default sampler's. //! `engine/px_samplers`' `px_sample_argument` and `engine/xr_samples`' `xr_sample_runtime` sample //! one texture through one normalized sampler state held in an argument buffer and bound at a -//! sampler slot, which read the same texels. +//! sampler slot, which read the same texels. `hs_sample`'s textures placed in a heap and reached +//! through their indices by a pass that names only the heap are read as they were where their +//! last handles drop right after the commit (a GPU hazard). //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -15,10 +17,10 @@ mod on_device { use crate::tests::command::on_device::{each_device, finished}; use crate::{ - Block, Buffer, ComputePipelineDescriptor, Device, DispatchType, FunctionDescriptor, - IndexClass, Library, MemoryClass, NumberedSampler, PixelFormat, Region, Resource, - ResourceUsage, SamplerDescriptor, StageSource, Texture, TextureDescriptor, TextureType, - TextureUsage, + Block, Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DispatchType, + FunctionDescriptor, HeapRange, IndexClass, Library, MemoryClass, NumberedSampler, + PixelFormat, Region, Resource, ResourceUsage, SamplerDescriptor, StageSource, Texture, + TextureDescriptor, TextureType, TextureUsage, }; use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, AssembleError}; @@ -93,6 +95,36 @@ mod on_device { texture } + /// `hs_sample`'s state, its constexpr sampler numbered [`CONSTEXPR`]. + fn hs_sample(name: &str, device: &Device, library: &Library) -> ComputePipelineState { + let function = library.function("hs_sample").expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + (device.new_compute_pipeline_state(&descriptor, |samplers| { + assert!( + matches!(samplers, [NumberedSampler::Constexpr(_)]), + "{name}: {samplers:?}" + ); + Ok(vec![CONSTEXPR]) + })) + .unwrap_or_else(|error| panic!("{name}: hs_sample: {error}")) + } + + /// The bytes of `hs_sample`'s `half` texture and its `float` texture, row by row. + fn hs_bytes() -> (Vec, Vec) { + let texels = (SIDE * SIDE) as usize; + let halves = (0..texels) + .flat_map(|i| (0..4).map(move |c| HALVES[half_at(i, c)].1)) + .flat_map(u16::to_le_bytes) + .collect(); + let floats = (0..texels) + .flat_map(|i| (0..4).map(move |c| float_at(i, c))) + .flat_map(f32::to_le_bytes) + .collect(); + (halves, floats) + } + /// A Shared buffer of `bytes` at `offset` of `block`. fn shared(device: &Device, block: &Block, offset: u64, bytes: &[u8]) -> Buffer { let buffer = @@ -130,27 +162,9 @@ mod on_device { (device.grant_indices(class, first, 2)) .unwrap_or_else(|error| panic!("{name}: {error}")) }); - let function = library.function("hs_sample").expect("the kernel"); - let descriptor = ComputePipelineDescriptor::new(StageSource::Function( - FunctionDescriptor::new(function), - )); - let state = (device.new_compute_pipeline_state(&descriptor, |samplers| { - assert!( - matches!(samplers, [NumberedSampler::Constexpr(_)]), - "{name}: {samplers:?}" - ); - Ok(vec![CONSTEXPR]) - })) - .unwrap_or_else(|error| panic!("{name}: hs_sample: {error}")); + let state = hs_sample(name, &device, &library); let texels = (SIDE * SIDE) as usize; - let halves: Vec = (0..texels) - .flat_map(|i| (0..4).map(move |c| HALVES[half_at(i, c)].1)) - .flat_map(u16::to_le_bytes) - .collect(); - let floats: Vec = (0..texels) - .flat_map(|i| (0..4).map(move |c| float_at(i, c))) - .flat_map(f32::to_le_bytes) - .collect(); + let (halves, floats) = hs_bytes(); let h = texture( name, &device, @@ -212,6 +226,161 @@ mod on_device { }); } + /// A GPU hazard (`m2v_gpu_hazards`, docs/VALIDATION.md; a CPU device runs it always): a read + /// through set 1 of textures released under the work that reads them. `hs_sample`'s two + /// textures sit in one heap at indices of their own, and its pass names only the heap + /// (`use_heap`), reaching them through the resource IDs its argument buffer holds. Their last + /// handles drop right after the commit, in two forms: while the command buffer waits on an + /// event (committed, not submitted), and while long work committed ahead of it on its queue + /// runs. A texture's going waits for the command buffers committed before its release + /// (`crate::memory::Wait`): each completes with no error, and its pass reads the textures as + /// they were. + #[cfg(any(m2v_cpu_icd, all(m2v_gpu, m2v_gpu_hazards)))] + #[test] + fn every_device_keeps_heap_textures_read_through_their_indices_past_their_release() { + use crate::tests::command::on_device::shared_event; + use crate::tests::compute::on_device::step; + use crate::tests::gpu_span::on_device::{dispatches_for, long, words, WORDS}; + let Some(library) = library("examples/heap_samples.ll") else { + return; + }; + each_device("argument_sampling_released", |name, _, device| { + let _grants = [ + (IndexClass::Texture, 1, 4), + (IndexClass::Sampler, SLOT_SAMPLER, 2), + ] + .map(|(class, first, count)| { + (device.grant_indices(class, first, count)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }); + let state = hs_sample(name, &device, &library); + let texels = (SIDE * SIDE) as usize; + let (halves, floats) = hs_bytes(); + let want: Vec<[f32; 4]> = (0..texels) + .flat_map(|i| { + let half = [0, 1, 2, 3].map(|c| HALVES[half_at(i, c)].0); + let float = [0, 1, 2, 3].map(|c| float_at(i, c)); + [half, float, half, float] + }) + .collect(); + let sampler = (device.new_sampler_state(&SamplerDescriptor::new(), SLOT_SAMPLER)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let len = MemoryClass::Private.block_len(); + let heap_block = (device.take_block(MemoryClass::Private, len)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let heap = HeapRange { + block: heap_block.id, + offset: 0, + len, + }; + let descriptor = |format| { + let mut d = TextureDescriptor::new(TextureType::Type2D, format, SIDE, SIDE); + d.usage = TextureUsage::SHADER_READ; + d + }; + let formats = [ + (PixelFormat::RGBA16Float, 8), + (PixelFormat::RGBA32Float, 16), + ]; + let fits = formats.map(|(format, _)| { + (device.heap_texture_size_and_align(&descriptor(format))) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }); + let align = fits.iter().map(|fit| fit.align).max().unwrap_or(1); + let stride = + (fits.iter().map(|fit| fit.size).max().unwrap_or(0)).next_multiple_of(align); + // The texture of `format` (`texel` bytes a texel) at place `at` of the heap and texture + // index `index`, its bytes `bytes`. + let place = |at: u64, (format, texel): (PixelFormat, u64), index: u32, bytes: &[u8]| { + let texture = + (device.new_heap_texture(&descriptor(format), Some(index), heap, at * stride)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let whole = Region { + origin: [0; 3], + size: [SIDE, SIDE, 1], + }; + let row = u64::from(SIDE) * texel; + (texture.replace_region( + whole, + 0, + 0, + crate::HostBytes::from(bytes), + row, + row * u64::from(SIDE), + )) + .unwrap_or_else(|error| panic!("{name}: {error}")); + texture + }; + let block = (device.take_block(MemoryClass::Shared, 65_536)).expect("a Shared block"); + let ahead_state = step(&device); + let busy = words(&device); + let queue = device.new_command_queue(4).expect("a queue"); + let count = dispatches_for(name, &queue, &ahead_state, &busy, 200_000_000); + let event = shared_event(&device); + let mut unlike = Vec::new(); + for (round, form) in ["at an event wait", "behind long work"] + .into_iter() + .enumerate() + { + let first = 1 + 2 * round as u32; + let at = 2 * round as u64; + let h = place(at, formats[0], first, &halves); + let f = place(at + 1, formats[1], first + 1, &floats); + let ids: Vec = [&h, &f] + .iter() + .flat_map(|t| t.gpu_resource_id().to_bits().to_le_bytes()) + .collect(); + let held = shared(&device, &block, 512 * at, &ids); + let out = shared(&device, &block, 512 * at + 256, &[0; 16 * 16]); + let ahead = (round == 1).then(|| long(&queue, &ahead_state, &busy, count, WORDS)); + let command_buffer = queue.command_buffer().expect("a command buffer"); + if ahead.is_none() { + (command_buffer.encode_wait_for_event(event.as_event(), 1)).expect("a wait"); + } + 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(&held), 0, 0).expect("held"); + encoder.set_buffer(Some(&out), 0, 1).expect("out"); + (encoder.set_sampler_state(Some(&sampler), 0)).expect("the sampler"); + (encoder.use_heap(heap.block)).expect("the heap"); + (encoder.dispatch_threadgroups([1, 1, 1], [SIDE, SIDE, 1])) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + if let Some(ahead) = &ahead { + ahead.commit().expect("a commit"); + } + command_buffer.commit().expect("a commit"); + drop((h, f)); + println!( + "{name}: the textures at indices {first} and {} released {form}", + first + 1 + ); + if ahead.is_none() { + std::thread::sleep(std::time::Duration::from_millis(50)); + event.set_signaled_value(1); + } + for command_buffer in ahead.iter().chain([&command_buffer]) { + finished(name, command_buffer); + } + let (loss, error) = (device.loss(), command_buffer.error()); + let read = float4s(&out, 4 * texels); + println!("{name}: {form}: loss {loss:?}, error {error:?}, read {read:?}"); + if loss.is_some() || error.is_some() || read != want { + unlike.push(form); + } + if loss.is_some() { + break; + } + } + assert!( + unlike.is_empty(), + "{name}: the textures were not read as they were {unlike:?}" + ); + println!("{name}: released heap textures read as they were through their indices"); + }); + } + /// Each thread `i = 4c + s` of `engine/sampler_table`'s `sampler_table_held` samples row 0 of /// the 4 by 1 texture its argument buffer holds (red, green, blue, white) at `x = xs[i]` /// through `samplers[which[i]]`, a program-scope table of four constexpr nearest samplers diff --git a/crates/metal2vulkan-runtime/src/tests/argument_tier.rs b/crates/metal2vulkan-runtime/src/tests/argument_tier.rs index e519e808c..4bbe0e46d 100644 --- a/crates/metal2vulkan-runtime/src/tests/argument_tier.rs +++ b/crates/metal2vulkan-runtime/src/tests/argument_tier.rs @@ -468,6 +468,74 @@ mod on_device { }); } + /// A GPU hazard (`m2v_gpu_hazards`, docs/VALIDATION.md; a CPU device runs it always): a read + /// of freed memory where the runtime frees an idle allocation under work in flight. A Shared + /// buffer of 17 MiB, in an allocation of its own, is read only by address, through a constant + /// buffer whose bytes the CPU wrote (`ab_address`), by a command buffer that waits on an event + /// first and names nothing of it. Its block's last handle drops right after the commit, and + /// the event is set past twice the idle age. The allocation's free waits for that command + /// buffer (`crate::memory::Wait`): it completes with no error, and the read sees the bytes the + /// buffer held. + #[cfg(any(m2v_cpu_icd, all(m2v_gpu, m2v_gpu_hazards)))] + #[test] + fn every_device_keeps_memory_read_by_address_alone_past_its_release_until_the_read_retires() { + use crate::tests::command::on_device::shared_event; + const LEN: u64 = 17 << 20; + let Some(library) = library("ab_pointers") else { + return; + }; + each_device("argument_tier_idle_free", |name, _, device| { + let read = state(name, &device, &library, "ab_address"); + let block = (device.take_block(MemoryClass::Shared, LEN)).expect("a block of its own"); + let far = (device.new_buffer(block.id, 0, LEN, Some(0))).expect("its buffer"); + let bytes = u32_bytes((0..THREADS + 2).map(|k| 0xA000_0000 | k)); + let contents = far.contents().expect("a Shared buffer"); + // SAFETY: the range lies in the buffer, which is alive, and no GPU work uses it. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) + }; + let start = far.gpu_address(); + let mut shared = Shared::new(&device); + let held = shared.of(&device, &(start + 8).to_le_bytes()); + let out = shared.of(&device, &u32_bytes((0..THREADS).map(|_| 0))); + let event = shared_event(&device); + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + (command_buffer.encode_wait_for_event(event.as_event(), 1)).expect("a wait"); + let mut encoder = + (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + encoder.set_compute_pipeline_state(&read).expect("a state"); + encoder.set_buffer(Some(&held), 0, 0).expect("held"); + encoder.set_buffer(Some(&out), 0, 1).expect("out"); + (encoder.dispatch_threadgroups([2, 1, 1], [THREADS / 2, 1, 1])) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + drop((far, block)); + println!( + "{name}: the buffer at {start:#x}..{:#x} released", + start + LEN + ); + std::thread::sleep(std::time::Duration::from_nanos( + 2 * crate::memory::IDLE_AGE_NANOS, + )); + event.set_signaled_value(1); + finished(name, &command_buffer); + assert_eq!(device.loss(), None, "{name}: the device"); + assert_eq!( + command_buffer.error(), + None, + "{name}: the reading command buffer" + ); + let want: Vec = (0..THREADS).map(|i| 0xA000_0000 | (2 + i)).collect(); + assert_eq!( + words::(&out, THREADS as usize), + want, + "{name}: the bytes it held" + ); + }); + } + /// A slot pointer converted to an integer: thread `i` stores the address of element `i` of /// buffer 0, bound 16 bytes past its buffer's start, and increments the element through the /// same pointer (`ab_slot_address`). The address is the buffer's `gpuAddress` plus 16 plus diff --git a/crates/metal2vulkan-runtime/src/tests/gpu_span.rs b/crates/metal2vulkan-runtime/src/tests/gpu_span.rs index c855dc488..97fe4fdf6 100644 --- a/crates/metal2vulkan-runtime/src/tests/gpu_span.rs +++ b/crates/metal2vulkan-runtime/src/tests/gpu_span.rs @@ -15,7 +15,7 @@ pub(crate) mod on_device { use std::time::Instant; /// The words of a long command buffer's buffer, each dispatch's grid: 64 MiB. - const WORDS: u32 = 1 << 24; + pub(crate) const WORDS: u32 = 1 << 24; /// The most dispatches a long command buffer holds, on the fastest device. const MOST: u64 = 20_000; @@ -29,7 +29,7 @@ pub(crate) mod on_device { const NAMED: u64 = 256 << 20; /// A Private buffer of [`WORDS`] words. - fn words(device: &Device) -> Buffer { + pub(crate) fn words(device: &Device) -> Buffer { let length = u64::from(WORDS) * 4; let block = (device.take_block(MemoryClass::Private, length)).expect("a Private block"); (device.new_buffer(block.id, 0, length, None)).expect("a buffer") @@ -37,7 +37,7 @@ pub(crate) mod on_device { /// A command buffer of `queue` of `count` dispatches of `state` over `buffer`, `threads` each /// ([`WORDS`] for a long one), in one serial encoder, so each waits for the one before it. - fn long( + pub(crate) fn long( queue: &CommandQueue, state: &ComputePipelineState, buffer: &Buffer, @@ -62,7 +62,7 @@ pub(crate) mod on_device { /// times cannot size it: Vulkan lets a timestamp be written at any stage logically later than /// the one named). A first command buffer of one dispatch runs before it, so nothing a first /// use waits for is timed. - fn dispatches_for( + pub(crate) fn dispatches_for( name: &str, queue: &CommandQueue, state: &ComputePipelineState,