From 3a3d31c3747f06a186411e8db4eaea2cdba846a8 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 11:23:09 -0800 Subject: [PATCH] RUNTIME 2470: Rebinds: a rebind before the submission of an encoder no rebind encodes again is refused A rebind between a command buffer's commit and the submission of its last event group, of a buffer an encoder of it named that keeps no log (a compute encoder its unit of command predication reaches past, a loop's laying, a render encoder opened while no buffer over host pages existed), failed that submission EncodedUseRebound: the commit let go of its holds, and nothing encodes the encoder again. The consumer's answer table ends the VM on that kind. Now the rebind is refused instead (EncodedUses), and the command buffer runs over the pages it was encoded over. - State::keep_replays also answers whether an encoder that keeps no log (not one its commit fails, which runs nothing) named a buffer over host pages, by its own commands or by work it left for later not recorded on the GPU alone (State::unlogged_names_a_pin). - Where so, the commit keeps the command buffer's holds (State::held_to_submission) instead of letting them go: Holds::hold_to_submission moves each from Entry::pending to a new Entry::unsubmitted under one lock of `buffers`, so no rebind falls between. They go as the last event group's first batch is submitted (State::first_submission, State::later_group), or at completion; a rebind after that keeps the old pages for the submitted work, as before. - replace and the rebind's first check refuse while `unsubmitted > 0`, counted as their own reason: WorkCounts::rebinds_refused_unsubmitted. - Cost: nothing new for a command buffer whose encoders a rebind encodes again (one pass over its ended encoders' flags at the commit, inside keep_replays). A host-step command buffer keeps holding to completion (steps_hold), unchanged. Deadlock audit, by lock: - Commit: hold_to_submission takes `buffers` under the command buffer's `state` lock: state -> buffers, the order encode_moved's Submitting and the commit's own clear of its holds already take. - Submission: the holds go under the scheduler's lock and `state`, after the `Submitting` guard (`buffers`) was dropped; each Holds' drop takes `buffers` alone: scheduler -> state -> buffers, the order the submission's judging already takes. Never under `buffers` itself. - Completion: moved out of `state` and dropped after its lock, with the submitted holds. - Nothing waits on them: a rebind finds `unsubmitted` and is refused; no wait is added anywhere, so no cycle can form. Tests (lavapipe): rebind_races gains a control (the predicated family committed behind an unsignaled shared-event wait, rebound before the signal: refused, completes over the old page, refused-unsubmitted 1), and the threaded run asserts no command buffer fails EncodedUseRebound. Tests that asserted the old outcome of such a rebind now assert the refusal and a completion over the old pages: pending_rebind, rebind_loop_check's rebind before the laying's submission, tile_rebind_making_wait's unlogged tile pass, and validation's rebind_reach test of a unit's encoder that laid its first step. The validation lane no longer has a test that announces encoded-use-rebound (degrade_notices says so). Docs: rebind.rs module docs (ordering rule, a predicated loop's laying), Buffer::rebind_bytes_no_copy, RebindProblem::EncodedUses, the encoded-use-rebound catalogue entry and its declaration, runtime README; api_signatures blessed. Follow-ups in the same landing: Rebinds: a state's reset takes held_to_submission fresh too; Rebinds: clippy (append, take) in the hold-to-submission moves. Checks (lane rebindsafe2): clippy plain (runtime, validation) 0 at 5bfab2beaa in m3-max-37364; lavapipe runtime tests 356/356 at a0fc57f283 (m3-max-37354: rebind, detach, host_page, host_step, indirect, predication, pending, holds, encoder_fold, deferred_calls), the new control refused with refused-unsubmitted 1 and the threaded run asserting 0 EncodedUseRebound. Validation lavapipe (m3-max-37365), rustdoc and the cfg clippy runs follow on development. --- crates/metal2vulkan-runtime/README.md | 5 +- .../src/buffer_descriptor.rs | 15 ++- .../src/command_buffer/first_submission.rs | 8 ++ .../src/command_buffer/mod.rs | 24 ++++ .../src/command_buffer/reencode.rs | 24 ++++ .../metal2vulkan-runtime/src/degradation.rs | 4 +- crates/metal2vulkan-runtime/src/rebind.rs | 104 ++++++++++++++---- .../src/tests/pending_rebind.rs | 63 +++++++---- .../src/tests/rebind_loop_check.rs | 43 ++++---- .../src/tests/rebind_races.rs | 88 ++++++++++++++- .../src/tests/tile_rebind_making_wait.rs | 63 ++++++----- .../metal2vulkan-runtime/src/work_counts.rs | 15 +++ .../src/runtime_lane/degrade_notices.rs | 5 +- .../src/runtime_lane/rebind_reach.rs | 88 +++++++-------- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 6 +- 17 files changed, 397 insertions(+), 161 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 146911a29..8fc611fb8 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -482,7 +482,10 @@ after it, and 0 of 80 with the device dropped first 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, 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. Other threads may encode and + encoder whose attachment lies in them uses them from its open. So is one while a command buffer + committed and not yet submitted used them in an encoder the runtime cannot encode again (a + compute encoder its unit of command predication reaches past, among others), until its last + submission (`WorkCounts::rebinds_refused_unsubmitted`). Other threads may encode and commit command buffers that use the bytes during a rebind: a blit encoder, or a render encoder that keeps a log, whose call raced it is encoded again over the new pages before its first submission (`WorkCounts::encoders_raced_rebind` counts the encoders that raced). The calls of the diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index f4f65d8b5..887f07df1 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -1246,7 +1246,10 @@ impl Device { self.shared().deferred.lower_all(); let key = buffer.identity().key; let encoded = || invalid(call, Problem::Rebind(RebindProblem::EncodedUses)); - if self.rebind_pending(key) { + if let Some(refused) = self.rebind_pending(key) { + if let crate::rebind::Unreplaced::Unsubmitted = refused { + self.shared().counts.rebind_refused_unsubmitted(); + } return Err(encoded()); } let shared = self.shared(); @@ -1697,8 +1700,14 @@ impl Device { .rebinds .replace(key, cell, Arc::clone(&pages)) .map_err(|refused| { - if let crate::rebind::Unreplaced::Calls = refused { - shared.counts.rebind_refused_calls_in_flight(); + match refused { + crate::rebind::Unreplaced::Calls => { + shared.counts.rebind_refused_calls_in_flight(); + } + crate::rebind::Unreplaced::Unsubmitted => { + shared.counts.rebind_refused_unsubmitted(); + } + crate::rebind::Unreplaced::Held => {} } encoded() })?; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index 3c36234df..6cd628d81 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -370,6 +370,10 @@ impl State { if !holds.is_empty() { self.submitted_holds.push((group.end - 1, holds)); } + // Its last group is submitted: a rebind from here keeps the old pages for it. + if group.end == self.batches.all().len() { + self.held_to_submission.clear(); + } // The list changed since the commit: what it listed is listed again, a rebind having // ended its use, and its resident set made of the list as it stands. let changed = self @@ -477,6 +481,10 @@ impl State { &mut holds, ); } + // Its last group is submitted: a rebind from here keeps the old pages for it. + if group.end == self.batches.all().len() { + self.held_to_submission.clear(); + } self.judged(&encoders, parts); let failing = self.failing_submissions(&verdicts); self.failing.extend(failing); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 6199d10d4..c6c5fee87 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -1077,6 +1077,11 @@ pub(super) struct State { /// (`rebind.rs`): let go at its commit, or, where a host step records commands after it, as /// it completes. pub(super) holds: Vec, + /// Those holds from its commit until the submission of its last event group (or its + /// completion), where an encoder no rebind encodes again named a buffer over host pages + /// (`State::unlogged_names_a_pin`): a rebind meanwhile is refused (`EncodedUses`), never + /// failing that submission (`Holds::hold_to_submission`). + pub(super) held_to_submission: Vec, /// What its ended encoders made resident, every encoder's joined (`residency.rs`): the /// residency the work its commit and host steps record resolves and binds against. Released /// with what it retained, as it completes. Its heaps are joined as each encoder ends, and the @@ -1335,6 +1340,7 @@ impl State { times: Times::default(), used_heaps: Vec::new(), holds: Vec::new(), + held_to_submission: Vec::new(), residency: None, joined: 0, inherits: [None, None], @@ -1482,6 +1488,7 @@ impl State { times, used_heaps, holds, + held_to_submission, residency, joined, inherits, @@ -1610,6 +1617,7 @@ impl State { self.times = times; self.used_heaps = used_heaps; self.holds = holds; + self.held_to_submission = held_to_submission; self.residency = residency; self.joined = joined; self.inherits = inherits; @@ -4785,6 +4793,7 @@ impl CommandBuffer { .rebinds .wait_for_replay(&self.0, kept.keys, kept.maps); } + let to_submission = kept.to_submission; let unreplayable = kept.gone; let reset = state.rate_maps_reset(); if reset.0 { @@ -4827,6 +4836,10 @@ impl CommandBuffer { // Committed, its commands recorded for good: a rebind of what they used takes // effect after them (`rebind.rs`); one a host step records holds until completion // (`steps_hold`). + // One whose encoder no rebind encodes again named a buffer over host pages holds + // until its last event group is submitted (`held_to_submission`), so a rebind + // meanwhile is refused rather than failing that submission. Nothing for one whose + // encoders a rebind encodes again. if steps_hold { let held = &mut *state; let kept = held @@ -4834,6 +4847,12 @@ impl CommandBuffer { .drain(..) .map(|holds| Box::new(holds) as Box); held.retained.extend(kept); + } else if to_submission { + let held = &mut *state; + for holds in &mut held.holds { + holds.hold_to_submission(); + } + held.held_to_submission.append(&mut held.holds); } else { state.holds.clear(); } @@ -6985,6 +7004,8 @@ impl CommandBufferShared { // The holds its batches' commands took of buffers over host pages, let go of here, before // its completed handlers run: dropped without the state's lock (`detach.rs`). let submitted_holds; + // The holds kept for a group never submitted (`held_to_submission`), dropped with them. + let held_to_submission: Vec; // Its sync file's semaphore, given back once its work ended (`sync_file.rs`). #[cfg(unix)] let sync_file; @@ -7179,6 +7200,8 @@ impl CommandBufferShared { // for its work answers `false`; one made from here on detaches. Dropped below, // without this lock, which no hold may be let go under (`Rebinds::wait_ran`). submitted_holds = state.holds_until(usize::MAX); + // A group never submitted runs nothing: no rebind fails it from here. + held_to_submission = std::mem::take(&mut state.held_to_submission); // Its work ended (its fences were signaled, or its queues drained after a failed // wait), so nothing of its pools is pending: its command pool goes to the device's // spares whatever its status, never released on this thread (`spares.rs`); its @@ -7215,6 +7238,7 @@ impl CommandBufferShared { // The holds taken above go here, with no lock of the command buffer's held, before any // handler of its runs: a detach from one of them detaches (`detach.rs`). drop(submitted_holds); + drop(held_to_submission); #[cfg(unix)] self.release_sync_file(sync_file); self.wake_parked(parked); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index ac86ecfef..373f7fec7 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -869,13 +869,34 @@ impl State { keys.dedup(); maps.sort_unstable(); maps.dedup(); + let to_submission = self.unlogged_names_a_pin(); KeptReplays { gone, keys: keys.into_boxed_slice(), maps: maps.into_boxed_slice(), + to_submission, } } + /// Whether an encoder that keeps no log, once its replays are kept ([`State::keep_replays`]), + /// named a buffer over host pages, by a command of its own or by work it left for later that + /// its commit did not record on the GPU alone: no rebind encodes or records that again, so the + /// command buffer holds its encoders' holds until its last event group is submitted + /// (`held_to_submission`), refusing a rebind meanwhile, which would fail that submission. + fn unlogged_names_a_pin(&self) -> bool { + // One its commit fails runs nothing whatever the rebind: it holds nothing past the commit. + let held = + |r: &super::EncoderRecord| r.replay.is_none() && r.unlogged != Some(Unlogged::Fails); + let unlogged = |at: usize| self.ended.get(at).is_some_and(held); + let own = (self.ended.iter()).any(|r| held(r) && r.taken.names_a_pin()); + own || (self.recorded.iter()) + .filter(|part| unlogged(part.encoder)) + .flat_map(|part| &part.segments) + .filter(|segment| !segment.gpu_alone) + .filter_map(|segment| segment.recorded.as_ref()) + .any(|done| done.taken.names_a_pin()) + } + /// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder a /// call of which raced a rebind of a buffer it took (`Taken::raced`) is to be encoded again, /// in the commit's call, before its first submission, its log kept. One that kept none keeps @@ -923,6 +944,9 @@ pub(super) struct KeptReplays { pub(super) keys: Box<[ResourceKey]>, /// The identities of the rasterization-rate maps its encoders' passes are over. pub(super) maps: Box<[usize]>, + /// An encoder that keeps no log named a buffer over host pages + /// (`State::unlogged_names_a_pin`): its holds stay until its last group's submission. + pub(super) to_submission: bool, } #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 982d15674..6945a13d5 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1716,7 +1716,9 @@ degradations! { /// **Other threads**, `WorkCounts::encoders_raced_rebind`: a blit or logged render /// encoder whose commit failed it or whose encoding again a call that answers otherwise /// refused, as the calls of compute encoders and of render encoders that keep no log are - /// gated, `rebind::CallGate`, and never race one) + /// gated, `rebind::CallGate`, and never race one; and a rebind after the commit of a + /// command buffer with an encoder that keeps no log that named the buffer is refused + /// until its last submission, `Holds::hold_to_submission`) /// (`CommandBufferError::EncodedUseRebound`, `command_buffer/first_submission.rs`), in an /// encoder the runtime could not encode again (a compute encoder its unit of command /// predication reaches past: one whose unit laid a step before it opened, or one of its diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 3dc6978ea..5592ddb17 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -22,11 +22,13 @@ //! each event group is submitted (`command_buffer/first_submission.rs`); a command it encoded //! that names the buffer took the pages as it was encoded (`Taken`), so the rebind encodes its //! compute, blit and render encoders that named the buffer again, in the rebind's call, before -//! their group's submission (`replay.rs`, `command_buffer/reencode.rs`); an encoder it cannot -//! encode again (a compute encoder its unit of command predication reaches past, among others) -//! fails -//! `CommandBufferError::EncodedUseRebound` there, as all did before. Commands encoded after -//! the rebind use the new pages. A rebind while a command buffer that is not yet committed has +//! their group's submission (`replay.rs`, `command_buffer/reencode.rs`). A command buffer one of +//! whose encoders the runtime cannot encode again (a compute encoder its unit of command +//! predication reaches past, among others) named the buffer holds it from its commit until its +//! last event group is submitted (`Holds::hold_to_submission`): a rebind meanwhile is refused +//! (`EncodedUses`, counted by `WorkCounts::rebinds_refused_unsubmitted`), never failing that +//! submission, where Metal's replace reaches the new pages; one after it keeps the old pages for +//! the command buffer's work. Commands encoded after the rebind use the new pages. A rebind while a command buffer that is not yet committed has //! encoded a use of the buffer or heap (one of its resources included), or has an encoder open //! that used one (a render encoder uses its attachments' bytes from its open), is refused //! (`Invalid`, [`RebindProblem::EncodedUses`]): its commands took the old pages, and committing @@ -46,8 +48,8 @@ //! 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. +//! loop runs on over them, and one before it is refused (`EncodedUses`), as the laying's +//! encoders cannot be encoded again (above). //! - **Other threads.** A rebind may run while other threads encode and commit command buffers that //! use the buffer or heap. Its publish runs from the moment the buffer lies in the new pages //! ([`Rebinds::replace`]) to the moment everything over its bytes (aliasing images and their @@ -146,7 +148,10 @@ pub enum RebindProblem { /// 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, 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. Also a call on + /// the GPU alone): commit or drop it first, or wait for its completion. Also one committed and + /// not yet submitted whole one of whose encoders the runtime cannot encode again used it (a + /// compute encoder its unit of command predication reaches past, among others): wait for its + /// submission. Also a call on /// another thread of an encoder the runtime may not encode again (a compute encoder's, or a /// render encoder's that keeps no log) still under way 2 ms after the rebind asked to go on /// (the module docs of `rebind.rs`, **Other threads**): try again. @@ -267,6 +272,10 @@ struct Entry { cell: Weak, /// The holds of encoders and of command buffers not yet committed on it ([`Holds`]). pending: u32, + /// The holds of command buffers committed and not yet submitted whole whose encoder no + /// rebind encodes again named it ([`Holds::hold_to_submission`]): each refuses a rebind as a + /// pending hold does, counted apart (`WorkCounts::rebinds_refused_unsubmitted`). + unsubmitted: u32, /// The holds of submitted work that took it (`SubmittedHolds`), each from the submission of /// its batches until their work completed, and, for a command buffer's last batches, until /// its completion is processed, before its completed handlers run: a detach refuses while one @@ -361,6 +370,7 @@ impl Rebinds { let entry = Entry { cell: Arc::downgrade(cell), pending: 0, + unsubmitted: 0, submitted: 0, detached: false, resident: false, @@ -708,18 +718,39 @@ impl Rebinds { self.completed.notify_all(); } - /// Let go of one hold of `key`. - fn release(&self, key: ResourceKey) { + /// Let go of one hold of `key`, held to its command buffer's submission where `submission` + /// ([`Holds::hold_to_submission`]). + fn release(&self, key: ResourceKey, submission: bool) { if let Some(entry) = lock(&self.buffers).get_mut(&key) { - entry.pending = entry.pending.saturating_sub(1); + match submission { + true => entry.unsubmitted = entry.unsubmitted.saturating_sub(1), + false => entry.pending = entry.pending.saturating_sub(1), + } } } - /// Whether a hold refuses a rebind of `key`. - fn pending(&self, key: ResourceKey) -> bool { - lock(&self.buffers) - .get(&key) - .is_some_and(|entry| entry.pending > 0) + /// The holds of `keys`, one each, held from now until their command buffer's last event group + /// is submitted ([`Holds::hold_to_submission`]), under one lock: moved from `pending` to + /// `unsubmitted`, so no rebind falls between. + fn hold_to_submission(&self, keys: &[ResourceKey]) { + let mut buffers = lock(&self.buffers); + for key in keys { + if let Some(entry) = buffers.get_mut(key) { + entry.pending = entry.pending.saturating_sub(1); + entry.unsubmitted += 1; + } + } + } + + /// Why a hold refuses a rebind of `key`, if one does. + fn pending(&self, key: ResourceKey) -> Option { + let buffers = lock(&self.buffers); + let entry = buffers.get(&key)?; + match (entry.pending > 0, entry.unsubmitted > 0) { + (true, _) => Some(Unreplaced::Held), + (false, true) => Some(Unreplaced::Unsubmitted), + (false, false) => None, + } } /// Give the buffer of `key`, whose hold on its pages is `cell`, `pages` from now on, unless @@ -752,6 +783,10 @@ impl Rebinds { self.unopen(buffers); return Err(Unreplaced::Held); } + if entry.unsubmitted > 0 { + self.unopen(buffers); + return Err(Unreplaced::Unsubmitted); + } if entry.detached { entry.detached = false; self.detached.fetch_sub(1, Ordering::AcqRel); @@ -787,6 +822,9 @@ pub(super) enum Unreplaced { Held, /// A gated call under way that did not end within [`CALLS_DRAIN`] ([`CallGate`]). Calls, + /// A command buffer committed and not yet submitted whole, whose encoder no rebind encodes + /// again named the buffer ([`Holds::hold_to_submission`]). + Unsubmitted, } thread_local! { @@ -1023,6 +1061,9 @@ pub(super) struct Holds { call: u64, /// Its encoder's calls are gated ([`CallGate`]). gates: bool, + /// Its holds are held to their command buffer's submission ([`hold_to_submission`]( + /// Self::hold_to_submission)). + to_submission: bool, } impl Holds { @@ -1035,9 +1076,23 @@ impl Holds { keys: Vec::new(), call: device.shared().rebinds.call_begins(), gates: false, + to_submission: false, } } + /// Its command buffer committed with an encoder no rebind encodes again that named a buffer + /// over host pages: its holds stay until its last event group is submitted, or it completes + /// (`State::held_to_submission`), refusing a rebind meanwhile + /// (`RebindProblem::EncodedUses`), which would fail that submission + /// (`CommandBufferError::EncodedUseRebound`). Once. + pub(super) fn hold_to_submission(&mut self) { + if self.to_submission || self.keys.is_empty() { + return; + } + self.device.shared().rebinds.hold_to_submission(&self.keys); + self.to_submission = true; + } + /// Gate its encoder's calls from its next on ([`CallGate`]): an encoder the runtime may not /// encode again. pub(super) fn gate_calls(&mut self) { @@ -1397,7 +1452,7 @@ impl Drop for Holds { fn drop(&mut self) { let rebinds = &self.device.shared().rebinds; for &key in &self.keys { - rebinds.release(key); + rebinds.release(key, self.to_submission); } } } @@ -1411,9 +1466,9 @@ impl Buffer { /// submitted before the call keep the old memory until they complete; one committed before it /// and first submitted after reaches the new memory through what it made resident and what its /// commands reach unnamed, and through what its compute, blit and render encoders named, which - /// this call encodes again; it fails `CommandBufferError::EncodedUseRebound` where an encoder - /// this call cannot encode again named the buffer (one of a command buffer that used command - /// predication, among others); commands encoded after it use the new. The old memory's + /// this call encodes again; where one of its encoders this call cannot encode again named the + /// buffer (one of a command buffer that used command predication, among others), the call is + /// refused until its last submission instead (below); commands encoded after it use the new. The old memory's /// deallocator runs once every command buffer submitted before the call that used it completed /// (in the call, where none holds it), and that of the memory a detach let go of in the call, /// as Metal's replace runs it; `deallocator` runs for the new memory at the next rebind's @@ -1455,8 +1510,9 @@ impl Buffer { /// 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, 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 + /// until it completed, or one committed whose encoder this call cannot encode again used it, + /// until its last submission (`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)`, @@ -1583,8 +1639,8 @@ impl Heap { } impl Device { - /// Whether a hold refuses a rebind of the buffer of `key` (`Rebinds::pending`). - pub(super) fn rebind_pending(&self, key: ResourceKey) -> bool { + /// Why a hold refuses a rebind of the buffer of `key`, if one does (`Rebinds::pending`). + pub(super) fn rebind_pending(&self, key: ResourceKey) -> Option { self.shared().rebinds.pending(key) } } diff --git a/crates/metal2vulkan-runtime/src/tests/pending_rebind.rs b/crates/metal2vulkan-runtime/src/tests/pending_rebind.rs index 55a54f313..dfce6e748 100644 --- a/crates/metal2vulkan-runtime/src/tests/pending_rebind.rs +++ b/crates/metal2vulkan-runtime/src/tests/pending_rebind.rs @@ -4,13 +4,14 @@ //! //! Such a dispatch's commands are recorded later -- by the scheduler's host step once the makings //! are done -- and they are the commands its encoding resolved: its set 0 names the `VkBuffer` -//! the buffer lay in as the dispatch was encoded. A rebind meanwhile frees that `VkBuffer`, since -//! a command buffer committed and not yet submitted holds the pages its commands took only weakly -//! (`first_submission.rs`), and the submission that holds the dispatch then runs nothing: -//! `CommandBufferError::EncodedUseRebound`, the encoder being one no rebind encodes again +//! the buffer lay in as the dispatch was encoded. Its encoder is one no rebind encodes again //! (`Unlogged::Predicated`: a block of command predication the encoder before it opened spans it, -//! so its commands run from gates that encoder's recording writes, `Predication::alone`). So the -//! host step records none of its commands. +//! so its commands run from gates that encoder's recording writes, `Predication::alone`), so the +//! command buffer holds the buffer from its commit until its last submission +//! (`Holds::hold_to_submission`): the rebind is refused (`RebindProblem::EncodedUses`), never +//! freeing that `VkBuffer` under the recorded descriptor nor failing the submission +//! (`CommandBufferError::EncodedUseRebound`), and the dispatch writes the pages it was encoded +//! over. //! //! Recording them named a freed `VkBuffer` in a bound descriptor, which the validation layer //! reports (`VUID-vkCmdDispatch-None-08114`) and a driver that reads a descriptor as it encodes @@ -30,9 +31,10 @@ use super::blit_holds::{over_host, Host, Scratch, WAIT}; use super::dispatch_pending::state; use super::layer_claim::Watched; +use crate::error::{invalid, Problem}; use crate::pipeline::pool::held; use crate::{ - CommandBufferError, CommandBufferStatus, Device, DeviceKind, DeviceOptions, ResourceOptions, + CommandBufferStatus, Device, DeviceKind, DeviceOptions, RebindProblem, ResourceOptions, ShaderCacheOptions, Size, }; use std::path::Path; @@ -79,12 +81,12 @@ pub(super) fn options() -> DeviceOptions { } /// A dispatch of a kernel writing into a no-copy buffer, inside an If the encoder before its own -/// opened, its `VkPipeline` held from being made, and the buffer rebound after the commit: the -/// command buffer fails `EncodedUseRebound`, writing nothing into either range of pages, and the -/// host step that records the dispatch once its making is done records nothing of it -- the -/// validation layer reports no descriptor naming the `VkBuffer` the rebind freed. +/// opened, its `VkPipeline` held from being made, and a rebind of the buffer after the commit: +/// the rebind is refused, and the host step that records the dispatch once its making is done +/// writes the pages it was encoded over, the command buffer completing -- the validation layer +/// reports no descriptor naming a freed `VkBuffer`. #[test] -fn a_pending_dispatch_records_nothing_where_a_rebind_freed_what_its_descriptors_name() { +fn a_rebind_after_the_commit_of_a_pending_dispatch_no_rebind_encodes_again_is_refused() { // Declared before the device, so dropped after it. let hosts = [Host::new(), Host::new()]; let watched = Watched::default(); @@ -132,23 +134,40 @@ fn a_pending_dispatch_records_nothing_where_a_rebind_freed_what_its_descriptors_ assert!(encoder.encode_end_if().unwrap(), "the If ends"); encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); - // The buffer lies elsewhere from here, and the pages it lay in go: nothing submitted holds - // them, and the committed command buffer holds them weakly. + // The command buffer holds the buffer until its submission, which waits for the makings. // // SAFETY: the pages outlive every buffer over them, and only its commands use them while it // lives. - unsafe { output.rebind_bytes_no_copy(hosts[1].memory(), None, None) }.unwrap(); - // The makings may finish now, so the host step records the dispatch after the rebind. + let rebound = unsafe { output.rebind_bytes_no_copy(hosts[1].memory(), None, None) }; + let encoded_uses = invalid( + "rebind_bytes_no_copy", + Problem::Rebind(RebindProblem::EncodedUses), + ); + assert_eq!( + rebound, + Err(encoded_uses), + "the rebind before the submission" + ); + // The makings may finish now, so the host step records the dispatch. drop(hold); command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.status(), CommandBufferStatus::Error); assert_eq!( - command_buffer.error(), - Some(CommandBufferError::EncodedUseRebound), - "the submission holding the dispatch ran nothing" + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + // `input[i] * SCALE + i`, input `i`. + let wrote: Vec = (0..COUNT) + .map(|i| (i as f32 * SCALE + i as f32).to_bits()) + .collect(); + assert_eq!( + &hosts[0].words()[..COUNT as usize], + &wrote[..], + "the dispatch wrote the pages it was encoded over" + ); + assert!( + hosts[1].holds(0), + "nothing wrote the pages the rebind offered" ); - assert!(hosts[0].holds(0), "the pages the dispatch took"); - assert!(hosts[1].holds(0), "the pages the buffer lies in now"); watched.layer_reported_nothing( "a dispatch recorded after a rebind of a buffer it named bound no freed VkBuffer", ); diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs b/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs index 72d31b9ec..427d55904 100644 --- a/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/rebind_loop_check.rs @@ -8,9 +8,10 @@ //! (`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`). +//! laying's submission is refused (`RebindProblem::EncodedUses`): the laying's encoders keep no +//! log to be encoded again from (`predication.rs`), so the command buffer holds the buffer until +//! its last submission (`Holds::hold_to_submission`), and the laying runs over the pages it was +//! encoded over, never failing `EncodedUseRebound`. //! //! 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 @@ -22,9 +23,10 @@ use super::blit_holds::{options, Scratch, WAIT}; use super::dispatch_pending::state; use super::rebind_behind_a_wait::{Page, BYTES, COUNT, SCALE}; +use crate::error::{invalid, Problem}; use crate::{ - Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, ComputePipelineState, - Degradation, Device, Error, EventRef, MessageSink, ResourceOptions, Size, + Buffer, CommandBuffer, CommandBufferStatus, ComputePipelineState, Degradation, Device, Error, + EventRef, MessageSink, RebindProblem, ResourceOptions, Size, }; use std::mem::ManuallyDrop; use std::sync::{Arc, Mutex}; @@ -213,12 +215,11 @@ fn a_rebind_while_a_loop_runs_again_is_taken_and_the_loop_keeps_its_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. +/// shared-event wait only the host signals, is refused: the laying's encoder cannot be encoded +/// again, so the command buffer holds the buffer until its submission, and the laying runs over +/// the first page, which its output shows, with no `EncodedUseRebound` failure or notice. #[test] -fn a_rebind_before_a_loop_s_submission_fails_it_rebound() { +fn a_rebind_before_a_loop_s_submission_is_refused() { let pages = ManuallyDrop::new([Page::new(), Page::new()]); let scratch = Scratch::new("loop-rebind-before"); let (device, heard) = device(&scratch); @@ -243,18 +244,12 @@ fn a_rebind_before_a_loop_s_submission_fails_it_rebound() { 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() .contains(&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(), @@ -262,11 +257,19 @@ fn a_rebind_before_a_loop_s_submission_fails_it_rebound() { command_buffer.error(), heard.lock().unwrap(), ); - assert_eq!(rebound, Ok(()), "the rebind before the laying's submission"); + let encoded_uses = invalid( + "rebind_bytes_no_copy", + Problem::Rebind(RebindProblem::EncodedUses), + ); + assert_eq!( + rebound, + Err(encoded_uses), + "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"); + assert_eq!(command_buffer.error(), None); + assert!(!announced(), "encoded-use-rebound announced"); + assert_eq!(floats(&output), expected(0.0), "the first page's input"); drop((command_buffer, queue, over, output, scale, state, gate)); drop(device); drop(ManuallyDrop::into_inner(pages)); diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_races.rs b/crates/metal2vulkan-runtime/src/tests/rebind_races.rs index 3e3ec6e36..df9291746 100644 --- a/crates/metal2vulkan-runtime/src/tests/rebind_races.rs +++ b/crates/metal2vulkan-runtime/src/tests/rebind_races.rs @@ -18,6 +18,13 @@ //! `WorkCounts::rebinds_refused_calls_in_flight`), and the dispatch reads the pages it was //! encoded over. A tree without the gate makes the rebind, and the encoder fails //! `EncodedUseRebound`. +//! - **After the commit.** That predicated dispatch's command buffer committed behind a wait on a +//! shared event, so not yet submitted, while the main thread rebinds the buffer: its encoder +//! cannot be encoded again, so the command buffer holds the buffer until its last submission +//! (`Holds::hold_to_submission`), the rebind is refused (`EncodedUses`, +//! `WorkCounts::rebinds_refused_unsubmitted`), and once signaled the dispatch reads the pages it +//! was encoded over. A tree without the hold makes the rebind, and the command buffer fails +//! `EncodedUseRebound`. //! - **Threads.** Six threads encode and commit command buffers whose commands read the buffer, //! one family each: a dispatch reading a texture over it, a draw reading it as a vertex buffer, //! a blit copying from it, a dispatch it was bound to a call before (the dispatch's bind @@ -27,9 +34,9 @@ //! completed, so its encoder keeps no log, `Unlogged::Segments`). A seventh thread rebinds it //! to fresh pages meanwhile, as often as it is let. Every page holds one value in every word, so //! each command buffer's output is wholly one page's, of a page the buffer lay in between the -//! start of the encoding and the completion, or the command buffer failed `EncodedUseRebound`: -//! the predicated one where the rebind came between its commit and its first submission (the -//! ordering rule, `rebind.rs`), never for a race (`WorkCounts::encoders_raced_unreplayable`). +//! start of the encoding and the completion, and none fails `EncodedUseRebound`: no encoder the +//! runtime cannot encode again races a rebind (`WorkCounts::encoders_raced_unreplayable`), and a +//! rebind between such a command buffer's commit and its submission is refused. //! It prints the rebinds made and refused, the encoders that raced and the failures. //! //! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). The functions @@ -43,8 +50,8 @@ use crate::error::{invalid, Problem}; use crate::rebind::pause::{self, Point}; use crate::{ BlitOption, Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, - ComputePipelineState, Device, Error, HostMemory, Origin, PipelineOptions, RebindProblem, - Region, RenderPipelineState, ResourceOptions, Size, Texture, TextureDescriptor, + ComputePipelineState, Device, Error, EventRef, HostMemory, Origin, PipelineOptions, + RebindProblem, Region, RenderPipelineState, ResourceOptions, Size, Texture, TextureDescriptor, }; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use std::alloc::Layout; @@ -599,6 +606,67 @@ fn a_rebind_during_a_call_of_an_encoder_it_cannot_encode_again_is_refused() { rebind(&buffer, &pages[1]).expect("the rebind after the completion"); } +/// The predicated dispatch's command buffer committed behind an unsignaled wait, so not yet +/// submitted, while the main thread rebinds the buffer: the rebind is refused, and the command +/// buffer, once signaled, completes over the pages it was encoded over. +#[test] +fn a_rebind_before_the_submission_of_an_encoder_it_cannot_encode_again_is_refused() { + let scratch = Scratch::new("rebind-races-unsubmitted"); + let device = device(&scratch.0); + let fixtures = Fixtures::new(&device); + let pages = [Page::new(0), Page::new(1)]; + let Some(buffer) = over(&device, &pages[0]) else { + return; + }; + let over_texture = texture_over(&buffer); + let queue = device.new_command_queue().unwrap(); + let before = device.work_counts(); + let encoded_uses = invalid( + "rebind_bytes_no_copy", + Problem::Rebind(RebindProblem::EncodedUses), + ); + 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(); + let output = encode( + Family::Predicated, + &device, + &fixtures, + &command_buffer, + (&buffer, &over_texture), + ); + command_buffer.commit().unwrap(); + let rebound = rebind(&buffer, &pages[1]); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let after = device.work_counts(); + let grew = |of: fn(&crate::WorkCounts) -> u64| of(&after) - of(&before); + println!( + "REBIND-RACES unsubmitted: rebind {rebound:?}; {:?} {:?}; {} refused for a command buffer \ + not yet submitted", + command_buffer.status(), + command_buffer.error(), + grew(|counts| counts.rebinds_refused_unsubmitted), + ); + assert_eq!( + rebound, + Err(encoded_uses), + "the rebind before the submission" + ); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + assert_eq!( + output.words(), + expected(Family::Predicated, 0), + "the dispatch read the pages it was encoded over" + ); + assert_eq!(grew(|counts| counts.rebinds_refused_unsubmitted), 1); + // Once the command buffer was submitted, the rebind goes. + rebind(&buffer, &pages[1]).expect("the rebind after the submission"); +} + /// What one command buffer of the threaded run came to. #[derive(Debug)] enum Seen { @@ -722,9 +790,11 @@ fn encoders_on_other_threads_read_wholly_one_page_of_a_buffer_rebound_meanwhile( let grew = |of: fn(&crate::WorkCounts) -> u64| of(&after) - of(&before); println!( "REBIND-RACES threads: {made} rebinds made, {refused} refused (EncodedUses), {} of them for \ - a gated call under way; {} gated calls waited for a publish; {} encoders raced a rebind, \ + a gated call under way, {} for a command buffer not yet submitted; {} gated calls \ + waited for a publish; {} encoders raced a rebind, \ {} of them unreplayable, {} encoded again, {} refused encoding again", grew(|counts| counts.rebinds_refused_calls_in_flight), + grew(|counts| counts.rebinds_refused_unsubmitted), grew(|counts| counts.encoder_calls_held_by_rebind), grew(|counts| counts.encoders_raced_rebind), grew(|counts| counts.encoders_raced_unreplayable), @@ -739,6 +809,12 @@ fn encoders_on_other_threads_read_wholly_one_page_of_a_buffer_rebound_meanwhile( .collect(); assert_eq!(seen.len(), FAMILIES.len() * ROUNDS); assert!(wrong.is_empty(), "wrong outputs: {wrong:?}"); + let rebound = (seen.iter()).filter(|(_, outcome)| matches!(outcome, Seen::Rebound)); + assert_eq!( + rebound.count(), + 0, + "command buffers that failed EncodedUseRebound" + ); assert_eq!( grew(|counts| counts.encoders_raced_unreplayable), 0, diff --git a/crates/metal2vulkan-runtime/src/tests/tile_rebind_making_wait.rs b/crates/metal2vulkan-runtime/src/tests/tile_rebind_making_wait.rs index 02a1d4981..5343cf6ca 100644 --- a/crates/metal2vulkan-runtime/src/tests/tile_rebind_making_wait.rs +++ b/crates/metal2vulkan-runtime/src/tests/tile_rebind_making_wait.rs @@ -50,11 +50,12 @@ use super::layer_claim::Watched; use super::pending_rebind::device as watched_device; use super::rebind_behind_a_wait::{Page, BYTES}; use super::tile_pending::{tile_state, FORMATS}; +use crate::error::{invalid, Problem}; use crate::pipeline::pool::held; use crate::{ - Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, Device, Error, - EventRef, LoadAction, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, - SharedEvent, Size, StoreAction, Texture, TextureDescriptor, + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, Error, EventRef, LoadAction, + RebindProblem, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, SharedEvent, + Size, StoreAction, Texture, TextureDescriptor, }; use metal2vulkan::metal::TextureUsage; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; @@ -488,26 +489,25 @@ fn a_rebind_does_not_wait_for_a_tile_making_another_encoder_began() { leg(Memo::InFlight); } -/// The guard on the other side of the rebind rule, with the validation layer watching. +/// The other side of the rebind rule, with the validation layer watching. /// /// A pass left for the pipelines its tile dispatch records holds no buffer's pages past its /// command buffer's commit (`CommandBuffer::commit`'s `steps_hold`), so a rebind of one is not /// refused -- Metal's replace never fails for that -- and encodes its encoder again instead. Where -/// that encoding again cannot happen, the pass must record nothing: its instances' secondaries and -/// its tile dispatch's recording resolved the buffer where it lay as they were encoded, and the -/// pages a rebind freed stay mapped, so a recording that bound that `VkBuffer` would have the GPU -/// write into pages the program handed back, with no fault and nothing said. That is the class of -/// bug this guard exists for, so it is watched by the layer and not by a page's contents alone. +/// that encoding again cannot happen, the command buffer holds the buffer from its commit until its +/// last submission (`Holds::hold_to_submission`), and a rebind meanwhile is refused: its +/// instances' secondaries and its tile dispatch's recording resolved the buffer where it lay as +/// they were encoded, so a rebind that freed those pages would leave the submission running +/// nothing (`EncodedUseRebound`), and a recording that bound that `VkBuffer` would have the GPU +/// write into pages the program handed back. /// /// The encoding again is made impossible: the render encoder is opened while the device has no -/// buffer over host pages, so it logs no call (`Unlogged::NoCalls`) and no rebind can replay it. The device's pool is held, so only a host step records the pass, -/// and only once the hold is gone -- after the rebind, in every run. -/// -/// Without `DeferredPass::record_forms`' `encoder_rebound` guard the host step records the pass and -/// the layer reports the freed `VkBuffer` in a bound descriptor -/// (`VUID-vkCmdDrawIndexed-None-08114` and its kin), which fails this test. +/// buffer over host pages, so it logs no call (`Unlogged::NoCalls`) and no rebind can replay it. +/// The device's pool is held, so only a host step records the pass, and only once the hold is +/// gone -- after the rebind, in every run. The rebind is refused, the pass records over the pages +/// it was encoded over, and the layer reports nothing. #[test] -fn a_tile_pass_records_nothing_where_a_rebind_freed_what_its_descriptors_name() { +fn a_rebind_before_the_submission_of_a_tile_pass_no_rebind_encodes_again_is_refused() { // Declared before the device, so dropped after it. let hosts = [Host::new(), Host::new()]; let watched = Watched::default(); @@ -550,31 +550,36 @@ fn a_tile_pass_records_nothing_where_a_rebind_freed_what_its_descriptors_name() ); command_buffer.commit().unwrap(); - // The buffer lies elsewhere from here, and the pages it lay in go: nothing submitted holds - // them, and the committed command buffer holds them weakly. The rebind is allowed at all only - // because the pass holds nothing past the commit. + // The command buffer holds the buffer until its submission, which waits for the makings. // // SAFETY: the pages outlive every buffer over them, and only its commands use them while it // lives. - unsafe { output.rebind_bytes_no_copy(hosts[1].memory(), None, None) }.unwrap(); + let rebound = unsafe { output.rebind_bytes_no_copy(hosts[1].memory(), None, None) }; + let encoded_uses = invalid( + "rebind_bytes_no_copy", + Problem::Rebind(RebindProblem::EncodedUses), + ); + assert_eq!( + rebound, + Err(encoded_uses), + "the rebind before the submission" + ); assert_eq!( device.work_counts().encoders_reencoded, 0, "the encoder kept no log, so nothing was encoded again" ); - // The makings may finish now, so the host step records the pass after the rebind. + // The makings may finish now, so the host step records the pass. drop(hold); command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.status(), CommandBufferStatus::Error); assert_eq!( - command_buffer.error(), - Some(CommandBufferError::EncodedUseRebound), - "the submission holding the pass ran nothing" + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) ); - assert!(hosts[0].holds(0), "the pages the dispatch took"); - assert!(hosts[1].holds(0), "the pages the buffer lies in now"); - watched.layer_reported_nothing( - "a tile pass recorded after a rebind of a buffer it named bound no freed VkBuffer", + assert!( + hosts[1].holds(0), + "nothing wrote the pages the rebind offered" ); + watched.layer_reported_nothing("a tile pass recorded over the pages it was encoded over"); } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b0926dd4c..1468630fb 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -789,6 +789,7 @@ pub(crate) struct Counters { encoders_raced_rebind: AtomicU64, encoders_raced_unreplayable: AtomicU64, rebinds_refused_calls_in_flight: AtomicU64, + rebinds_refused_unsubmitted: AtomicU64, encoder_calls_held_by_rebind: AtomicU64, pipeline_libraries_made: AtomicU64, fragment_shader_libraries_made: AtomicU64, @@ -6172,6 +6173,12 @@ impl Counters { (self.rebinds_refused_calls_in_flight).fetch_add(1, Ordering::Relaxed); } + /// A rebind was refused (`EncodedUses`) for a committed command buffer not yet submitted whole + /// whose encoder no rebind encodes again named the buffer (`Holds::hold_to_submission`). + pub(crate) fn rebind_refused_unsubmitted(&self) { + (self.rebinds_refused_unsubmitted).fetch_add(1, Ordering::Relaxed); + } + /// A gated encoder call waited, as it began, for a rebind's publish to close /// (`rebind::CallGate`). pub(crate) fn encoder_call_held_by_rebind(&self) { @@ -11863,6 +11870,12 @@ pub struct WorkCounts { /// where no such call outlasts the bound (a call waiting for a `VkPipeline` being made, say); /// the caller may try again. pub rebinds_refused_calls_in_flight: u64, + /// Rebinds refused (`RebindProblem::EncodedUses`) because a command buffer committed and not + /// yet submitted whole used the buffer in an encoder the runtime cannot encode again (a + /// compute encoder its unit of command predication reaches past, among others): a rebind + /// before that submission would fail it (`EncodedUseRebound`), so it gives way until the + /// command buffer's last event group is submitted; the caller may try again. + pub rebinds_refused_unsubmitted: u64, /// Calls of such encoders that waited, as they began, for a rebind's publish on another /// thread to close (`rebind_bytes_no_copy`): from just before the buffer took its new pages /// to when everything over its bytes was made over them. @@ -13692,6 +13705,8 @@ impl Device { .load(Ordering::Relaxed), rebinds_refused_calls_in_flight: (counters.rebinds_refused_calls_in_flight) .load(Ordering::Relaxed), + rebinds_refused_unsubmitted: (counters.rebinds_refused_unsubmitted) + .load(Ordering::Relaxed), encoder_calls_held_by_rebind: (counters.encoder_calls_held_by_rebind) .load(Ordering::Relaxed), fences_made: self.shared().fences.made(), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 548e24beb..dc5c24ea2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -103,8 +103,9 @@ //! and zero them in `color_reformat` ([`KEPT_COLORS`]), multisampled depth copied in by an //! inexact fragment-depth draw in `sample_copies` ([`DRAWN_DEPTH`]), textures bound beyond their //! declared usage through an image of their own in `buffer_texture_order` ([`USAGE_SHADOWS`]), -//! command buffers whose named uses of a buffer rebound before their first submission fail in -//! `rebind_reach` ([`REBOUND_USES`]), textures over bytes detached after they were resident, +//! command buffers whose named uses of a buffer rebound before their first submission fail +//! ([`REBOUND_USES`]: `rebind_reach` refuses such a rebind now where no rebind encodes the use +//! again, so no lane test takes it today), textures over bytes detached after they were resident, //! and writable ones whose writes their stand-ins' sinks keep, reached unnamed in //! `detach_textures` ([`DETACHED_REACHES`]), textures in heaps laid out otherwise than Metal's //! tiles in `heap_layouts` and `heap_textures` ([`HEAP_LAYOUTS`]), fetches under a written depth test diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs index e12eb972b..4677cdfee 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs @@ -55,10 +55,11 @@ use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, BufferContents, BufferDescriptor, ClearColor, CommandBuffer, CommandBufferError, - CommandBufferStatus, CommandQueue, CommitFailure, Deallocator, Degradation, Device, EventRef, - FailedEncoders, Heap, HeapType, HostMemory, KeepAlive, LoadAction, PipelineOptions, Region, - RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, - StoreAction, Submission, SubmissionCheck, TextureDescriptor, + CommandBufferStatus, CommandQueue, CommitFailure, Deallocator, Degradation, Device, Error, + EventRef, FailedEncoders, Heap, HeapType, HostMemory, Invalid, KeepAlive, LoadAction, + PipelineOptions, Problem, RebindProblem, Region, RenderCommandEncoder, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, Size, StoreAction, Submission, SubmissionCheck, + TextureDescriptor, }; use std::collections::BTreeMap; use std::num::NonZeroU64; @@ -771,18 +772,18 @@ fn a_unit_s_plain_encoder_before_its_predicated_one_is_encoded_again() { /// where its step writes them -- so such a command would run nothing where Metal runs it. /// Encoding a run of a unit's encoders again together, which that shape needs, is not done. /// -/// The unit's first encoder dispatches `prd_mark` into the member rebound after the commit and -/// then opens and closes an If, so the member is named by a dispatch before the unit's first -/// record, which runs ungated; next in its unit a plain encoder dispatches into a buffer of its -/// own, from a gate that first encoder's step writes. The first encoder laid the unit's first -/// step and the unit went on past it, so it keeps no log and keeps its first recording, which -/// named the old pages: its submission (the unit's two encoders) runs nothing, the member keeps -/// the new pages' node, the command buffer fails `EncodedUseRebound`, announced once, the notice -/// naming the encoder and why, and its signal fires. The blit encoder before it, which copies -/// the member, is encoded again, and its own submission -/// (`checks::metal_submissions`: consecutive compute encoders share one) copies the new pages. +/// The unit's first encoder dispatches `prd_mark` into the member and then opens and closes an +/// If, so the member is named by a dispatch before the unit's first record, which runs ungated; +/// next in its unit a plain encoder dispatches into a buffer of its own, from a gate that first +/// encoder's step writes. The first encoder laid the unit's first step and the unit went on past +/// it, so it keeps no log: its command buffer, committed behind a wait, holds the member until +/// its last submission (`Holds::hold_to_submission`), so a rebind of the member before the +/// signal is refused (`EncodedUses`, `WorkCounts::rebinds_refused_unsubmitted`) rather than +/// failing that submission `EncodedUseRebound`. The command buffer completes over the pages it +/// was encoded over -- the blit copies the old node -- with no `EncodedUseRebound` notice, and its +/// signal fires. #[test] -fn a_unit_s_encoder_that_laid_its_first_step_fails_encoded_use_rebound() { +fn a_rebind_before_the_submission_of_a_unit_s_encoder_that_laid_its_first_step_is_refused() { on_device_noticed(|device, messages| { let queue = device.new_command_queue().unwrap(); let Some((member, _)) = member_over(device, A) else { @@ -827,51 +828,36 @@ fn a_unit_s_encoder_that_laid_its_first_step_fails_encoded_use_rebound() { .unwrap(); command_buffer.commit().unwrap(); let before = device.work_counts(); - drop(rebind_to(&member, B)); + let seen = Arc::new(Seen::default()); + assert_eq!( + rebind(&member, pages(buffer_len(), 0, &node(B)), &seen), + Err(Error::Invalid(Invalid::new( + "rebind_bytes_no_copy", + Problem::Rebind(RebindProblem::EncodedUses) + ))), + "the rebind before the submission" + ); event.set_signaled_value(1); command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.status(), CommandBufferStatus::Error); assert_eq!( - command_buffer.error(), - Some(CommandBufferError::EncodedUseRebound) + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) ); assert_eq!( read_buffer(&copied, 0, 16).unwrap(), - node(B), - "the blit's copy of the new pages" - ); - assert_eq!( - read_buffer(&member, 0, 16).unwrap(), - node(B), - "the unit's dispatches ran nothing" - ); - assert_eq!( - read_buffer(&log, 0, 16).unwrap(), - vec![0; 16], - "the gated dispatch of the unit's later encoder ran nothing" + node(A), + "the blit's copy of the pages it was encoded over" ); assert_eq!(done.signaled_value(), 1, "its signal"); - let notices = made_once(messages, &REBOUND_USES, &shared_kinds(device)); - // The notice names where the first submission found the use, and why no rebind - // encoded it again. - let reason = (notices.iter()) - .filter_map(|message| message.degradation.as_ref()) - .find(|notice| notice.degradation == Degradation::EncodedUseRebound) - .map(|notice| notice.reason.clone()); - let found = "(found in its compute encoder 1: a command of its own named it, not encoded \ - again as its unit of command predication laid a step before it opened, or \ - one of its own that the unit's later encoders read, or a loop, or left work \ - out"; - assert!( - reason - .as_deref() - .is_some_and(|reason| reason.contains(found)), - "{reason:?}" - ); + let notices = assert_made_once(messages, &[], &shared_kinds(device)); + assert!(!notices.contains_key(&Degradation::EncodedUseRebound)); let after = device.work_counts(); - // The blit encoder, alone, encoded again. - assert_eq!(after.encoders_reencoded, before.encoders_reencoded + 1); - eprintln!("REBIND-REACH not encoded again: EncodedUseRebound, announced once"); + assert_eq!( + after.rebinds_refused_unsubmitted, + before.rebinds_refused_unsubmitted + 1 + ); + assert_eq!(after.encoders_reencoded, before.encoders_reencoded); + eprintln!("REBIND-REACH not encoded again: the rebind refused until the submission"); }); } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index bf01901a8..55370dc97 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 = 524; /// 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 = 2469; +pub const RUNTIME_VERSION: u32 = 2470; /// 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/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f6064f4ff..dfd65b2fd 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3559,6 +3559,7 @@ field metal2vulkan-runtime::WorkCounts.reading_draws_split_variant_refused pub r field metal2vulkan-runtime::WorkCounts.reading_draws_split_views pub reading_draws_split_views: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_split_visibility_query pub reading_draws_split_visibility_query: u64 field metal2vulkan-runtime::WorkCounts.rebinds_refused_calls_in_flight pub rebinds_refused_calls_in_flight: u64 +field metal2vulkan-runtime::WorkCounts.rebinds_refused_unsubmitted pub rebinds_refused_unsubmitted: u64 field metal2vulkan-runtime::WorkCounts.record_lists_grown pub record_lists_grown: u64 field metal2vulkan-runtime::WorkCounts.record_storage_kept pub record_storage_kept: u64 field metal2vulkan-runtime::WorkCounts.reencodes_refused pub reencodes_refused: u64 diff --git a/docs/API.md b/docs/API.md index 3fd03e30e..d3f175f9c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3627,7 +3627,11 @@ bound. `WorkCounts::encoders_raced_rebind`), in an encoder the runtime could not encode again. A raced one is a blit or logged render encoder whose commit failed it or whose encoding again a call that answers otherwise refused: the calls of compute encoders and of render encoders that keep no log - never race a rebind, which waits for them or is refused (`RebindProblem::EncodedUses`). Cost: each + never race a rebind, which waits for them or is refused (`RebindProblem::EncodedUses`). Nor does a + rebind after the commit reach an encoder that keeps no log: its command buffer holds the buffer + until its last submission, and the rebind is refused meanwhile (`EncodedUses`, + `WorkCounts::rebinds_refused_unsubmitted`); what remains is an encoder that kept its log and whose + encoding again a call that answers otherwise refused, or that its commit failed. Cost: each of Metal's submissions of the command buffer holding such a command runs nothing and the command buffer fails (EncodedUseRebound), where Metal resolves the use as it submits the command buffer and reaches the pages the buffer lies in then; the rebind encodes compute, blit and render