From fb2a637c05636bd6bd0eb7dd5fd76a6453595aeb Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 26 Oct 2026 02:10:49 +0200 Subject: [PATCH] diag: a dispatch encoded again binds a set an earlier command wrote The steps this packet landed as, in order: - Test that a dispatch encoded again writes its own descriptor set - Shut a command buffer's set-0 cache at its commit - Re-pin the runtime sources at the landing tip Content: the tree of `development` at ae026a6b69, unchanged. --- crates/metal2vulkan-runtime/src/binding.rs | 13 +- .../src/command_buffer/mod.rs | 10 + .../src/descriptor_arena.rs | 38 ++- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/rebind_descriptor_slip.rs | 260 ++++++++++++++++++ .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- 7 files changed, 316 insertions(+), 11 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/rebind_descriptor_slip.rs diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 53a6823f0..09b151eea 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -1178,10 +1178,15 @@ const SETS_ROOM: usize = 8; /// /// - **A set holds what was written.** Written once, as it is allocated; nothing writes it again. /// - **No handle it holds names another object.** A set is kept only once its command records, -/// so every object its writes name is held until the command buffer completes: by the command -/// (its buffers, textures, views and samplers), the command buffer's arena (uploads) or the -/// device (neutrals). No such object goes, nor can another take its handle, while its sets are -/// kept; a refused command's set is never kept. +/// and only while the command buffer holds what its commands took strongly, which is until it +/// is committed (`command_buffer/mod.rs`): every object a kept set's writes name is held by the +/// command (its buffers, textures, views and samplers), the command buffer's arena (uploads) or +/// the device (neutrals), so no such object goes, nor can another take its handle, while its +/// sets are kept. A refused command's set is never kept. At the commit the holds go weak, so a +/// rebind may let the pages go, and the cache is shut there and keeps and serves nothing again +/// (`DescriptorArena::shut`): every command recorded from the commit on -- an encoder encoded +/// again at a rebind (`command_buffer/reencode.rs`), a host step's -- allocates and writes its +/// own set. /// - **The writes compare by value** ([`SetWrite::same`], in order), behind a hash of them /// ([`set_key`]), so a set is bound again only where every descriptor written is the one the /// command writes. diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index a3e55bd3b..9343f67bc 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2691,6 +2691,16 @@ impl CommandBuffer { state.retained.push(Box::new(ticket)); } state.status = CommandBufferStatus::Committed; + // Its set-0 cache is shut here, before anything records again: from the commit on it + // holds what its commands took only weakly (below), so no handle a kept set holds is + // held against another object taking it -- which is the cache's own precondition + // (`binding::SetCache`). A rebind frees the import a kept set was written for and + // records the commands over the new one in the same call (`reencode.rs`), and the new + // import's `VkBuffer` may take the freed one's handle, all the cache compares; so + // every command recorded from here -- an encoder encoded again, a host step's -- + // allocates and writes its own set. The commands recorded before the commit keep the + // sets they bound. + state.descriptors.shut(); state.queued_commit = false; if let Some(hang) = state.hang.take() { match hangs { diff --git a/crates/metal2vulkan-runtime/src/descriptor_arena.rs b/crates/metal2vulkan-runtime/src/descriptor_arena.rs index a085985fc..6289f116a 100644 --- a/crates/metal2vulkan-runtime/src/descriptor_arena.rs +++ b/crates/metal2vulkan-runtime/src/descriptor_arena.rs @@ -178,6 +178,10 @@ pub(crate) struct DescriptorArena { /// (`binding::SetCache`), from its first command that looks one up: forgotten as the pools /// go. Boxed, so a fitted arena, which keeps none, stays small. sets: Option>, + /// Whether its command buffer is committed, from which point it keeps and serves no set of + /// its own ([`shut`](Self::shut)): the cache's exactness rests on a hold the commit lets go + /// of. + shut: bool, /// The arena of a predicated loop's check, lent while it records a run again /// (`command_buffer/rerun.rs`): every set is allocated from it, and kept there, meanwhile, /// and its pools are reset once that run completed ([`reset`](Self::reset)). @@ -194,6 +198,7 @@ impl DescriptorArena { device: None, fitted: true, sets: None, + shut: false, lent: None, } } @@ -262,13 +267,16 @@ impl DescriptorArena { /// The set 0 of `layout` holding `writes` that one of the command buffer's recorded commands /// wrote (`binding::SetCache::find`): of its own pools, or of the arena lent, which its own - /// outlive. + /// outlive. None of its own once it is [`shut`](Self::shut). pub(crate) fn find( &mut self, layout: vk::DescriptorSetLayout, writes: &[Write], ) -> Option { - let own = (self.sets.as_mut()).and_then(|sets| sets.find(layout, writes)); + let own = match self.shut { + true => None, + false => (self.sets.as_mut()).and_then(|sets| sets.find(layout, writes)), + }; match &self.lent { Some(lent) if own.is_none() => lock(lent).find(layout, writes), _ => own, @@ -277,18 +285,37 @@ impl DescriptorArena { /// Keep `set`, of `layout`, written with `writes`, once its command recorded /// (`binding::SetCache::keep`): in the arena lent where one is, whose pools it came from. + /// Kept in none of its own once it is [`shut`](Self::shut). pub(crate) fn keep( &mut self, layout: vk::DescriptorSetLayout, set: vk::DescriptorSet, writes: &[Write], ) { - match &self.lent { - Some(lent) => lock(lent).keep(layout, set, writes), - None => self.sets.get_or_insert_default().keep(layout, set, writes), + match (&self.lent, self.shut) { + (Some(lent), _) => lock(lent).keep(layout, set, writes), + (None, false) => self.sets.get_or_insert_default().keep(layout, set, writes), + (None, true) => {} } } + /// Forget the sets 0 its command buffer's commands wrote, and keep and serve none of its own + /// again: its command buffer is committed, so from here it holds what its commands took only + /// weakly (`command_buffer/mod.rs`) and the cache's second invariant -- no object a kept + /// set's handles name can go, nor another take its handle (`binding::SetCache`) -- no longer + /// holds. A rebind frees the import a kept set was written for and then records the commands + /// over the new one in the same call (`buffer_descriptor.rs`, `command_buffer/reencode.rs`), + /// and the new import's `VkBuffer` may take the freed one's handle, which with its offset and + /// range is all the cache compares; so every command recorded from the commit on -- an + /// encoder encoded again, a host step's -- allocates and writes its own set. Shut for good: + /// a command recorded again keeps no set either, or the next rebind would find that one + /// stale. Its pools are untouched; the sets already bound by commands recorded before the + /// commit stay theirs. + pub(crate) fn shut(&mut self) { + self.shut = true; + self.sets = None; + } + /// How many pools it holds (a device test's measure). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn pools(&self) -> usize { @@ -331,6 +358,7 @@ impl DescriptorArena { device: self.device.clone(), fitted: self.fitted, sets: None, + shut: self.shut, lent: None, } } diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 04158d637..d9752ce6f 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -198,6 +198,8 @@ mod reader_sizes; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_behind_a_wait; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod rebind_descriptor_slip; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_making_wait; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod recycle; diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_descriptor_slip.rs b/crates/metal2vulkan-runtime/src/tests/rebind_descriptor_slip.rs new file mode 100644 index 000000000..677aa15ae --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/rebind_descriptor_slip.rs @@ -0,0 +1,260 @@ +//! A dispatch encoded over a no-copy buffer's pages, its command buffer committed behind a +//! shared-event wait, the buffer detached and rebound before the host signals: the rebind encodes +//! the compute encoder again (`command_buffer/reencode.rs`), and this reads what the encoding +//! again recorded, not only what the submission then wrote. +//! +//! `rebind_behind_a_wait.rs` asserts the outcome of the sequence once per keep-alive leg. This +//! asserts the condition behind a wrong outcome instead, which holds far more often than the +//! wrong write shows: a dispatch encoded again must allocate and write its own set 0, never bind +//! one an earlier command of the same command buffer wrote (`binding::SetCache`, +//! `WorkCounts::set_zero_sets_found`). +//! +//! The cache is exact for commands recorded as the program encodes them: a kept set is kept only +//! once its command records, and the command then holds every object its descriptors name until +//! the command buffer completes, so no handle it holds can come to name another object. A command +//! buffer committed and not yet first submitted holds what its commands took only *weakly* +//! (`command_buffer/mod.rs`), exactly so that a rebind may let the pages go; the rebind frees the +//! import the kept set was written for and then encodes the encoder again +//! (`buffer_descriptor.rs`), inside one call. The new import's `VkBuffer` may take the freed +//! one's handle, and the cache compares and hashes a buffer descriptor by that handle with its +//! offset and range (`binding::SetWrite::same`, `binding::set_key`), so the dispatch encoded +//! again is handed the first encoding's set and reaches whatever that handle names now. +//! +//! The counts are read around the rebind alone, so nothing of the submission is in them. +//! +//! Device test: compiled only under the validation crate's GPU safety cfgs. The kernel is +//! `scale_and_offset` of the owned fixture +//! `validation/fixtures/public/examples/runtime_examples.ll`, as `dispatch_pending.rs` runs it. + +use super::blit_holds::{device, Scratch, WAIT}; +use super::dispatch_pending::state; +use crate::{ + Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, ComputePipelineState, Device, + Error, EventRef, HostMemory, KeepAlive, ResourceOptions, Size, +}; +use std::alloc::Layout; +use std::ptr::NonNull; + +/// The buffer's bytes: one page of any host, as the consumer's are. +const BYTES: usize = 16 << 10; + +/// The threads the dispatch runs, in one threadgroup, and the scale it multiplies by. +const COUNT: u64 = 64; +const SCALE: f32 = 2.0; + +/// The rounds it runs. The condition it asserts held in about half the rounds measured on an M3 +/// Max (105 of 200), so a few tens of rounds meet it or the tree does not have it; the wrong +/// write it leads to showed in about one round in two hundred, so no round count makes that one +/// a gate. +const ROUNDS: usize = 40; + +/// One page of host memory, zeroed, freed when dropped. +struct Page(NonNull); + +impl Page { + fn layout() -> Layout { + Layout::from_size_align(BYTES, BYTES).unwrap() + } + + fn new() -> Page { + // SAFETY: the layout's size is not zero. + let pointer = unsafe { std::alloc::alloc_zeroed(Page::layout()) }; + Page(NonNull::new(pointer).unwrap()) + } + + /// Whether the kernel wrote it: its words are zero until it does. + fn written(&self) -> bool { + // SAFETY: `BYTES` bytes, allocated in `new` aligned past a word, which no command writes + // any more (its command buffer completed). + let words = unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::(), BYTES / 4) }; + words.iter().any(|&word| word != 0) + } + + /// Its pages, for a no-copy buffer or a rebind. + /// + /// # Safety + /// + /// They outlive every buffer over them, which alone uses them while it lives. + unsafe fn memory(&self) -> HostMemory { + // SAFETY: the caller's contract; `BYTES` bytes, allocated in `new` page-aligned. + unsafe { HostMemory::new(self.0) } + } +} + +impl Drop for Page { + fn drop(&mut self) { + // SAFETY: allocated with this layout in `Page::new`. + unsafe { std::alloc::dealloc(self.0.as_ptr(), Page::layout()) }; + } +} + +/// The dispatch of `state` writing `output`, encoded into `command_buffer`. +fn dispatch( + command_buffer: &CommandBuffer, + state: &ComputePipelineState, + input: &Buffer, + output: &Buffer, + scale: &Buffer, +) { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(input), 0, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_buffer(Some(scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(COUNT, 1, 1), Size::new(COUNT, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); +} + +/// What one round saw. +#[derive(Debug, Default, PartialEq, Eq)] +struct Round { + /// The dispatch wrote the pages the buffer was made over, which it left at the first detach: + /// a backing two rebinds behind the submission, which no command of it named. + dummy: bool, + /// It wrote the pages it was encoded over, which the buffer left before the submission. + old: bool, + /// It wrote the pages the buffer lies in at the submission, which is the only right answer + /// for a command buffer that completed with no error. + new: bool, + status: Option, + error: Option, + /// Over the rebind alone: the encoders it encoded again, and the splices it refused. + reencoded: u64, + refused: u64, + /// Over the rebind alone: the sets 0 a command of the encoding again was handed from the + /// command buffer's cache instead of allocating and writing its own. The condition: the + /// cache's exactness rests on a hold the rebind let go of, so every one of these binds + /// descriptors written for an import that is freed. + found: u64, +} + +/// One round of the sequence on `device`: the pages are the caller's, so it reads all three +/// ranges back whatever the rebinds passed. `None` where the device imports no host memory. +fn round( + device: &Device, + state: &ComputePipelineState, + queue: &crate::CommandQueue, + pages: &[Page; 3], + (input, scale): (&Buffer, &Buffer), +) -> Option { + let keep = || Some(Box::new(()) as KeepAlive); + // SAFETY: each page outlives every buffer over it (the caller's, dropped after the device), + // and only the buffer's commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + let output = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("REBIND-DESCRIPTOR-SLIP: the device imports no host memory: {gap:?}"); + return None; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + assert_eq!(output.detach_backing(), Ok(true), "the first detach"); + // SAFETY: as above. + unsafe { output.rebind_bytes_no_copy(pages[1].memory(), None, keep()) }.unwrap(); + + // The dispatch is encoded over the second page, and cannot start: its command buffer waits + // for an event only the host signals. + let gate = device.new_shared_event().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + dispatch(&command_buffer, state, input, &output, scale); + command_buffer.commit().unwrap(); + + assert_eq!( + output.detach_backing(), + Ok(true), + "the detach of a buffer whose only use waits for an event" + ); + // Around the rebind alone, which encodes the encoder again in this call: nothing of the + // submission is in these. + let before = device.work_counts(); + // SAFETY: as above. + unsafe { output.rebind_bytes_no_copy(pages[2].memory(), None, keep()) }.unwrap(); + let after = device.work_counts(); + + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + Some(Round { + dummy: pages[0].written(), + old: pages[1].written(), + new: pages[2].written(), + status: Some(command_buffer.status()), + error: command_buffer.error(), + reencoded: after.encoders_reencoded - before.encoders_reencoded, + refused: after.reencodes_refused - before.reencodes_refused, + found: after.set_zero_sets_found - before.set_zero_sets_found, + }) +} + +/// The sequence [`ROUNDS`] times, each round over its own pages and its own buffer: no command of +/// an encoder encoded again binds a set 0 the command buffer kept, and no dispatch reaches other +/// pages than the buffer lies in at the submission. +#[test] +fn a_dispatch_encoded_again_binds_no_set_an_earlier_command_wrote() { + let scratch = Scratch::new("rebind-descriptor-slip"); + let device: Device = device(&scratch.0); + let state = state(&device); + let queue = device.new_command_queue().unwrap(); + let bytes: Vec = (0..COUNT).flat_map(|i| (i as f32).to_le_bytes()).collect(); + let input = device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap(); + let scale = device + .new_buffer_with_bytes(&SCALE.to_le_bytes(), ResourceOptions::shared()) + .unwrap(); + // Warm, over a buffer of the runtime's own, as the consumer's does. + let warm = device + .new_buffer(COUNT * 4, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + dispatch(&command_buffer, &state, &input, &warm, &scale); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + + let mut rounds = Vec::new(); + for at in 0..ROUNDS { + // Dropped at the round's end: every round takes its own pages, as the consumer's fresh + // process does. + let pages = [Page::new(), Page::new(), Page::new()]; + let Some(seen) = round(&device, &state, &queue, &pages, (&input, &scale)) else { + return; + }; + println!("rebind-descriptor-slip round {at}: {seen:?}"); + rounds.push(seen); + } + let found: u64 = rounds.iter().map(|round| round.found).sum(); + let wrong: Vec<&Round> = (rounds.iter()) + .filter(|round| round.dummy || round.old || !round.new) + .collect(); + println!( + "rebind-descriptor-slip: {found} sets 0 bound again at a rebind, {} rounds reached other \ + pages than the buffer lies in", + wrong.len(), + ); + // The condition. A tree that has it meets it in about half its rounds, so this reads zero or + // it does not, with no rate to weigh; a round that reaches the wrong pages is one of these + // whose handle came to name something else, and far rarer. + assert_eq!( + found, 0, + "a command of an encoder encoded again was handed {found} sets 0 the command buffer kept, \ + written for an import the rebind freed", + ); + assert!( + wrong.is_empty(), + "the dispatch reached other pages than the buffer lies in, in {} of {ROUNDS} rounds: \ + {wrong:?}", + wrong.len(), + ); +} diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 427788293..0406bb67a 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -2c78405628677524415e1b081e1fca2070f2a7be841c0d2048b75f54f0fe88a6 +63f1125d13968869a9fa988be48e6263d6e6a42506a996ebeba25f6657a66457 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9d4ebec30..d7994dfd7 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 450; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1632; +pub const RUNTIME_VERSION: u32 = 1638; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles