From 83b3b67f30cfe3220b7af700afd59da68c4ec954 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 07:24:16 -0800 Subject: [PATCH] RUNTIME 2457: Predicated loops: a rebind while a loop without work apart runs again is taken A predicated loop's check (Deferred::Loop) answered false in Deferred::resolved_at_its_calls, so the commit's steps_hold kept the pages of every buffer over host pages its command buffer used until it completed, and a rebind of one meanwhile was refused Invalid(Rebind(EncodedUses)) for as long as the loop ran on, which Metal does without bound. The check's host step reads only its unit's halt word, in the command buffer's upload arena. Each run again submits the laying's VkCommandBuffers again as they were encoded (Piece::Raw), the predicate word's VkBuffer or address and the body's sets taken at encoding, over the pages the laying's event group took at its first submission, which Submitting::submit keeps in State::retained until the command buffer completes; the batch the check holds keeps it from completing before the loop ends. Only the work the laying left apart is recorded again at each run: a host step's resolves the buffers its encoder named then, and work on the GPU alone records over the buffers as they lie then. So a loop's check is now resolved at its calls where its laying left no work apart (LoopCheck::leaves_work_apart). A rebind after the laying's submission is taken and every run again keeps the old pages, as Metal's loop reads the pages its submission found. A rebind before that submission is taken too, and the laying's encoders, which keep no log to be encoded again from, fail their submission EncodedUseRebound (announced), as every other compute encoder that predication reaches past does. A laying that left work apart keeps holding as before. The docs say so: deferred.rs, rerun.rs, rebind.rs (the module doc, RebindProblem::EncodedUses, Buffer::rebind_bytes_no_copy), the commit's steps_hold comment, the runtime README, and FAST-PATHS's two known gaps (the refusal now names a loop whose laying left work apart; the rebind between submissions names a loop's laying rebound before its submission). docs/REFUSALS.md does not move. The test is tests/rebind_loop_check.rs: a no-copy buffer holds a DoWhile's word and its body's input. A rebind while the loop runs again is taken, the loop runs again after it, ends on the old page's word alone, and its body wrote the old page's input; a rebind before the laying's submission fails the command buffer EncodedUseRebound, announced, its output unwritten. Verified: m3-max-36621 (msi, lavapipe, --cfg m2v_cpu_icd) at 30a7bfaa4e: rebind_loop_check 2/2 (running: rebind Ok, loop ends on the old page's word, old input; before submission: rebind Ok, EncodedUseRebound announced); rebind_*|pending_rebind|host_step_*|rerun_*|predicat* 29/29; control (development's Loop arm) fails both with Err(Invalid(Rebind(EncodedUses))); m3-max-36628 clippy --all-targets --all-features 0. clippy --cfg m2v_gpu / m2v_cpu_icd, rustdoc and the validation lanes run after the merge. --- crates/metal2vulkan-runtime/README.md | 5 +- .../src/command_buffer/mod.rs | 4 +- .../src/command_buffer/rerun.rs | 18 ++ crates/metal2vulkan-runtime/src/deferred.rs | 19 +- crates/metal2vulkan-runtime/src/rebind.rs | 18 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/rebind_loop_check.rs | 269 ++++++++++++++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- docs/FAST-PATHS.md | 31 +- 9 files changed, 344 insertions(+), 24 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 851c467ee..2af3476d5 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -480,8 +480,9 @@ after it, and 0 of 80 with the device dropped first keeping the objects, addresses and IDs. A rebind is refused (`RebindProblem::EncodedUses`) while a command buffer not yet committed, or an open encoder, used the bytes, or while one committed that used them, with commands the runtime records once earlier work completed (an indirect - command buffer's executions the GPU writes, a dispatch left to its host step), has not - completed; a render encoder whose attachment lies in them uses them from its open. Where a + command buffer's executions the GPU writes, a dispatch left to its host step, a predicated + loop's run again of such work or of work on the GPU alone), has not completed; a render + encoder whose attachment lies in them uses them from its open. Where a driver refuses the pointer (RADV refuses shared mappings, a `memfd`'s among them), memory made with `HostMemory::with_dma_buf` is imported from dma-bufs of its pages instead ([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)), and a no-copy buffer or heap diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index c419e3a44..6e602a7df 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -4610,7 +4610,9 @@ impl CommandBuffer { // for the pipelines its draws and tile dispatches record // (`render/pending_tile.rs`). Metal's replace fails for neither, and a rebind encodes // their encoder again instead (`command_buffer/reencode.rs`); where it cannot, their - // recording records nothing of the encoder (`DeferredPass::record_forms`). + // recording records nothing of the encoder (`DeferredPass::record_forms`). Nor does a + // predicated loop's check whose laying left no work apart, whose runs again submit the + // laying as encoded, over the pages its first submission took (`rerun.rs`). let steps_hold = (segments.iter().zip(&prepared)).any(|((work, _), prepared)| { !prepared.for_good && !work.resolved_at_its_calls(prepared.pipelines) }); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs index 3e5c43e53..c1b140e54 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs @@ -37,6 +37,17 @@ //! committed later on another queue that conflicts with the laying's uses waits behind it //! (`CommandBufferShared::footprint`), as behind any host step. The batch's other segments step //! once the check ends: they read what the laying leaves. +//! - **A rebind meanwhile** (`rebind.rs`). The check reads only the halt word, in the command +//! buffer's arena, and a laying that left no work apart is submitted again as it was encoded: +//! its command buffers name the pages of buffers over host pages that their first submission +//! took, which the command buffer holds until it completes, and the batch the check holds keeps +//! it from completing before the loop ends. So its commit holds none of those pages +//! (`Deferred::resolved_at_its_calls`): a rebind after that submission keeps the old pages for +//! every run again, as Metal's loop reads the pages its submission found, the loop's word +//! included; one before it fails that submission (`EncodedUseRebound`), its encoders keeping +//! no log to be encoded again from. Work apart is recorded again at each run, resolving the +//! buffers as they lie then, so a laying that left some holds every page its command buffer +//! used until it completes, and a rebind meanwhile is refused (`RebindProblem::EncodedUses`). //! - **Ends.** As Metal's GPU runs a loop without bound on after the program let go of every //! handle of its queue and its device, so does the thread, which holds the command buffer, and //! through it the queue and the device. It stops only at a lost device, the GPU's recovery @@ -204,6 +215,13 @@ impl LoopCheck { self.from } + /// Whether its laying left work apart, which each run again records again: a host step's + /// resolves the buffers its encoder named as it records, and work on the GPU alone records + /// over the buffers as they lie then (`Deferred::resolved_at_its_calls`). + pub(crate) fn leaves_work_apart(&self) -> bool { + (self.pieces.iter()).any(|piece| matches!(piece, Piece::Apart(_))) + } + /// At the commit, with its segments prepared: learn how each piece of work apart runs again /// from the segment it left among `parts`, the laying's parts and those after it. pub(crate) fn learn(&self, parts: &[Recorded]) { diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index fac9f5199..52c0dafec 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -834,10 +834,20 @@ impl Deferred { /// tiles of its texture alone, as its batch mapped them, and reads no buffer /// (`sparse::emulated::Scrub`): a rebind before the command buffer's submission encodes that /// encoder again, its CPU part, its copy in or its scrub with it, and one after it keeps the - /// old pages until the command buffer completes (`rebind.rs`). + /// old pages until the command buffer completes (`rebind.rs`). So does a predicated loop's + /// check whose laying left no work apart (`command_buffer/rerun.rs`): its step reads only its + /// unit's halt word, in the command buffer's arena, and each run again submits the laying's + /// command buffers again as they were encoded, over the pages their first submission took, + /// which the command buffer holds until it completes. A rebind after that submission keeps + /// the old pages for every run again, as Metal's loop reads the pages its submission found; + /// one before it fails that submission (`EncodedUseRebound`, + /// `command_buffer/first_submission.rs`), as the laying's encoders keep no log to be encoded + /// again from (`predication.rs`). /// Everything else its step resolves as it records (an execution, a dispatch left to its host - /// step, a loop's check): a rebind meanwhile is refused (`RebindProblem::EncodedUses`), a - /// known gap (`docs/FAST-PATHS.md`). + /// step, a loop's check whose laying left work apart, which each run again records again as + /// it records: a host step's work resolving the buffers its encoder named then, work on the + /// GPU alone over the buffers as they lie then): a rebind meanwhile is refused + /// (`RebindProblem::EncodedUses`), a known gap (`docs/FAST-PATHS.md`). pub(super) fn resolved_at_its_calls(&self, pipelines: bool) -> bool { match self { Deferred::Pending(_) @@ -849,7 +859,8 @@ impl Deferred { | Deferred::GatedCopyIn(_) | Deferred::SparseScrub(_) => true, Deferred::RenderPass(pass) => pipelines && !pass.executes(), - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::Loop(_) => false, + Deferred::Loop(check) => !check.leaves_work_apart(), + Deferred::Execute(_) | Deferred::Dispatch(_) => false, } } diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index e78a5ceec..a5f722387 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -37,11 +37,17 @@ //! resolves the buffers its encoder named as it records (`Deferred::resolved_at_its_calls`), //! counts as uncommitted until it completed: a rebind meanwhile is refused likewise //! (`EncodedUses`), where Metal's replace before the command buffer's submission reaches the new -//! pages, and one after it keeps the old pages until it completed. One committed with commands +//! pages, and one after it keeps the old pages until it completed. So does one whose predicated +//! loop's laying left such work, or work on the GPU alone, apart, which each run again of the +//! loop records again (`command_buffer/rerun.rs`). One committed with commands //! left for a `VkPipeline` still being made does not: a dispatch whose pipelines were being //! made (`pending_dispatch.rs`) and a render pass left for its draws' and tile dispatches' //! (`render/pending_tile.rs`) record what their calls resolved, so the rebind encodes their -//! encoder again as it does any other, and Metal's replace fails for neither. +//! encoder again as it does any other, and Metal's replace fails for neither. Nor does one +//! whose predicated loop's laying left no work apart, whose runs again submit the laying as +//! encoded: a rebind after its submission keeps the old pages for every run again, as Metal's +//! loop runs on over them, and one before it fails that submission (`EncodedUseRebound`), as +//! the laying's encoders cannot be encoded again. //! - **The new pages' import.** New memory that is the bytes a live no-copy buffer was made over, //! of its memory class, lies in that buffer's import, as a buffer made over them does //! (`host_aliases.rs`): the rebind imports nothing, pins no page and asks the kernel about no @@ -102,7 +108,8 @@ pub enum RebindProblem { /// a resource placed in it, or has an encoder open that used one (a render encoder uses its /// attachments' bytes from its open), or one committed whose commands the runtime records /// only once earlier work completed (an indirect command buffer's executions the GPU writes, - /// a dispatch left to its host step): commit or drop it first, or wait for its completion. + /// a dispatch left to its host step, a predicated loop's run again of such work or of work on + /// the GPU alone): commit or drop it first, or wait for its completion. EncodedUses, } @@ -1014,8 +1021,9 @@ impl Buffer { /// the buffer, or an open encoder that did (a render encoder with an attachment over it, from /// its open), or one committed whose commands used it that the runtime records once earlier /// work completed (an indirect command buffer's executions the GPU writes, a dispatch left to - /// its host step), until it completed (`Invalid`, [`RebindProblem::EncodedUses`]), where - /// Metal's replace before its submission reaches the new pages; new memory at another offset + /// its host step, a predicated loop's run again of such work or of work on the GPU alone), + /// until it completed (`Invalid`, [`RebindProblem::EncodedUses`]), where Metal's replace + /// before its submission reaches the new pages; new memory at another offset /// in its page than the old where a texture over the buffer lives and the buffer's GPU writes /// are dropped (`NotImplemented(RebindTextures)`), or where the device cannot make a texture's /// aliasing image again over the new memory or its copy (`NotImplemented(RebindTextures)`, diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 61b7cad1d..fdfc589da 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -671,6 +671,8 @@ 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_loop_check; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_making_wait; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_sparse_scrub; diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs b/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs new file mode 100644 index 000000000..dce6ece4e --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs @@ -0,0 +1,269 @@ +//! A predicated loop whose laying left no work apart, over a no-copy buffer that holds both the +//! loop's word and its body's input, and a rebind of that buffer. +//! +//! The loop's check (`command_buffer/rerun.rs`) reads only its unit's halt word, in the command +//! buffer's arena, and each run again submits the laying's command buffers again as they were +//! encoded, over the pages their first submission took, which the command buffer holds until it +//! completes: the commit holds none of the buffer's pages past it +//! (`Deferred::resolved_at_its_calls`). So a rebind while the loop runs again is taken, and the +//! loop goes on over the pages its submission found, as Metal's does (`rebind.rs`'s ordering +//! rule): its word ends it from those pages, and its body reads their input. A rebind before the +//! laying's submission is taken too, and that submission, whose encoders keep no log to be +//! encoded again from (`predication.rs`), runs nothing and fails `EncodedUseRebound`, announced +//! (`command_buffer/first_submission.rs`). +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. The kernel is `scale_and_offset` of the owned fixture +//! `validation/fixtures/public/examples/runtime_examples.ll` (`output[i] = input[i] * scale + i`), +//! as `dispatch_pending.rs` runs it, in one threadgroup. It prints `LOOP-REBIND` lines, and +//! returns where the device imports no host memory. A leg that fails leaves its pages allocated: +//! a loop that did not end may read them still. + +use super::blit_holds::{options, Scratch, WAIT}; +use super::dispatch_pending::state; +use super::rebind_behind_a_wait::{Page, BYTES, COUNT, SCALE}; +use crate::{ + Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, ComputePipelineState, + Degradation, Device, Error, EventRef, MessageSink, ResourceOptions, Size, +}; +use std::mem::ManuallyDrop; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// Where the loop's word lies in the buffer, and where its body's input begins. +const WORD_AT: u64 = 0; +const INPUT_AT: u64 = 256; + +/// The word's values: the loop runs again while it holds [`AGAIN`] (Metal's code 0, `==`). +const AGAIN: u32 = 0; +const STOP: u32 = 1; + +/// The first input word of the pages the buffer is rebound over; the first page's is 0. +const OTHER: f32 = 1000.0; + +/// The degradations the device announced, in order. +type Heard = Arc>>; + +/// The device the cfg selects, with a scratch shader cache, and what it announces. +fn device(scratch: &Scratch) -> (Device, Heard) { + let heard: Heard = Arc::default(); + let hearing = Arc::clone(&heard); + let mut options = options(&scratch.0); + options.messages = Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + hearing.lock().unwrap().push(notice.degradation); + } + })); + (Device::system_default_with(&options).unwrap(), heard) +} + +/// A page's bytes: the loop's `word` at [`WORD_AT`], and at [`INPUT_AT`] the input `first + i` +/// for each of the [`COUNT`] threads. +fn bytes(word: u32, first: f32) -> Vec { + let mut bytes = vec![0; INPUT_AT as usize]; + bytes[WORD_AT as usize..][..4].copy_from_slice(&word.to_le_bytes()); + bytes.extend((0..COUNT).flat_map(|i| (first + i as f32).to_le_bytes())); + bytes +} + +/// What the body writes from the input whose first word is `first`. +fn expected(first: f32) -> Vec { + (0..COUNT) + .map(|i| (first + i as f32) * SCALE + i as f32) + .collect() +} + +/// A no-copy buffer over `page`; `None`, printed, where the device imports no host memory. +fn no_copy(device: &Device, page: &Page) -> Option { + // SAFETY: the page outlives the buffer (dropped after the device, or never), and only the + // buffer's commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + page.memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + match made { + Ok(buffer) => Some(buffer), + Err(Error::Unsupported(gap)) => { + eprintln!("LOOP-REBIND: the device imports no such pages: {gap:?}"); + None + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + } +} + +/// The loop, encoded into `command_buffer`: a DoWhile over one dispatch of `state` that reads its +/// input from `over` at [`INPUT_AT`] and writes `output`, again while `over`'s word at +/// [`WORD_AT`] holds [`AGAIN`]. Its laying leaves no work apart: a direct dispatch, whose pipeline +/// is made. +fn encode_loop( + command_buffer: &CommandBuffer, + state: &ComputePipelineState, + over: &Buffer, + (output, scale): (&Buffer, &Buffer), +) { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(over), INPUT_AT, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_buffer(Some(scale), 0, 2).unwrap(); + encoder.encode_start_do_while().unwrap(); + encoder + .dispatch_threads(Size::new(COUNT, 1, 1), Size::new(COUNT, 1, 1)) + .unwrap(); + let end = encoder.encode_end_do_while(Some(over), WORD_AT, 0, AGAIN); + assert_eq!(end, Ok(true)); + encoder.end_encoding().unwrap(); +} + +/// The device's runs again of predicated loops once they reach `at_least`, or as they stand +/// [`WAIT`] after the call: the caller's assert names what it saw. +fn runs_reach(device: &Device, at_least: u64) -> u64 { + let deadline = Instant::now() + WAIT; + loop { + let runs = device.work_counts().predicated_loop_runs_again; + if runs >= at_least || Instant::now() >= deadline { + return runs; + } + std::thread::sleep(Duration::from_millis(1)); + } +} + +/// `buffer`'s first [`COUNT`] floats, read once no command buffer writes them. +fn floats(buffer: &Buffer) -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer holds `COUNT` floats, and no command buffer writes them now. + unsafe { std::slice::from_raw_parts(contents.as_ptr().cast::(), COUNT as usize) }.to_vec() +} + +/// A rebind of the buffer while the loop runs again is taken, and the loop goes on over the +/// pages its submission found: the runs again go on after the rebind, the loop ends once the +/// word in those pages says so (the pages the buffer lies in then keep saying again), and the +/// body wrote what their input gives, the command buffer completing with no error. +#[test] +fn a_rebind_while_a_loop_runs_again_is_taken_and_the_loop_keeps_its_pages() { + let pages = ManuallyDrop::new([Page::new(), Page::new()]); + let scratch = Scratch::new("loop-rebind-running"); + let (device, heard) = device(&scratch); + pages[0].write(&bytes(AGAIN, 0.0)); + pages[1].write(&bytes(AGAIN, OTHER)); + let Some(over) = no_copy(&device, &pages[0]) else { + return; + }; + let state = state(&device); + let shared = ResourceOptions::shared(); + let output = device.new_buffer(COUNT * 4, shared).unwrap(); + let scale = device + .new_buffer_with_bytes(&SCALE.to_le_bytes(), shared) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + encode_loop(&command_buffer, &state, &over, (&output, &scale)); + let before = device.work_counts().predicated_loop_runs_again; + command_buffer.commit().unwrap(); + let started = runs_reach(&device, before + 2); + let old = over.contents().unwrap(); + // SAFETY: the second page outlives the buffer, as the first does. + let rebound = unsafe { over.rebind_bytes_no_copy(pages[1].memory(), None, None) }; + let moved = over.contents() != Some(old); + let at_rebind = device.work_counts().predicated_loop_runs_again; + let after = runs_reach(&device, at_rebind + 2); + // SAFETY: the word of the first page, which the GPU only reads; aligned, as the page is. + unsafe { (old.as_ptr().add(WORD_AT as usize).cast::()).write_volatile(STOP) }; + let completed = command_buffer.wait_until_completed_for(WAIT); + let runs = device.work_counts().predicated_loop_runs_again - before; + println!( + "LOOP-REBIND running {}: rebind {rebound:?}; runs again {} before it, {} after, {runs} \ + in all; {completed:?} {:?} {:?}; heard {:?}", + device.name(), + at_rebind - before, + after - at_rebind, + command_buffer.status(), + command_buffer.error(), + heard.lock().unwrap(), + ); + assert!( + started >= before + 2, + "the loop ran again {} times within {WAIT:?}, not 2", + started - before + ); + assert_eq!(rebound, Ok(()), "the rebind while the loop runs again"); + assert!(moved, "the buffer's contents are the second page's"); + assert!( + after >= at_rebind + 2, + "the loop ran again {} times within {WAIT:?} after the rebind, not 2", + after - at_rebind + ); + assert!( + completed.is_ok(), + "the loop did not end within {WAIT:?} of its first page's word saying so ({runs} runs \ + again): it reads the pages the buffer lies in now" + ); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + assert_eq!(floats(&output), expected(0.0), "the first page's input"); + drop((command_buffer, queue, over, output, scale, state)); + drop(device); + drop(ManuallyDrop::into_inner(pages)); +} + +/// A rebind of the buffer before the laying's submission, the command buffer committed behind a +/// shared-event wait only the host signals, is taken: the laying's encoder cannot be encoded +/// again, so the submission runs nothing and the command buffer fails `EncodedUseRebound`, +/// announced, its output unwritten. Both pages' words stop the loop after its first pass, so a +/// laying that ran over either would have written the output and completed. +#[test] +fn a_rebind_before_a_loop_s_submission_fails_it_rebound() { + let pages = ManuallyDrop::new([Page::new(), Page::new()]); + let scratch = Scratch::new("loop-rebind-before"); + let (device, heard) = device(&scratch); + pages[0].write(&bytes(STOP, 0.0)); + pages[1].write(&bytes(STOP, OTHER)); + let Some(over) = no_copy(&device, &pages[0]) else { + return; + }; + let state = state(&device); + let shared = ResourceOptions::shared(); + let output = device.new_buffer(COUNT * 4, shared).unwrap(); + let scale = device + .new_buffer_with_bytes(&SCALE.to_le_bytes(), shared) + .unwrap(); + let gate = device.new_shared_event().unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&gate), 1)).unwrap(); + encode_loop(&command_buffer, &state, &over, (&output, &scale)); + command_buffer.commit().unwrap(); + // SAFETY: the second page outlives the buffer, as the first does. + let rebound = unsafe { over.rebind_bytes_no_copy(pages[1].memory(), None, None) }; + gate.set_signaled_value(1); + let completed = command_buffer.wait_until_completed_for(WAIT); + // The announcement, where the command buffer failed so. + let deadline = Instant::now() + WAIT; + let announced = + || (heard.lock().unwrap().iter()).any(|kind| *kind == Degradation::EncodedUseRebound); + let rebound_failure = Some(CommandBufferError::EncodedUseRebound); + while command_buffer.error() == rebound_failure && !announced() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + println!( + "LOOP-REBIND before {}: rebind {rebound:?}; {completed:?} {:?} {:?}; heard {:?}", + device.name(), + command_buffer.status(), + command_buffer.error(), + heard.lock().unwrap(), + ); + assert_eq!(rebound, Ok(()), "the rebind before the laying's submission"); + assert!(completed.is_ok(), "no completion within {WAIT:?}"); + assert_eq!(command_buffer.error(), rebound_failure); + assert!(announced(), "encoded-use-rebound announced within {WAIT:?}"); + assert_eq!(floats(&output), vec![0.0; COUNT as usize], "nothing ran"); + drop((command_buffer, queue, over, output, scale, state, gate)); + drop(device); + drop(ManuallyDrop::into_inner(pages)); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 43dc68f14..bbb7c4131 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// 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 = 2456; +pub const RUNTIME_VERSION: u32 = 2457; /// 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 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 1aaa60888..a5f4f4610 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -1409,18 +1409,24 @@ driver's. Each is open work. made before the check answered, stays live. 275 kept dma-buf imports of 512 KiB each cost 54-56 us per command buffer there (no other size measured). - **A rebind of a buffer over host pages is refused until a committed command buffer that used it - completes, where the command buffer holds a dispatch left to its host step** - (`Invalid`, `RebindProblem::EncodedUses`; `rebind.rs`). Such a dispatch is an indirect one off - the GPU's own path, or any while an indirect stage-in region is set (`indirect_dispatch.rs`); - so is an indirect command buffer's execution the GPU writes, where a host step records it. Its - host step reads its arguments once the work before it completed and resolves the buffers its - encoder named as it records (`Deferred::resolved_at_its_calls`), so the commit keeps the pages - of every buffer over host pages the command buffer used until it completes, and a rebind - meanwhile is not encoded again but refused. Metal's replace before the command buffer's - submission reaches the new pages, and one after it keeps the old pages until it completed. + completes, where the command buffer holds a dispatch left to its host step, or a predicated + loop whose laying left work apart** (`Invalid`, `RebindProblem::EncodedUses`; `rebind.rs`). + Such a dispatch is an indirect one off the GPU's own path, or any while an indirect stage-in + region is set (`indirect_dispatch.rs`); so is an indirect command buffer's execution the GPU + writes, where a host step records it. Its host step reads its arguments once the work before it + completed and resolves the buffers its encoder named as it records + (`Deferred::resolved_at_its_calls`); a loop's laying that left such work, or an execution on + the GPU alone, apart records it again at each run again of the loop, over the buffers as they + lie then (`command_buffer/rerun.rs`). So the commit keeps the pages of every buffer over host + pages the command buffer used until it completes, and a rebind meanwhile is not encoded again + but refused. Metal's replace before the command buffer's submission reaches the new pages, and + one after it keeps the old pages until it completed. A loop whose laying left no work apart + holds no page past the commit: a rebind after the laying's submission is taken, and every run + again keeps the old pages, as Metal's; one before it fails that submission (below). `host_step_reads.rs` checks the refusal for an indirect dispatch on a device without device addresses: the dispatch runs the arguments of the pages it was encoded over, and the rebind is - taken once the command buffer completed. + taken once the command buffer completed. `rebind_loop_check.rs` checks both rebinds of a loop + without work apart. - **A detach or rebind between a command buffer's submissions.** A command buffer's later submission, behind an event wait, reaches a no-copy buffer detached or rebound after its first submission through an address (made resident, or unnamed) through the pages its first @@ -1430,7 +1436,10 @@ driver's. Each is open work. where it is detached by then, as Metal's; those of an encoder that cannot be encoded again (a compute encoder its unit of command predication reaches past, which is one whose unit laid a step before it opened or one of its own that the unit's later encoders read, and one whose unit - laid a loop or left work out; work on the GPU alone) fail `EncodedUseRebound` (announced). + laid a loop or left work out; work on the GPU alone) fail `EncodedUseRebound` (announced). So + does a rebind before the submission of a predicated loop's laying that named the buffer, where + the rebind is taken (its laying left no work apart, above): the laying runs nothing and its + submission fails `EncodedUseRebound` (announced), where Metal's loop runs over the new pages. - **A failure inside a group of encoders recorded together, whose unit of command predication laid a loop or left work out, fails the whole group** (`encoder_fold.rs`, `command_buffer/fold.rs`'s `State::split_failure`). A `CommandBuffer::commit_failed` whose