From 5acd27cd0d6a1258253e8e5b0934c9d2acdac86c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 10:59:33 -0800 Subject: [PATCH] RUNTIME 2468: Rebinds: a call of an encoder the runtime cannot encode again never races a rebind After RUNTIME 2465 a rebind racing an encoder call on another thread is detected and the encoder encoded again; one the runtime cannot encode again (a compute encoder its predication unit reaches past, one that left a GPU-written indirect dispatch to its host step, a render encoder that keeps no log) failed EncodedUseRebound at submission instead, which a consumer's answer table treats as fatal. The protocol: those encoders' calls are gated, so no publish overlaps one. - Rebinds gains `calls` (gated calls under way). A gated call begins (`Holds::begin_call` -> `CallGate::enter`): calls += 1, then reads `open`; where a publish is open it backs off and waits for it to close (`wait_published`), before it reads anything of a buffer over host pages. - A rebind's publish now opens before its replace (`Rebinds::quiet_calls`): open += 1, then reads `calls`; where a call is under way it waits for the calls to end (`drain`/`drained`), up to CALLS_DRAIN (2 ms), and is refused past it (EncodedUses, Unreplaced::Calls), never failing the encoder later. The four accesses are SeqCst (a store-buffering handshake: of a rebind and a call that meet, at least one reads the other's rise), so each gated call reads the buffer wholly before the publish (holding it, which refuses a rebind until its commit) or wholly after its close. Chosen over the registry lock: the call side costs two atomics and takes no lock. - Which encoders: every compute encoder, and a render encoder that opened with no log. A compute encoder can become unreplayable mid-encoding (the call that records predication, a loop's record, an unbalanced record that leaves work out, a later encoder of its unit that lays a loop, a dispatch left to its host step), after earlier calls ran: a gate that started at that transition would leave those earlier calls racing. So the gate covers a compute encoder from its open. Blit encoders always log, and render encoders with a log, stay re-encodable and pay nothing new. A device with no buffer over host pages pays one Relaxed load per gated call (`any`). - Nesting: a thread-local depth, so a call an encoder's call makes of its own public calls (a blit's unlogged calls, a loop's copies) never waits. - WorkCounts: rebinds_refused_calls_in_flight (the retry rate), encoder_calls_held_by_rebind, and encoders_raced_unreplayable (raced encoders committed with no log: each fails EncodedUseRebound; zero now). Deadlock audit, extending 2465's, by lock: - `drain`: taken by a rebind waiting for the calls (no other runtime lock held: rebind_host_pages holds no lock across replace) and by a gated call's end, which holds none of the runtime's at its end. Nothing is taken under it. - `buffers`: `unopen` takes it alone to lower `open` and notify `closed` (so a waiter between its check and its wait cannot miss it); a gated call's back-off waits on `closed` under it, holding at most its render deferral's `lowerer` lock (lowerer -> buffers is the order holds already take). No publish step takes `lowerer`; the rebind's `lower_all` runs before the publish opens. - The rebind's wait for calls is bounded (2 ms), so a gated call under way that waits on a thread held at a gated begin (a render end waiting for its lowering) ends in a refusal, not a deadlock. A gated call waits only as it begins, never under way, and the publish waits for nothing an encoder holds (2465's audit), so every begin's wait ends when the open publishes close. Docs: the Safety text of Buffer::rebind_bytes_no_copy and Heap::rebind_bytes_no_copy, the rebind.rs **Other threads** bullet and RebindProblem::EncodedUses state the new outcome: refused, never failed later, for the gated kinds. api_signatures.tsv gains the three fields. Tests (src/tests/rebind_races.rs): a pause-point control (a predicated dispatch, Unlogged::Predicated, held at its hold while the main thread rebinds: the rebind refused, the command buffer completes over the old page, refused-for-calls 1); the threaded run gains a predicated family and a host-step family (an indirect stage-in region, Unlogged::Segments), and asserts encoders_raced_unreplayable == 0. Follow-up in the same landing (cc0b4592a3): Rebinds: the refusal reason carries no pages (clippy: field never read). Unreplaced::Held and Unreplaced::Calls no longer give the new pages back: replace drops them once the registry's lock went (unopen drops the guard first), as the caller's map_err dropped them before. Also the docs of the encoded-use-rebound notice (degradation.rs, docs/API.md) and the runtime README say which encoders still fail it after a race (a blit or logged render encoder whose commit failed it, or whose encoding again a call that answers otherwise refused) and that gated calls never race. Verified: m3-max-37298 (msi) clippy at ec3cbb49c7 failed on exactly these two fields; the next job checks this commit. Checks (lane rebindsafe2): clippy plain (runtime, all targets, all features) 0 at cc0b4592a3 in m3-max-37302; lavapipe rebind/detach/host-page/host-step/indirect/predication/pending/holds suites with the gated control and the six-family threaded run in m3-max-37299 (ec3cbb49c7, same library code), the gate-off negative control, clippy GPU/CPU-ICD cfgs and rustdoc follow on development. --- crates/metal2vulkan-runtime/README.md | 11 +- crates/metal2vulkan-runtime/src/blit.rs | 4 +- .../src/buffer_descriptor.rs | 10 +- .../src/command_buffer/mod.rs | 4 + .../src/command_buffer/reencode.rs | 10 + crates/metal2vulkan-runtime/src/compute.rs | 8 +- .../metal2vulkan-runtime/src/degradation.rs | 5 +- crates/metal2vulkan-runtime/src/encoder.rs | 15 +- .../metal2vulkan-runtime/src/predication.rs | 10 +- crates/metal2vulkan-runtime/src/rebind.rs | 266 +++++++++++++++--- crates/metal2vulkan-runtime/src/render.rs | 7 +- .../src/render/deferral.rs | 2 +- .../metal2vulkan-runtime/src/render/replay.rs | 4 +- .../src/tests/rebind_races.rs | 157 ++++++++++- .../metal2vulkan-runtime/src/work_counts.rs | 43 +++ crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 3 + docs/API.md | 5 +- 18 files changed, 491 insertions(+), 75 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 051548e4b..3c97eec84 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -483,10 +483,13 @@ after it, and 0 of 80 with the device dropped first 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 - commit command buffers that use the bytes during a rebind: an encoder whose call raced it is - encoded again over the new pages before its first submission, and one the runtime cannot encode - again fails `CommandBufferError::EncodedUseRebound` (`WorkCounts::encoders_raced_rebind` counts - the encoders that raced); another rebind or a detach of the same buffer or heap, a texture made + 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 + encoders the runtime may not be able to encode again (every compute encoder's, and a render + encoder's that keeps no log) never race it: the rebind waits up to 2 ms for such a call under way + and is refused past it (`EncodedUses`, counted by `WorkCounts::rebinds_refused_calls_in_flight`; + try again), and such a call that begins during the rebind waits for it; another rebind or a detach of the same buffer or heap, a texture made over its bytes and a resource placed in the heap during the call are the caller's to exclude. 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 diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 6a4b2997b..15411a4ab 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -271,7 +271,7 @@ impl BlitCommandEncoder { call: impl FnOnce(&mut CallLog) -> BlitCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { - self.core.begin_call(); + let _call = self.core.begin_call(); let _for = self.core.notices_for(); self.refuse_aborted()?; if flush { @@ -813,7 +813,7 @@ impl BlitCommandEncoder { fill_tiles: _, mut run, } = self; - core.begin_call(); + let _call = core.begin_call(); core.flush_copies(&mut run); if let Some(pattern) = pattern { core.retain(pattern); diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index ceda258df..f4f65d8b5 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -1690,10 +1690,18 @@ impl Device { // merged back from a copy of them. pages.logged_as(key); pages.copied_as(key); + // Refused where a hold refuses it, or where a call of an encoder the runtime may not + // encode again stays under way (`rebind::CallGate`): such a call reads the buffer wholly + // before the publish or wholly after it, never across it. let (old, twins, again) = shared .rebinds .replace(key, cell, Arc::clone(&pages)) - .map_err(|_| encoded())?; + .map_err(|refused| { + if let crate::rebind::Unreplaced::Calls = refused { + shared.counts.rebind_refused_calls_in_flight(); + } + encoded() + })?; // The publish is open from here to its close below, and as short as it can be: what lies // over the bytes is made over the new pages, and nothing goes, nor any deallocator runs, // until it closes (`rebind.rs`, **Other threads**). diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 62ffd5e78..c4c2bbf8a 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -4810,6 +4810,10 @@ impl CommandBuffer { if raced { self.0.mark_reencode(); } + let raced_unlogged = state.raced_unreplayable(); + if raced_unlogged > 0 { + (device.shared().counts).encoders_raced_unreplayable(raced_unlogged); + } if let Some(slot) = lock(&self.0.slot).as_mut() { slot.committed(); } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index b41cb36bc..ac86ecfef 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -884,6 +884,16 @@ impl State { (self.ended.iter()).any(|record| record.taken.raced() && record.replay.is_some()) } + /// As it commits, once its replays are kept: how many encoders a call of which raced a + /// rebind kept no log (`WorkCounts::encoders_raced_unreplayable`), each failing + /// `EncodedUseRebound` at its submission. None where every encoder that may keep none had its + /// calls gated (`rebind::CallGate`). + pub(super) fn raced_unreplayable(&self) -> usize { + (self.ended.iter()) + .filter(|record| record.taken.raced() && record.replay.is_none()) + .count() + } + /// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder /// whose pass took a rasterization-rate map since reset, before the commit, is to be encoded /// again before its first submission, its log kept (`rate_mapped_pass.rs`); and why each that diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index f02ae6202..ddace12eb 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -313,6 +313,10 @@ impl CommandBuffer { (opened.boxed(), live) } }; + // A record of command predication of its unit, or a dispatch it leaves to its host step, + // may leave it one the runtime cannot encode again, though its calls before were + // encoded: its calls no rebind's publish overlaps (`rebind::CallGate`). + core.gate_calls(); // The laying of a loop open across its start goes on in a command buffer of its own, which // the loop's check may submit again (`predication.rs`). if !carried.is_empty() && self.state().predication.laying() { @@ -400,7 +404,7 @@ impl ComputeCommandEncoder { call: impl FnOnce(&mut CallLog) -> ComputeCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { - self.core.begin_call(); + let _call = self.core.begin_call(); let _for = self.core.notices_for(); let at = self.log(call); let ran = run(self); @@ -1707,7 +1711,7 @@ impl ComputeCommandEncoder { /// `endEncoding`. What it binds is held until the command buffer completes, as Metal holds /// what an encoder was handed. pub fn end_encoding(mut self) -> Result<(), Error> { - self.core.begin_call(); + let _call = self.core.begin_call(); let _for = self.core.notices_for(); // Its unit of command predication takes what it encoded (`predication.rs`): as its core // ends, under the one lock that takes, where its command buffer has no record. diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 2a63daa5d..982d15674 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1713,7 +1713,10 @@ degradations! { /// encoded and before the command buffer was first submitted, or that a rebind on another /// thread raced the command's encoding of (its call held the buffer while the rebind was /// making what lies over its bytes again, or after, having begun before: `rebind.rs`'s - /// **Other threads**, `WorkCounts::encoders_raced_rebind`) + /// **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) /// (`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/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 5dd9291dc..0c46e3d7c 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -74,7 +74,7 @@ use super::noted_apart::{Moved, NotedApart, NotedInto}; use super::pass_runs::RunKeep; use super::pending_dispatch::PendingDispatch; use super::pipeline::VariantObjects; -use super::rebind::{Holds, Taken}; +use super::rebind::{CallGate, Holds, Taken}; use super::render::face_swap::Turns; use super::render_target::PassKey; use super::replay::Replay; @@ -2349,9 +2349,16 @@ impl EncoderCore { /// The encoder's next call begins (a logged call, a render encoder's lowered call, an end), /// before it reads anything of a buffer over host pages: a hold in it of a buffer whose /// rebind's publish closed since, or is open, finds the call raced that rebind - /// (`Holds::begin_call`). One load. - pub(super) fn begin_call(&mut self) { - self.holds.begin_call(); + /// (`Holds::begin_call`). One load, and for an encoder whose calls are gated the call counted + /// under way while the answer lives (`rebind::CallGate`): the caller keeps it until it returns. + pub(super) fn begin_call(&mut self) -> CallGate { + self.holds.begin_call() + } + + /// Gate the encoder's calls from its next on (`rebind::CallGate`): one the runtime may not + /// encode again over a buffer's new pages, whose calls no rebind's publish overlaps. + pub(super) fn gate_calls(&mut self) { + self.holds.gate_calls(); } /// The encoder's call begins as one began at `call` (`Rebinds::call_begins`): a render diff --git a/crates/metal2vulkan-runtime/src/predication.rs b/crates/metal2vulkan-runtime/src/predication.rs index 12988cb18..1116684da 100644 --- a/crates/metal2vulkan-runtime/src/predication.rs +++ b/crates/metal2vulkan-runtime/src/predication.rs @@ -2010,7 +2010,7 @@ impl ComputeCommandEncoder { /// for the End that closes that block; with no block open it is an unbalanced record, /// answering `NO` (the module docs). pub fn encode_end_if(&mut self) -> Result { - self.core().begin_call(); + let _call = self.core().begin_call(); let _for = self.core().notices_for(); let at = self.log(|_| ComputeCall::EndIf(false)); let result = self.encode_end_if_uncounted(); @@ -2052,7 +2052,7 @@ impl ComputeCommandEncoder { comparison: u64, reference_value: u32, ) -> Result<(), Error> { - self.core().begin_call(); + let _call = self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_start_while_uncounted(buffer, offset, comparison, reference_value); @@ -2090,7 +2090,7 @@ impl ComputeCommandEncoder { /// run, and again while that End's condition holds after each run, as /// [`encode_start_while`](Self::encode_start_while)'s run, laid down as there. pub fn encode_start_do_while(&mut self) -> Result<(), Error> { - self.core().begin_call(); + let _call = self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_start_do_while_uncounted(); @@ -2107,7 +2107,7 @@ impl ComputeCommandEncoder { /// block it kills the outermost open block and answers `NO`; with no block open it is an /// unbalanced record, answering `NO` (the module docs). pub fn encode_end_while(&mut self) -> Result { - self.core().begin_call(); + let _call = self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_end_while_uncounted(); @@ -2137,7 +2137,7 @@ impl ComputeCommandEncoder { comparison: u64, reference_value: u32, ) -> Result { - self.core().begin_call(); + let _call = self.core().begin_call(); let _for = self.core().notices_for(); self.stop_logging(); let result = diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index a8635315c..3dc6978ea 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -60,17 +60,26 @@ //! it read of the buffer before its hold may be the old pages' (`Taken::raced`, counted by //! `WorkCounts::encoders_raced_rebind`). Such an encoder runs only encoded again over the new //! pages, after the publish closed: by its commit, in the commit's call, or by the rebind's call -//! where it committed while the publish was open. An encoder the runtime cannot encode again -//! whose call raced a rebind fails `CommandBufferError::EncodedUseRebound` at its submission, -//! announced (`encoded-use-rebound`): a compute encoder its unit of command predication reaches -//! past, one that left a GPU-written indirect dispatch to its host step, a blit or render encoder -//! opened while the device had no buffer over host pages, an encoder whose command buffer's -//! commit fails it, and one with a call that answers otherwise than at its encoding +//! where it committed while the publish was open. That holds for blit encoders and for render +//! encoders that keep a log. The calls of the encoders the runtime may not encode again are +//! gated instead, so none races a rebind ([`CallGate`]): every compute encoder's (its unit's +//! records of command predication, or a dispatch it leaves to its host step, a GPU-written +//! indirect one among them, can leave it one the runtime cannot encode again, from the call that +//! makes it so or one of a later encoder of its unit), and a render encoder's that opened while +//! the device had no buffer over host pages, which keeps no log. A rebind opens its publish just +//! before its replace, once no such call is under way, and each such call that begins while one +//! is open waits for it to close before it reads anything (one sequentially consistent +//! handshake of two counts, [`Rebinds::quiet_calls`]): so each reads the buffer wholly before +//! the publish, holding it, which refuses a rebind until its command buffer commits, or wholly +//! after it. A rebind that waited 2 ms for such a call still under way (one waiting for a +//! `VkPipeline` being made, say) is refused (`EncodedUses`, counted by +//! `WorkCounts::rebinds_refused_calls_in_flight`), never the encoder failed later; the caller may +//! try again. Nothing waits for that rebind: a call under way never waits for one, and a call +//! that waits does so as it begins. A blit or logged render encoder whose call raced still fails +//! `CommandBufferError::EncodedUseRebound` at its submission where its command buffer's commit +//! fails it, or a call that answers otherwise than at its encoding refuses its encoding again //! (`command_buffer/rebound_use.rs`; a resource state encoder takes no pages, so races none). A -//! rebind no encode of the buffer overlaps changes nothing for them: every call either held the -//! buffer before the rebind, which refuses it (`EncodedUses`), or began after its publish closed -//! and reads the new pages. A commit and a submission order against the rebind under `buffers`' -//! lock as above. Another rebind of the same buffer or heap whose publish is open is refused +//! commit and a submission order against the rebind under `buffers`' lock as above. Another rebind of the same buffer or heap whose publish is open is refused //! (`EncodedUses`); a rebind or detach of it on another thread, a texture made over its bytes and //! a resource placed in the heap during the call stay the caller's to exclude //! (`Buffer::rebind_bytes_no_copy`'s **Safety**). @@ -118,9 +127,11 @@ use super::rate_map::{MapState, RasterizationRateMap}; use super::resource::{ObjectId, ResourceKey}; use super::Device; use std::any::Any; +use std::cell::Cell; use std::collections::BTreeSet; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak}; +use std::time::{Duration, Instant}; /// What `rebind_bytes_no_copy` refuses as Metal's validation would a misuse (`Invalid`). #[non_exhaustive] @@ -135,7 +146,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. + /// the GPU alone): commit or drop it first, or wait for its completion. 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. EncodedUses, } @@ -176,11 +190,23 @@ pub(super) struct Rebinds { /// publish closed past that, or is open, finds the call raced it (the module docs, **Other /// threads**). published: AtomicU64, - /// How many rebinds' publishes are open ([`Rebinds::replace`] to [`Rebinds::published`]). + /// How many rebinds' publishes are open ([`Rebinds::replace`] to [`Rebinds::published`]), + /// each from just before its replace, as it lets the gated calls under way end + /// ([`Rebinds::quiet_calls`]). open: AtomicUsize, - /// Signaled as a rebind closes its publish: an encoding again that raced one waits for none - /// to be open before it encodes again (`CommandBufferShared::reencode`). + /// Signaled as a rebind closes its publish, or gives up opening one: an encoding again that + /// raced one waits for none to be open before it encodes again + /// (`CommandBufferShared::reencode`), and so does a gated call before it begins + /// ([`CallGate`]). closed: Condvar, + /// How many gated calls are under way ([`CallGate`]): the calls of encoders the runtime may + /// not encode again, which no publish overlaps (the module docs, **Other threads**). With + /// `open`, the two sides of one sequentially consistent handshake. + calls: AtomicUsize, + /// Held as a rebind waits for the gated calls under way to end ([`Rebinds::quiet_calls`]), + /// and as the last of them signals `drained`. + drain: Mutex<()>, + drained: Condvar, } /// The command buffers waiting for the submission of an event group whose encoders a rebind @@ -408,7 +434,7 @@ impl Rebinds { // count. super::buffer::host_cells_settled(); entry.published = self.published.fetch_add(1, Ordering::AcqRel) + 1; - self.open.fetch_sub(1, Ordering::AcqRel); + self.open.fetch_sub(1, Ordering::SeqCst); #[cfg(debug_assertions)] PUBLISHES_OPEN.fetch_sub(1, Ordering::AcqRel); let again = self.mark_waiting(key); @@ -430,6 +456,74 @@ impl Rebinds { } } + /// Open a publish ahead of its replace, once the gated calls under way ended ([`CallGate`]): + /// from the count's rise every gated call that begins waits for the publish to close, so + /// those under way end, which this waits for, up to [`CALLS_DRAIN`]. A call held past it + /// (one waiting for a `VkPipeline` being made, say) refuses the rebind instead: `false`, + /// nothing opened, the waiting calls let go. Its wait holds no lock of the runtime's, and a + /// gated call's end takes `drain` alone, so the wait ends within its bound whatever the call + /// under way waits for. + /// + /// The handshake with [`Rebinds::enter_call`]: each side writes its count, then reads the + /// other's, all four sequentially consistent, so of a rebind and a call that meet at least one + /// reads the other's rise. A call that reads `open` raised backs off before it reads anything + /// of a buffer over host pages; a rebind that reads `calls` raised waits for it to fall. + fn quiet_calls(&self) -> bool { + self.open.fetch_add(1, Ordering::SeqCst); + if self.calls.load(Ordering::SeqCst) == 0 { + return true; + } + let deadline = Instant::now() + CALLS_DRAIN; + let mut drain = lock(&self.drain); + while self.calls.load(Ordering::SeqCst) > 0 { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + drop(drain); + self.unopen(lock(&self.buffers)); + return false; + } + drain = match self.drained.wait_timeout(drain, left) { + Ok((drain, _)) => drain, + Err(poisoned) => poisoned.into_inner().0, + }; + } + true + } + + /// A publish [`quiet_calls`](Self::quiet_calls) opened closes unpublished (its rebind + /// refused, or its buffer not one of `buffers`, whose lock the caller hands in): the gated + /// calls and encodings again waiting for it go on. + fn unopen(&self, buffers: MutexGuard<'_, KeyMap>) { + self.open.fetch_sub(1, Ordering::SeqCst); + drop(buffers); + self.closed.notify_all(); + } + + /// A gated call begins ([`CallGate`]): counted under way, once no publish is open, waiting + /// for each open one to close first ([`Rebinds::wait_published`]). Whether it waited. Its + /// caller reads nothing of a buffer over host pages before. + fn enter_call(&self) -> bool { + let mut waited = false; + loop { + self.calls.fetch_add(1, Ordering::SeqCst); + if self.open.load(Ordering::SeqCst) == 0 { + return waited; + } + self.leave_call(); + waited = true; + self.wait_published(); + } + } + + /// A gated call ends ([`CallGate`]): a rebind waiting for the calls under way hears it. + fn leave_call(&self) { + self.calls.fetch_sub(1, Ordering::SeqCst); + if self.open.load(Ordering::SeqCst) > 0 { + let _drain = lock(&self.drain); + self.drained.notify_all(); + } + } + /// Mark each command buffer waiting for the submission of an event group whose replayable /// encoders or work on the GPU alone named the buffer of `key` to encode or record them again /// before that submission (`CommandBufferShared::reencode`), each once, for the caller to run @@ -629,28 +723,34 @@ impl Rebinds { } /// Give the buffer of `key`, whose hold on its pages is `cell`, `pages` from now on, unless - /// a hold refuses it: where it lay (a detached one is attached again), the read twins it let + /// a hold refuses it, or a gated call under way ([`Rebinds::quiet_calls`]): where it lay (a detached one is attached again), the read twins it let /// go of, which the caller drops without this lock ([`LeftTwins`]), and the command /// buffers waiting for the submission of an event group whose replayable encoders or work on /// the GPU alone named it ([`Rebinds::wait_for_replay`]), each marked under this lock to /// encode or record them again before that submission (`CommandBufferShared::reencode`), which - /// the caller runs; `Err` gives `pages` back. Its publish is open from here until the caller - /// closes it ([`Rebinds::published`]). + /// the caller runs; `Err` says why, `pages` dropped once this lock went. Its publish is open + /// from here until the caller closes it ([`Rebinds::published`]). pub(super) fn replace( &self, key: ResourceKey, cell: &HostCell, pages: Arc, - ) -> Result<(Lying, LeftTwins, Vec>), Arc> { + ) -> Result<(Lying, LeftTwins, Vec>), Unreplaced> { + // The publish opens before the lock, once no gated call is under way: none overlaps it. + if !self.quiet_calls() { + return Err(Unreplaced::Calls); + } let mut buffers = lock(&self.buffers); let Some(entry) = buffers.get_mut(&key) else { let (lying, twins) = cell.replace(Lying::In(pages)); + self.unopen(buffers); return Ok((lying, twins, Vec::new())); }; // A rebind of it on another thread whose publish is open refuses this one as a hold does, // where the caller's contract has none (`Buffer::rebind_bytes_no_copy`). if entry.pending > 0 || entry.publishing { - return Err(pages); + self.unopen(buffers); + return Err(Unreplaced::Held); } if entry.detached { entry.detached = false; @@ -658,9 +758,9 @@ impl Rebinds { } // No command buffer made the new pages resident yet. entry.resident = false; - // What lies over the bytes is the old pages' until the publish closes. + // What lies over the bytes is the old pages' until the publish closes, which `open` + // counts from `quiet_calls`. entry.publishing = true; - self.open.fetch_add(1, Ordering::AcqRel); #[cfg(debug_assertions)] PUBLISHES_OPEN.fetch_add(1, Ordering::AcqRel); let (lying, twins) = cell.replace(Lying::In(pages)); @@ -673,7 +773,79 @@ impl Rebinds { } /// How often a detach waiting for submitted command buffers looks whether the device was lost. -const LOST_POLL: std::time::Duration = std::time::Duration::from_millis(20); +const LOST_POLL: Duration = Duration::from_millis(20); + +/// How long a rebind waits for the gated calls under way to end before it refuses +/// ([`Rebinds::quiet_calls`]): an encoder call takes microseconds, so a call still under way +/// past this waits for something else (a `VkPipeline` being made, a lock another thread holds). +const CALLS_DRAIN: Duration = Duration::from_millis(2); + +/// Why [`Rebinds::replace`] refused: as `RebindProblem::EncodedUses` both. +pub(super) enum Unreplaced { + /// A hold of an encoder or a command buffer not yet committed, or another rebind's open + /// publish. + Held, + /// A gated call under way that did not end within [`CALLS_DRAIN`] ([`CallGate`]). + Calls, +} + +thread_local! { + /// How deep this thread is in gated calls ([`CallGate`]): a call an encoder's call makes of + /// its own public calls (a blit's `unlogged`, a loop's copies) is under way already. + static GATED: Cell = const { Cell::new(0) }; +} + +/// A call of an encoder whose calls are gated ([`Holds::gate_calls`]): counted under way while it +/// lives, so no rebind's publish overlaps it ([`Rebinds::quiet_calls`]). Such an encoder is one the +/// runtime may not encode again over the new pages (the module docs, **Other threads**): a compute +/// encoder, any of which a record of command predication of its unit, or a dispatch it leaves to +/// a host step, may make one, and a render encoder that keeps no log. Every call of such an encoder +/// reads where the buffer lay wholly before a publish, or wholly after its close: none raced a +/// rebind, so none fails `EncodedUseRebound` for one. Free where the device has no buffer over host +/// pages, and for every other encoder. +#[must_use = "the call is under way while it lives"] +pub(super) enum CallGate { + /// Not gated. + Free, + /// Inside a gated call of this thread's. + Nested, + /// Counted under way on the device. + Entered(Device), +} + +impl CallGate { + /// A gated call of an encoder of `device` begins, before it reads anything of a buffer over + /// host pages. + fn enter(device: &Device) -> CallGate { + let depth = GATED.get(); + if depth > 0 { + GATED.set(depth + 1); + return CallGate::Nested; + } + let shared = device.shared(); + if !shared.rebinds.any() { + return CallGate::Free; + } + GATED.set(1); + if shared.rebinds.enter_call() { + shared.counts.encoder_call_held_by_rebind(); + } + CallGate::Entered(device.clone()) + } +} + +impl Drop for CallGate { + fn drop(&mut self) { + match self { + CallGate::Free => {} + CallGate::Nested => GATED.set(GATED.get() - 1), + CallGate::Entered(device) => { + GATED.set(GATED.get() - 1); + device.shared().rebinds.leave_call(); + } + } + } +} /// The buffers over host pages, locked as a command buffer's batch is submitted /// (`Rebinds::submitting`): each `Taken` is judged against where its buffers lie now and its @@ -849,6 +1021,8 @@ pub(super) struct Holds { /// Self::begin_call)), or as the holds were made: a hold or pin in the call finds whether /// the call raced a rebind of what it takes against it. call: u64, + /// Its encoder's calls are gated ([`CallGate`]). + gates: bool, } impl Holds { @@ -860,15 +1034,28 @@ impl Holds { device: device.clone(), keys: Vec::new(), call: device.shared().rebinds.call_begins(), + gates: false, } } + /// 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) { + self.gates = true; + } + /// The encoder's next call begins, before it reads anything of a buffer over host pages (an - /// encoder's logged call, a render encoder's lowered one, an end): one load. - pub(super) fn begin_call(&mut self) { + /// encoder's logged call, a render encoder's lowered one, an end): one load, and for a gated + /// encoder's the call counted under way, which the caller keeps until the call returns. + pub(super) fn begin_call(&mut self) -> CallGate { + let gate = match self.gates { + true => CallGate::enter(&self.device), + false => CallGate::Free, + }; #[cfg(debug_assertions)] CALL_MOVED.set(super::buffer::host_cells_moved()); self.call = self.device.shared().rebinds.call_begins(); + gate } /// The encoder's call begins as one began at `call` ([`Rebinds::call_begins`]): a render @@ -1285,16 +1472,19 @@ impl Buffer { /// thread rebinds or detaches the buffer, or makes a texture over its bytes, during the call. /// /// Other threads may encode and commit command buffers that use the buffer during the call. - /// An encoder whose call raced it (held the buffer while the call was making what lies over - /// its bytes again, or after, having begun before) is encoded again over the new memory before - /// its first submission, where the runtime can encode it again (the module docs of `rebind.rs`, - /// **Other threads**, counted by `WorkCounts::encoders_raced_rebind`); one it cannot fails - /// `CommandBufferError::EncodedUseRebound` at that submission: a compute encoder its unit of - /// command predication reaches past, one that left a GPU-written indirect dispatch to its host - /// step, a blit or render encoder opened while the device had no buffer over host pages, an - /// encoder whose command buffer's commit fails it, and one with a call that answers otherwise - /// than at its encoding. A call with no concurrent encode of the buffer changes nothing for - /// them. + /// A blit encoder's, or a render encoder's that keeps a log, whose call raced it (held the + /// buffer while the call was making what lies over its bytes again, or after, having begun + /// before) is encoded again over the new memory before its first submission (the module docs + /// of `rebind.rs`, **Other threads**, counted by `WorkCounts::encoders_raced_rebind`); it + /// fails `CommandBufferError::EncodedUseRebound` at that submission only where its command + /// buffer's commit fails it, or a call that answers otherwise than at its encoding refuses its + /// encoding again. The calls of the encoders the runtime may not encode again (every compute + /// encoder's, its predicated ones and those with a GPU-written indirect dispatch among them, + /// and a render encoder's that opened while the device had no buffer over host pages) never + /// race it: the call waits up to 2 ms for such a call under way to end, and is refused + /// otherwise (`Invalid`, [`RebindProblem::EncodedUses`], counted by + /// `WorkCounts::rebinds_refused_calls_in_flight`), never failing that encoder later; such a + /// call that begins during it waits for it, so it reads the old memory or the new one, whole. pub unsafe fn rebind_bytes_no_copy( &self, memory: HostMemory, @@ -1359,9 +1549,9 @@ impl Heap { /// of the heap and its resources: no other thread rebinds the heap, detaches one of its /// resources' bytes, or places a resource in it, during the call. Other threads may encode and /// commit command buffers that use the heap or its resources during the call, with the outcomes - /// [`Buffer::rebind_bytes_no_copy`]'s **Safety** names, `EncodedUseRebound` for an encoder the - /// runtime cannot encode again whose call raced it, and none of them where no encode overlaps - /// the call. + /// [`Buffer::rebind_bytes_no_copy`]'s **Safety** names: an encoder the runtime may not encode + /// again never races it, its call under way refusing the rebind (`EncodedUses`) where it does + /// not end within 2 ms, and a blit or logged render encoder that raced it is encoded again. pub unsafe fn rebind_bytes_no_copy( &self, memory: HostMemory, diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index e6a551ea2..7f11f766b 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -2234,7 +2234,7 @@ impl Lowering { /// its kept draw carried into its command buffer's next render encoder where it carries /// (`render/carried.rs`). pub(crate) fn end_encoding(mut self) -> Result<(), Error> { - self.core.begin_call(); + let _call = self.core.begin_call(); let _for = self.core.notices_for(); self.ending_carried().end_encoding() } @@ -2382,6 +2382,11 @@ impl CommandBuffer { } .boxed(); core.begun_at(begun); + // An encoder that keeps no log is not encoded again: its calls no rebind's publish + // overlaps (`rebind::CallGate`). + if again.is_none() && log.is_none() { + core.gate_calls(); + } // A color's texture with faces that the pass renders whole without loading it turns to // its other face here, before anything of the pass names its image; the kept draw the // last render encoder carried bound the face presented before (`render/face_swap.rs`). diff --git a/crates/metal2vulkan-runtime/src/render/deferral.rs b/crates/metal2vulkan-runtime/src/render/deferral.rs index 81f6d6fb8..2b60e4ab7 100644 --- a/crates/metal2vulkan-runtime/src/render/deferral.rs +++ b/crates/metal2vulkan-runtime/src/render/deferral.rs @@ -793,7 +793,7 @@ impl RenderCommandEncoder { pub(crate) fn at_call_unit(&mut self, f: impl FnOnce(&mut Lowering)) { self.next += 1; let lowered = |lowering: &mut Lowering| { - lowering.core.begin_call(); + let _call = lowering.core.begin_call(); let _for = lowering.core.notices_for(); f(lowering); }; diff --git a/crates/metal2vulkan-runtime/src/render/replay.rs b/crates/metal2vulkan-runtime/src/render/replay.rs index 8d7c5239f..37a4e2490 100644 --- a/crates/metal2vulkan-runtime/src/render/replay.rs +++ b/crates/metal2vulkan-runtime/src/render/replay.rs @@ -731,7 +731,7 @@ impl Lowering { &mut self, run: impl FnOnce(&mut Lowering) -> Result, ) -> Result { - self.core.begin_call(); + let _call = self.core.begin_call(); let _for = self.core.notices_for(); let at = self.log.as_ref().map(|log| log.calls.calls.len()); let ran = run(self); @@ -776,7 +776,7 @@ pub(super) fn render( use Table as T; // Each call begins before it reads anything of a buffer over host pages (`rebind.rs`, **Other // threads**). - encoder.core.begin_call(); + let _call = encoder.core.begin_call(); match call { C::PipelineState(state) => encoder.set_render_pipeline_state(log.render_state(*state)), C::Buffer(table, buffer, offset, index) => { diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_races.rs b/crates/metal2vulkan-runtime/src/tests/rebind_races.rs index 04fbb8a85..7cdf8762b 100644 --- a/crates/metal2vulkan-runtime/src/tests/rebind_races.rs +++ b/crates/metal2vulkan-runtime/src/tests/rebind_races.rs @@ -11,13 +11,25 @@ //! the texture over its bytes has its image made over them (`Point::Publishing`), while a //! dispatch on another thread reads the texture: the dispatch's hold finds the publish open, //! and the commit, after the publish closed, encodes the encoder again over the new image. -//! - **Threads.** Four threads encode and commit command buffers whose commands read the buffer, +//! - **A call the runtime cannot encode again.** A dispatch inside an If its command buffer's +//! encoder before opened (`Unlogged::Predicated`: no rebind encodes its encoder again) held at +//! its hold of the buffer while the main thread rebinds it: its call is gated +//! (`rebind::CallGate`), so the rebind waits for it, then is refused (`EncodedUses`, +//! `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`. +//! - **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, and a dispatch it was bound to a call before (the dispatch's bind -//! state reuses nothing a move changed, `buffer::host_cells_moved`). A fifth thread rebinds it +//! a blit copying from it, a dispatch it was bound to a call before (the dispatch's bind +//! state reuses nothing a move changed, `buffer::host_cells_moved`), that dispatch inside an If +//! the encoder before opened, and that dispatch left to its host step (an indirect stage-in +//! region set: a dispatch whose GPU-written region a host step reads once the work before it +//! 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`. +//! 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`). //! 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 @@ -145,13 +157,21 @@ enum Family { BlitCopy, /// `scale_and_offset` reads it, bound a call before the dispatch. BoundBefore, + /// As `BoundBefore`, the dispatch inside an If (that holds) the encoder before opened: the + /// runtime cannot encode its encoder again (`Unlogged::Predicated`). + Predicated, + /// As `BoundBefore`, the dispatch left to its host step by an indirect stage-in region: the + /// runtime cannot encode its encoder again (`Unlogged::Segments`). + HostStep, } -const FAMILIES: [Family; 4] = [ +const FAMILIES: [Family; 6] = [ Family::TextureRead, Family::VertexBuffer, Family::BlitCopy, Family::BoundBefore, + Family::Predicated, + Family::HostStep, ]; /// The states, and the objects of the device's own, the families' commands use. @@ -161,6 +181,10 @@ struct Fixtures { draw: RenderPipelineState, scale_bytes: Buffer, positions: Buffer, + /// The word a predicated family's If tests: 0, so the If holds. + word: Buffer, + /// The host-step family's indirect stage-in region: origin 0, size [`COUNT`] by 1 by 1. + region: Buffer, } impl Fixtures { @@ -190,6 +214,15 @@ impl Fixtures { ResourceOptions::shared(), ) .unwrap(), + word: device + .new_buffer_with_bytes(&0u32.to_le_bytes(), ResourceOptions::shared()) + .unwrap(), + region: device + .new_buffer_with_bytes( + &bytes_of(&[0, 0, 0, COUNT as u32, 1, 1], u32::to_le_bytes), + ResourceOptions::shared(), + ) + .unwrap(), } } } @@ -240,7 +273,7 @@ fn expected(family: Family, tag: usize) -> Vec { vec![u32::from_le_bytes([code; 4]); (TARGET * TARGET) as usize] } Family::BlitCopy => vec![word; (COPIED / 4) as usize], - Family::BoundBefore => (0..COUNT) + Family::BoundBefore | Family::Predicated | Family::HostStep => (0..COUNT) .map(|i| (value(tag) * SCALE + i as f32).to_bits()) .collect(), } @@ -322,11 +355,24 @@ fn encode( blit.end_encoding().unwrap(); Output::Buffer(out) } - Family::BoundBefore => { + Family::BoundBefore | Family::Predicated | Family::HostStep => { let out = device .new_buffer(COUNT * 4, ResourceOptions::shared()) .unwrap(); + if family == Family::Predicated { + // Comparison 0: `word == reference`, which holds. + let mut opening = command_buffer.compute_command_encoder().unwrap(); + opening + .encode_start_if(Some(&fixtures.word), 0, 0, 0) + .unwrap(); + opening.end_encoding().unwrap(); + } let mut encoder = command_buffer.compute_command_encoder().unwrap(); + if family == Family::HostStep { + encoder + .set_stage_in_region_indirect(&fixtures.region, 0) + .unwrap(); + } // Bound in its own call, before the state and the dispatch. encoder.set_buffer(Some(buffer), 0, 0).unwrap(); encoder.set_compute_pipeline_state(&fixtures.scale).unwrap(); @@ -337,6 +383,9 @@ fn encode( encoder .dispatch_threads(Size::new(COUNT, 1, 1), Size::new(COUNT, 1, 1)) .unwrap(); + if family == Family::Predicated { + assert!(encoder.encode_end_if().unwrap(), "the If ends"); + } encoder.end_encoding().unwrap(); Output::Buffer(out) } @@ -466,6 +515,80 @@ fn a_dispatch_that_read_a_texture_over_the_buffer_during_its_publish_runs_over_t assert_eq!(raced, 1, "the encoder that raced the rebind"); } +/// A dispatch inside an If the encoder before opened, which no rebind can encode again, held at +/// its hold of the buffer, after it read the buffer's pages, while the main thread rebinds the +/// buffer: its call is under way, so the rebind waits for it, then is refused, and the dispatch +/// reads the pages it was encoded over, its command buffer completing. +#[test] +fn a_rebind_during_a_call_of_an_encoder_it_cannot_encode_again_is_refused() { + let scratch = Scratch::new("rebind-races-gated"); + 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 (reached, go) = pause::arm(Point::Holding, buffer.identity().key); + let (output, command_buffer, rebound) = std::thread::scope(|scope| { + let encoding = scope.spawn(|| { + let command_buffer = queue.command_buffer().unwrap(); + let output = encode( + Family::Predicated, + &device, + &fixtures, + &command_buffer, + (&buffer, &over_texture), + ); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + (output, command_buffer) + }); + reached + .recv_timeout(WAIT) + .expect("the dispatch reached its hold"); + let rebound = rebind(&buffer, &pages[1]); + go.send(()).unwrap(); + let (output, command_buffer) = encoding.join().unwrap(); + (output, command_buffer, rebound) + }); + let after = device.work_counts(); + let grew = |of: fn(&crate::WorkCounts) -> u64| of(&after) - of(&before); + println!( + "REBIND-RACES gated: rebind {rebound:?}; {:?} {:?}; {} refused for a call under way, {} \ + raced, {} raced unreplayable", + command_buffer.status(), + command_buffer.error(), + grew(|counts| counts.rebinds_refused_calls_in_flight), + grew(|counts| counts.encoders_raced_rebind), + grew(|counts| counts.encoders_raced_unreplayable), + ); + assert_eq!( + rebound, + Err(encoded_uses), + "the rebind during the gated call" + ); + 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_calls_in_flight), 1); + assert_eq!(grew(|counts| counts.encoders_raced_rebind), 0); + // Once the command buffer completed, the rebind goes. + rebind(&buffer, &pages[1]).expect("the rebind after the completion"); +} + /// What one command buffer of the threaded run came to. #[derive(Debug)] enum Seen { @@ -477,9 +600,10 @@ enum Seen { Wrong(String), } -/// Four threads encoding and committing command buffers that read the buffer, a family each, -/// while a fifth rebinds it to fresh pages: every output is wholly one page's, of a page the -/// buffer lay in meanwhile, or its command buffer failed `EncodedUseRebound`. +/// Six threads encoding and committing command buffers that read the buffer, a family each, +/// while a seventh rebinds it to fresh pages: every output is wholly one page's, of a page the +/// buffer lay in meanwhile, or its command buffer failed `EncodedUseRebound`, and no encoder the +/// runtime cannot encode again raced a rebind. #[test] fn encoders_on_other_threads_read_wholly_one_page_of_a_buffer_rebound_meanwhile() { let scratch = Scratch::new("rebind-races-threads"); @@ -587,9 +711,13 @@ 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); {} encoders \ - raced a rebind, {} encoded again, {} refused encoding again", + "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, \ + {} of them unreplayable, {} encoded again, {} refused encoding again", + grew(|counts| counts.rebinds_refused_calls_in_flight), + grew(|counts| counts.encoder_calls_held_by_rebind), grew(|counts| counts.encoders_raced_rebind), + grew(|counts| counts.encoders_raced_unreplayable), grew(|counts| counts.encoders_reencoded), grew(|counts| counts.reencodes_refused), ); @@ -601,5 +729,10 @@ 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:?}"); + assert_eq!( + grew(|counts| counts.encoders_raced_unreplayable), + 0, + "encoders that raced a rebind and fail EncodedUseRebound for it" + ); assert!(made > 0, "no rebind was made"); } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index d541688b4..b0926dd4c 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -787,6 +787,9 @@ pub(crate) struct Counters { replay_tables_pointed: AtomicU64, reencodes_refused: AtomicU64, encoders_raced_rebind: AtomicU64, + encoders_raced_unreplayable: AtomicU64, + rebinds_refused_calls_in_flight: AtomicU64, + encoder_calls_held_by_rebind: AtomicU64, pipeline_libraries_made: AtomicU64, fragment_shader_libraries_made: AtomicU64, pipelines_linked: AtomicU64, @@ -6157,6 +6160,24 @@ impl Counters { self.encoders_raced_rebind.fetch_add(1, Ordering::Relaxed); } + /// `count` encoders a call of which raced a rebind committed, the runtime unable to encode + /// them again: each fails `EncodedUseRebound` (`rebind.rs`, **Other threads**). + pub(crate) fn encoders_raced_unreplayable(&self, count: usize) { + (self.encoders_raced_unreplayable).fetch_add(count as u64, Ordering::Relaxed); + } + + /// A rebind was refused (`EncodedUses`) for a gated encoder call still under way past its + /// bound (`rebind::CallGate`). + pub(crate) fn rebind_refused_calls_in_flight(&self) { + (self.rebinds_refused_calls_in_flight).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) { + (self.encoder_calls_held_by_rebind).fetch_add(1, Ordering::Relaxed); + } + /// A new image was moved to `GENERAL` and zeroed on the host (`texture/host_copy.rs`). pub(crate) fn image_started_on_the_host(&self) { self.images_started_on_the_host @@ -11830,6 +11851,22 @@ pub struct WorkCounts { /// encodes the encoder again over the new pages, and one that cannot be encoded again fails /// `EncodedUseRebound`. Zero where no encoder races a rebind. pub encoders_raced_rebind: u64, + /// Of those, the encoders committed that the runtime could not encode again, each failing + /// `EncodedUseRebound`: zero, as the calls of every encoder that may be one are gated, so no + /// rebind's publish overlaps them (`rebind.rs`, **Other threads**). A count past zero is a + /// defect. + pub encoders_raced_unreplayable: u64, + /// Rebinds refused (`RebindProblem::EncodedUses`) because a call of an encoder the runtime + /// may not encode again (a compute encoder's, or a render encoder's that keeps no log) on + /// another thread was still under way 2 ms after the rebind asked to go on: the call reads + /// the buffer wholly before the rebind or wholly after it, so the rebind gives way. Zero + /// 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, + /// 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. + pub encoder_calls_held_by_rebind: u64, /// Fences made to end command buffers, where none was idle (`command_buffer/fences.rs`): /// none on a driver that reads no command buffer's objects after its value, whose queues' /// failures are not relayed. @@ -13651,6 +13688,12 @@ impl Device { replay_tables_pointed: counters.replay_tables_pointed.load(Ordering::Relaxed), reencodes_refused: counters.reencodes_refused.load(Ordering::Relaxed), encoders_raced_rebind: counters.encoders_raced_rebind.load(Ordering::Relaxed), + encoders_raced_unreplayable: (counters.encoders_raced_unreplayable) + .load(Ordering::Relaxed), + rebinds_refused_calls_in_flight: (counters.rebinds_refused_calls_in_flight) + .load(Ordering::Relaxed), + encoder_calls_held_by_rebind: (counters.encoder_calls_held_by_rebind) + .load(Ordering::Relaxed), fences_made: self.shared().fences.made(), pipeline_libraries_made: counters.pipeline_libraries_made.load(Ordering::Relaxed), fragment_shader_libraries_made: counters diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index de17e4ddc..0f5dd1591 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 = 2467; +pub const RUNTIME_VERSION: u32 = 2468; /// 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 f889e6a34..f6064f4ff 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3055,6 +3055,7 @@ field metal2vulkan-runtime::WorkCounts.draws_unlike_kept_tessellation pub draws_ field metal2vulkan-runtime::WorkCounts.draws_unlike_kept_under pub draws_unlike_kept_under: u64 field metal2vulkan-runtime::WorkCounts.driver_diagnostics_withheld pub driver_diagnostics_withheld: u64 field metal2vulkan-runtime::WorkCounts.empty_memory_blocks_live pub empty_memory_blocks_live: u64 +field metal2vulkan-runtime::WorkCounts.encoder_calls_held_by_rebind pub encoder_calls_held_by_rebind: u64 field metal2vulkan-runtime::WorkCounts.encoder_command_buffers_begun pub encoder_command_buffers_begun: u64 field metal2vulkan-runtime::WorkCounts.encoder_primaries_begun_ahead pub encoder_primaries_begun_ahead: u64 field metal2vulkan-runtime::WorkCounts.encoder_primaries_begun_ahead_missed pub encoder_primaries_begun_ahead_missed: u64 @@ -3069,6 +3070,7 @@ field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_layout pub encode field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_split pub encoders_none_kept_next_split: u64 field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_under pub encoders_none_kept_next_under: u64 field metal2vulkan-runtime::WorkCounts.encoders_raced_rebind pub encoders_raced_rebind: u64 +field metal2vulkan-runtime::WorkCounts.encoders_raced_unreplayable pub encoders_raced_unreplayable: u64 field metal2vulkan-runtime::WorkCounts.encoders_reencoded pub encoders_reencoded: u64 field metal2vulkan-runtime::WorkCounts.encoders_uncarried_commands pub encoders_uncarried_commands: u64 field metal2vulkan-runtime::WorkCounts.encoders_uncarried_drawless pub encoders_uncarried_drawless: u64 @@ -3556,6 +3558,7 @@ field metal2vulkan-runtime::WorkCounts.reading_draws_split_unreadable_own_pixel_ field metal2vulkan-runtime::WorkCounts.reading_draws_split_variant_refused pub reading_draws_split_variant_refused: u64 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.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 f408d7c8e..3fd03e30e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3624,7 +3624,10 @@ bound. (`rebind_bytes_no_copy`) after the command was encoded and before the command buffer was first submitted, or whose encoding a rebind on another thread raced (the call held the buffer while the rebind was making what lies over its bytes again, or after, having begun before; counted by - `WorkCounts::encoders_raced_rebind`), in an encoder the runtime could not encode again. Cost: each + `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 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