From 456d6230265608114ec7be8920c1f7ab3ed0effb Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 21:02:05 +0000 Subject: [PATCH 1/2] victory-gpu: add opt-in Flight-1 GPU overlap (VICTORY_FLIGHT1=1) and async submit worker (VICTORY_ASYNC_SUBMIT=1) Implement Wait-Before-Prep Flight-1 overlap (Phase A, VICTORY_FLIGHT1=1) and a dedicated victory-submit worker thread (Phase B, VICTORY_ASYNC_SUBMIT=1) behind opt-in environment switches (default off): - Move Flight-1 state, launch, background victory-flight finisher thread, signal attachment, and GPU regression tests into host/flight.rs. - Enforce Wait-Before-Prep: finish_flight_locked always drains Flight N-1 (GPU fence wait, Mark check, copy-back, defer_after, BoP writes, upload list return, HostList recycling, and atomic pending_signals delivery) before Flight N touches any shared Shadow, descriptor heap, texture staging pool, or Mark buffer. - Keep Vec> and owned bindless::Uploads inside InFlight so list::restart preserves strong_count > 1 on early title Reset and bindless::LIST / texture::recycle never reset in-flight resources. - Drain any active flight inside Host::quiet() after locking submitted so the GPU is idle during shader-visible descriptor heap creation/null-fill. - Add Held::take_ready / finish_running so victory-submit and Flight-1 never hold HELD across GPU submission, strictly preserving the lock DAG (SUBMIT_DRAIN -> HELD -> Host::submitted -> Host::flight -> Fence::waiters) and draining cleanly at PresentX, CopyPageMappingsBatchX, and sync Host::execute calls. --- crates/victory-gpu/src/bindless.rs | 50 +- crates/victory-gpu/src/hold.rs | 162 +++++- crates/victory-gpu/src/host.rs | 514 +++++++++++------ crates/victory-gpu/src/host/flight.rs | 789 ++++++++++++++++++++++++++ crates/victory-gpu/src/queue.rs | 351 +++++++++++- 5 files changed, 1642 insertions(+), 224 deletions(-) create mode 100644 crates/victory-gpu/src/host/flight.rs diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index 44224027..69c9e3b8 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -199,20 +199,27 @@ pub(crate) fn uploads( heaps: &[Arc], textures: &[(Arc, Arc)], ) -> Option { - static LIST: Mutex = Mutex::new(Holder(None)); - let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner()); + static LIST: Mutex> = Mutex::new(None); + let taken = LIST.lock().unwrap_or_else(|e| e.into_inner()).take(); crate::texture::recycle(); - match &guard.0 { + let list = match taken { // Closed by the last submission, which has run. - Some(list) => list.reset(), + Some(list) => { + list.reset(); + list + } // Made open. None => { let list = crate::host::host()?.new_list().ok()?; list.set_ours(); - guard.0 = Some(list); + list } - } - let list = guard.0.as_ref()?; + }; + let uploads = Uploads { + list: Some(list), + pool: &LIST, + }; + let list = uploads.list(); // What to bring up: the textures lists read through tables, and those // the heaps view that shaders read lately. Collected under the heaps' // locks and brought up without them, several at a time: reading title @@ -280,22 +287,29 @@ pub(crate) fn uploads( unsafe { list.list.ResourceBarrier(&readable) }; } list.close(); - // A list recording nothing is not run (its reset next time is fine). - recorded.then_some(Uploads(guard)) + // A list recording nothing is not run (dropping `uploads` returns it to + // `LIST` for the next submission). + recorded.then_some(uploads) } -/// The upload list, used under its lock only. -pub(crate) struct Holder(Option); -// SAFETY: D3D12 objects are free-threaded; the list is used by one -// submission at a time, under the lock. -unsafe impl Send for Holder {} - -/// The upload list of a submission, ours until it has run. -pub(crate) struct Uploads(std::sync::MutexGuard<'static, Holder>); +/// The upload list of a submission, owned until the submission's GPU fence +/// completes; dropping returns it to the reuse slot for the next submission. +pub(crate) struct Uploads { + list: Option, + pool: &'static Mutex>, +} impl Uploads { pub(crate) fn list(&self) -> &HostList { - self.0.0.as_ref().expect("made before it is handed out") + self.list.as_ref().expect("made before it is handed out") + } +} + +impl Drop for Uploads { + fn drop(&mut self) { + if let Some(list) = self.list.take() { + *self.pool.lock().unwrap_or_else(|e| e.into_inner()) = Some(list); + } } } diff --git a/crates/victory-gpu/src/hold.rs b/crates/victory-gpu/src/hold.rs index f5a02bcc..652380c0 100644 --- a/crates/victory-gpu/src/hold.rs +++ b/crates/victory-gpu/src/hold.rs @@ -85,9 +85,28 @@ pub(crate) struct Pumped { pub(crate) unknown: u32, } +/// One ready step popped from [`Held`] so the caller can release the `HELD` +/// lock while running it on the host GPU. +#[cfg(any(windows, test))] +pub(crate) enum Ready { + /// Consecutive ready segments from `queue`. `queue` stays marked running + /// until [`Held::finish_running`] is called so later submissions and + /// signals on the same queue wait behind it. + Segments { + queue: usize, + segments: Vec, + waited: Vec<(usize, Duration)>, + unknown: u32, + }, + /// A fence signal ready at the head of `queue`. + Signal { fence: usize, value: u64 }, +} + /// Every queue's held work. pub(crate) struct Held { queues: Vec<(usize, Fifo)>, + /// Queue whose popped segments are currently executing outside the lock. + running: Option, } /// A queue's items, each with when it was pushed and whether it is fresh @@ -102,7 +121,10 @@ impl Default for Held { impl Held { pub(crate) const fn new() -> Self { - Held { queues: Vec::new() } + Held { + queues: Vec::new(), + running: None, + } } } @@ -215,14 +237,101 @@ impl Held { .collect() } - /// Whether no queue holds anything. + /// Pops the next ready batch of segments or ready fence signal so the + /// caller can drop the `HELD` lock before invoking the host GPU. + /// When [`Ready::Segments`] is returned, the caller must call + /// [`Self::finish_running`] with the same `queue` once the submission + /// call returns. + #[cfg(any(windows, test))] + pub(crate) fn take_ready( + &mut self, + read: &dyn Fn(u64, u8) -> Option, + fence: &dyn Fn(usize) -> u64, + ) -> Option> { + for (queue, items) in &mut self.queues { + if self.running == Some(*queue) { + continue; + } + let mut segments = Vec::new(); + let mut waited = Vec::new(); + let mut unknown = 0u32; + loop { + match items.front_mut() { + None => break, + Some((Item::FenceWait(f, v), _, fresh)) => { + if fence(*f) >= *v { + items.pop_front(); + continue; + } + *fresh = false; + break; + } + Some((Item::Signal(..), ..)) => { + if !segments.is_empty() { + break; + } + if let Some((Item::Signal(f, v), ..)) = items.pop_front() { + self.queues.retain(|(_, q)| !q.is_empty()); + return Some(Ready::Signal { fence: f, value: v }); + } + break; + } + Some((Item::Segment(_, waits), since, fresh)) => { + let mut ok = true; + for wait in waits.iter() { + match wait.holds(read) { + Some(true) => {} + Some(false) => ok = false, + None => unknown += 1, + } + } + if !ok { + *fresh = false; + break; + } + if !*fresh { + waited.push((*queue, since.elapsed())); + } + if let Some((Item::Segment(s, _), ..)) = items.pop_front() { + segments.push(s); + } + } + } + } + if !segments.is_empty() { + let q = *queue; + self.running = Some(q); + return Some(Ready::Segments { + queue: q, + segments, + waited, + unknown, + }); + } + } + self.queues.retain(|(_, items)| !items.is_empty()); + None + } + + /// Clears the running marker set by [`Self::take_ready`] once the popped + /// batch has been handed to the host GPU. + #[cfg(any(windows, test))] + pub(crate) fn finish_running(&mut self, queue: usize) { + if self.running == Some(queue) { + self.running = None; + } + self.queues.retain(|(_, items)| !items.is_empty()); + } + + /// Whether no queue holds anything and none is currently running. pub(crate) fn is_empty(&self) -> bool { - self.queues.is_empty() + self.running.is_none() && self.queues.is_empty() } - /// Whether `queue` holds anything. + /// Whether `queue` holds anything or has a popped batch still launching. pub(crate) fn holds_work(&self, queue: usize) -> bool { - self.queues.iter().any(|(q, items)| *q == queue && !items.is_empty()) + self.running == Some(queue) + || self.queues.iter().any(|(q, items)| *q == queue && !items.is_empty()) } /// Releases work held longer than `limit` at the heads of blocked @@ -441,4 +550,47 @@ mod tests { pump(&mut held, &fake); assert_eq!(fake.borrow().log, ["q2: stuck"]); } + + #[test] + fn take_ready_marks_queue_running_until_finished() { + let mut held = Held::default(); + held.push(1, Item::Segment("a", vec![])); + held.push(1, Item::Signal(9, 1)); + held.push(1, Item::Segment("b", vec![])); + let read = |_: u64, _| Some(0u64); + let fence = |_: usize| 0u64; + + match held.take_ready(&read, &fence) { + Some(Ready::Segments { + queue, segments, .. + }) => { + assert_eq!(queue, 1); + assert_eq!(segments, ["a"]); + } + _ => panic!("expected segments"), + } + // Queue 1 is marked running: holds_work stays true and take_ready + // must not pop its queued Signal before finish_running(1). + assert!(held.holds_work(1)); + assert!(!held.is_empty()); + assert!(held.take_ready(&read, &fence).is_none()); + + held.finish_running(1); + match held.take_ready(&read, &fence) { + Some(Ready::Signal { fence: f, value }) => assert_eq!((f, value), (9, 1)), + _ => panic!("expected signal"), + } + match held.take_ready(&read, &fence) { + Some(Ready::Segments { + queue, segments, .. + }) => { + assert_eq!(queue, 1); + assert_eq!(segments, ["b"]); + } + _ => panic!("expected trailing segment"), + } + held.finish_running(1); + assert!(!held.holds_work(1)); + assert!(held.is_empty()); + } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5d7ad469..d3004364 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4,8 +4,11 @@ //! shortcut: every submission is waited for, so CPU and GPU never overlap; //! overlap them with per-submission fences once more than clears run. +mod flight; +pub(crate) use flight::{async_submit_enabled, flight1_enabled}; + use std::sync::atomic::{AtomicU32, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; @@ -54,9 +57,37 @@ impl Drop for Holding { /// Submissions held off ([`Host::quiet`]). pub(crate) struct Quiet<'a> { - // Dropped in this order: the mark, then the lock. - _holding: Holding, - _held: std::sync::MutexGuard<'a, u64>, + holding: Option, + held: Option>, + landed: bool, +} + +impl Drop for Quiet<'_> { + fn drop(&mut self) { + // Drop in strict order: thread-local flag, then submission lock, and + // only after releasing `submitted` notify held queues if a flight landed. + self.holding.take(); + self.held.take(); + if self.landed { + crate::queue::on_flight_landed(); + } + } +} + +/// Prepared submission artifacts owned between `prepare_submission` and +/// `finish_post_gpu`. +struct PreparedSubmission { + lists: Vec>, + #[cfg(feature = "diagnostics")] + firsts: Vec, + native_boundaries: Vec, + batch: Batch, + heaps: Vec>, + uploads: Option, + started: std::time::Instant, + prepared: std::time::Instant, + #[cfg(feature = "diagnostics")] + traced: bool, } pub(crate) struct Host { @@ -73,6 +104,13 @@ pub(crate) struct Host { /// Extra marks for native calls before the final call of a split submission. split_marks: Mutex>>, event: HANDLE, + /// Separate fence event waited on exclusively by `victory-flight` outside + /// `Host::submitted`. + flight_event: HANDLE, + /// At-most-one active GPU flight and title fence signals queued behind it. + flight: Mutex, + /// Wakes `victory-flight` whenever a new flight is launched. + flight_wake: Condvar, rtvs: ID3D12DescriptorHeap, rtv_size: u32, /// A ring of depth views, used as `rtvs`. @@ -332,6 +370,7 @@ fn create() -> windows::core::Result { })?; let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = CreateEventW(None, false, false, None)?; + let flight_event = CreateEventW(None, false, false, None)?; let rtvs: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, @@ -375,6 +414,9 @@ fn create() -> windows::core::Result { mark: OnceLock::new(), split_marks: Mutex::new(Some(Vec::new())), event, + flight_event, + flight: Mutex::new(flight::FlightState::default()), + flight_wake: Condvar::new(), rtvs, rtv_size, dsvs, @@ -1601,16 +1643,24 @@ impl Host { /// itself. A late event left set by an earlier wait cannot end a later /// wait early, as the fence is checked after every wake-up too. fn wait_for(&self, value: u64) { + self.wait_for_on_event(self.event, value, 1000); + } + + /// Waits until the host fence reaches `value`, polling `event` every + /// `poll_ms` milliseconds so a dropped D3DMetal event (#50) never hangs. + pub(super) fn wait_for_on_event(&self, event: HANDLE, value: u64, poll_ms: u32) { use std::sync::atomic::AtomicU64; static MISSED: AtomicU64 = AtomicU64::new(0); - let mut seconds = 0u32; + let started = std::time::Instant::now(); + let mut next_log_secs = 1u64; + let mut logged_hang = false; loop { // SAFETY: our event and fence. - let woke = unsafe { WaitForSingleObject(self.event, 1000) }; + let woke = unsafe { WaitForSingleObject(event, poll_ms) }; // SAFETY: as above. let completed = unsafe { self.fence.GetCompletedValue() }; if completed >= value { - if woke != windows::Win32::Foundation::WAIT_OBJECT_0 { + if woke != windows::Win32::Foundation::WAIT_OBJECT_0 && started.elapsed().as_millis() >= 1000 { let n = MISSED.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { tracing::warn!(n, value, completed, "a host submission finished without setting its event; went on after checking the fence"); @@ -1619,11 +1669,13 @@ impl Host { return; } if woke != windows::Win32::Foundation::WAIT_OBJECT_0 { - seconds += 1; - if seconds.is_power_of_two() { + let seconds = started.elapsed().as_secs(); + if seconds >= next_log_secs { tracing::warn!(seconds, value, completed, "still waiting for the host GPU"); + next_log_secs = (next_log_secs * 2).max(seconds + 1); } - if seconds == 8 { + if !logged_hang && seconds >= 8 { + logged_hang = true; let what = WAITING_ON.lock().unwrap_or_else(|e| e.into_inner()).clone(); tracing::error!(%what, value, "host GPU hang: the submission waited on"); } @@ -1741,154 +1793,77 @@ impl Host { if !crate::under_wine() || HOLDS_SUBMISSIONS.with(std::cell::Cell::get) { return None; } - let held = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); - Some(Quiet { _holding: Holding::enter(), _held: held }) + let mut held = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let holding = Holding::enter(); + // Ensure the GPU is completely idle before descriptor heap creation / + // null-fill begins (VIctory-macOS issue #31). + let landed = self.finish_flight_locked(&mut held, None); + Some(Quiet { + holding: Some(holding), + held: Some(held), + landed, + }) } - /// Runs closed lists and waits for them. + /// Runs closed lists and waits for them. Drains any queued async-submit + /// work and any active Flight-1 submission first so synchronous callers + /// observe strictly ordered GPU state. pub(crate) fn execute(&self, runs: &[&HostList]) { + if !HOLDS_SUBMISSIONS.with(std::cell::Cell::get) { + crate::queue::before_sync(); + } + self.execute_sync(runs); + } + + /// Runs closed lists synchronously under `self.submitted`, finishing any + /// active Flight-1 submission first. + pub(crate) fn execute_sync(&self, runs: &[&HostList]) { // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let _holding = Holding::enter(); - let started = std::time::Instant::now(); - #[cfg(feature = "diagnostics")] - let faults = crate::copystat::page_faults(); - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::Submissions, 1); - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::ExecuteLists, runs.len() as u64); - // Host textures the title has not used for a while (or past the - // card's budget) are given up first: the last submission has run. - crate::resource::evict_unused(); - // The first shader writing through a heap may run in this - // submission: unordered views left null are made again first. - if crate::bindless::take_remake() { - crate::descriptor::remake_unordered(); - } - // Descriptors the title copied into its heaps itself, before the - // heaps' views are brought up to date below. - #[cfg(feature = "diagnostics")] - let syncing = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SyncHeapsUs); - crate::descriptor::sync_heaps(); - #[cfg(feature = "diagnostics")] - drop(syncing); - // Textures heap-indexing shaders may read, uploaded first by a list - // of ours where their title memory changed. - let heaps: Vec> = runs - .iter() - .flat_map(|l| { - l.deferred() - .copies - .iter() - .filter_map(|s| match s { - Step::Heap(v) => Some(v.clone()), - _ => None, - }) - .collect::>() - }) - .collect(); - // And textures read through tables, uploaded by the same list. - let textures: Vec<_> = runs - .iter() - .flat_map(|l| { - l.deferred() - .copies - .iter() - .filter_map(|s| match s { - Step::Texture(staging, copy) => Some((staging.clone(), copy.clone())), - _ => None, - }) - .collect::>() - }) - .collect(); - #[cfg(feature = "diagnostics")] - let uploading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::UploadsUs); - let uploads = (!heaps.is_empty() || !textures.is_empty()) - .then(|| crate::bindless::uploads(&heaps, &textures)) - .flatten(); + self.finish_flight_locked(&mut submitted, None); + #[cfg(feature = "diagnostics")] - drop(uploading); - let runs: Vec<&HostList> = uploads + let gpu_timing = timing(); + #[cfg(not(feature = "diagnostics"))] + let gpu_timing = false; + + let mut prep = self.prepare_submission(&submitted, runs, gpu_timing); + let run_refs: Vec<&HostList> = prep + .uploads .as_ref() .map(|u| u.list()) .into_iter() .chain(runs.iter().copied()) .collect(); - let runs = &runs[..]; - // A frame `crate::capture` lists: every command of every list, in - // the order the GPU runs them (with `VICTORY_D3D12_DRED`, which - // notes them). - #[cfg(feature = "diagnostics")] - let traced = crate::capture::listed(crate::queue::presented() + 1); - #[cfg(feature = "diagnostics")] - if traced { - for (i, r) in runs.iter().enumerate() { - let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); - for (k, (note, _)) in notes.iter().enumerate() { - tracing::info!( - target: "victory_gpu::trace", - "s{} l{i}/{} #{k}: {note}", - *submitted + 1, - runs.len() - ); - } - } - } - #[cfg(feature = "diagnostics")] - let gpu_timing = timing(); - #[cfg(not(feature = "diagnostics"))] - let gpu_timing = false; - let split_preludes = !gpu_timing && split_uav_srv_prelude(); - let mut native_boundaries = Vec::new(); - let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); - // Where each run's lists start in `lists`. - let mut firsts = Vec::with_capacity(runs.len()); - let mut batch = Batch::default(); - for list in runs { - list.run_deferred(&mut batch); - firsts.push(lists.len()); - #[cfg(feature = "diagnostics")] - let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::PreludeUs); - if let Some((prelude, uav_to_srv)) = list.prelude(split_preludes) { - if uav_to_srv && !lists.is_empty() { - native_boundaries.push(lists.len()); - } - lists.push(Some(prelude)); - } - lists.push(list.list.cast().ok()); - } - batch.flush(); - #[cfg(feature = "diagnostics")] - batch.log_refreshes(*submitted + 1, runs.len()); - let prepared = std::time::Instant::now(); - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::FaultsPrep, crate::copystat::page_faults().saturating_sub(faults)); + let runs = &run_refs[..]; + // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). #[cfg(feature = "diagnostics")] let groups: Vec<&[Option]> = if gpu_timing { - firsts + prep.firsts .iter() - .zip(firsts.iter().skip(1).chain([&lists.len()])) - .map(|(&a, &b)| &lists[a..b]) + .zip(prep.firsts.iter().skip(1).chain([&prep.lists.len()])) + .map(|(&a, &b)| &prep.lists[a..b]) .collect() } else { - vec![&lists[..]] + vec![&prep.lists[..]] }; #[cfg(not(feature = "diagnostics"))] - let groups = [&lists[..]]; + let groups = [&prep.lists[..]]; let mut removed_in = None; let mark = self.mark(); // A failed earlier call may leave the queue able to run the final mark. // Give each native call its own mark so failure recovery can see it. if mark.is_none() { - native_boundaries.clear(); + prep.native_boundaries.clear(); } - let mut split_pool = (!native_boundaries.is_empty()) + let mut split_pool = (!prep.native_boundaries.is_empty()) .then(|| self.split_marks.lock().unwrap_or_else(|e| e.into_inner())); if let Some(pool) = split_pool.as_deref_mut() { if let Some(marks) = pool.as_mut() - && let Err(error) = (marks.len()..native_boundaries.len()).try_for_each(|_| { + && let Err(error) = (marks.len()..prep.native_boundaries.len()).try_for_each(|_| { marks.push(Mark::new(self)?); Ok::<_, windows::core::Error>(()) }) @@ -1900,35 +1875,13 @@ impl Host { *pool = None; } if pool.is_none() { - native_boundaries.clear(); + prep.native_boundaries.clear(); } } let split_marks = split_pool .as_deref() .and_then(Option::as_deref) .unwrap_or(&[]); - if !native_boundaries.is_empty() { - static FIRST_SPLIT: std::sync::Once = std::sync::Once::new(); - FIRST_SPLIT.call_once(|| { - tracing::info!( - native_calls = native_boundaries.len() + 1, - "split host submission at deferred UAV-to-SRV preludes" - ); - }); - } - // What a hang would be waiting on (`Host::wait_for` names it after 8 s). - *WAITING_ON.lock().unwrap_or_else(|e| e.into_inner()) = { - let pipelines: std::collections::BTreeSet = runs - .iter() - .flat_map(|l| { - l.pipelines - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clone() - }) - .collect(); - format!("{} lists, pipelines {pipelines:?}", runs.len()) - }; for (i, group) in groups.iter().enumerate() { *submitted += 1; let started = std::time::Instant::now(); @@ -1945,7 +1898,7 @@ impl Host { let waited = unsafe { // All native calls share the existing fence signal and wait. let mut first = 0; - for (&end, mark) in native_boundaries.iter().zip(split_marks) { + for (&end, mark) in prep.native_boundaries.iter().zip(split_marks) { mark.arm(*submitted); let mut marked = group[first..end].to_vec(); marked.push(mark.list()); @@ -1976,7 +1929,10 @@ impl Host { if waited && let Some(mark) = mark && (!mark.saw(*submitted) - || split_marks.iter().take(native_boundaries.len()).any(|m| !m.saw(*submitted))) + || split_marks + .iter() + .take(prep.native_boundaries.len()) + .any(|m| !m.saw(*submitted))) // SAFETY: a plain query. && unsafe { self.device.GetDeviceRemovedReason() }.is_ok() { @@ -1988,7 +1944,10 @@ impl Host { if groups.len() > 1 { // SAFETY: a plain query. let frequency = unsafe { queue.GetTimestampFrequency() }.unwrap_or(1); - gpu_times(started.elapsed(), &runs[i].slowest(frequency, usize::MAX).unwrap_or_default()); + gpu_times( + started.elapsed(), + &runs[i].slowest(frequency, usize::MAX).unwrap_or_default(), + ); } #[cfg(feature = "diagnostics")] if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { @@ -2022,13 +1981,218 @@ impl Host { } } } - // SAFETY: a plain query. - if groups.len() > 1 && removed_in.is_none() && unsafe { self.device.GetDeviceRemovedReason() }.is_err() { - removed_in = Some(i); + if groups.len() > 1 && removed_in.is_none() { + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + removed_in = Some(i); + } } let _ = (i, started); } - let _ = &firsts; + drop(split_pool); + self.finish_post_gpu( + runs, + prep.batch, + prep.heaps, + prep.started, + prep.prepared, + removed_in, + ); + // A listed frame: what this submission's lists drew, as it is now + // (the dumps submit lists of their own). + #[cfg(feature = "diagnostics")] + if prep.traced { + let sub = *submitted; + let mut targets: Vec<(usize, String)> = Vec::new(); + for r in runs { + for t in r.targets.lock().unwrap_or_else(|e| e.into_inner()).iter() { + if !targets.iter().any(|x| x.0 == t.0) { + targets.push(t.clone()); + } + } + } + drop(run_refs); + drop(prep.uploads); + drop(submitted); + crate::capture::dump_submission(sub, &targets); + } + } + + /// Prepares a submission under `self.submitted` once any prior flight has + /// finished: evicts unused textures, syncs descriptor heaps, records + /// texture uploads, runs deferred CPU copies/refreshes, and builds preludes. + fn prepare_submission( + &self, + submitted: &u64, + runs: &[&HostList], + gpu_timing: bool, + ) -> PreparedSubmission { + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let faults = crate::copystat::page_faults(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Submissions, 1); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::ExecuteLists, runs.len() as u64); + // Host textures the title has not used for a while (or past the + // card's budget) are given up first: the last submission has run. + crate::resource::evict_unused(); + // The first shader writing through a heap may run in this + // submission: unordered views left null are made again first. + if crate::bindless::take_remake() { + crate::descriptor::remake_unordered(); + } + // Descriptors the title copied into its heaps itself, before the + // heaps' views are brought up to date below. + #[cfg(feature = "diagnostics")] + let syncing = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SyncHeapsUs); + crate::descriptor::sync_heaps(); + #[cfg(feature = "diagnostics")] + drop(syncing); + // Textures heap-indexing shaders may read, uploaded first by a list + // of ours where their title memory changed. + let heaps: Vec> = runs + .iter() + .flat_map(|l| { + l.deferred() + .copies + .iter() + .filter_map(|s| match s { + Step::Heap(v) => Some(v.clone()), + _ => None, + }) + .collect::>() + }) + .collect(); + // And textures read through tables, uploaded by the same list. + let textures: Vec<_> = runs + .iter() + .flat_map(|l| { + l.deferred() + .copies + .iter() + .filter_map(|s| match s { + Step::Texture(staging, copy) => Some((staging.clone(), copy.clone())), + _ => None, + }) + .collect::>() + }) + .collect(); + #[cfg(feature = "diagnostics")] + let uploading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::UploadsUs); + let uploads = (!heaps.is_empty() || !textures.is_empty()) + .then(|| crate::bindless::uploads(&heaps, &textures)) + .flatten(); + #[cfg(feature = "diagnostics")] + drop(uploading); + let run_refs: Vec<&HostList> = uploads + .as_ref() + .map(|u| u.list()) + .into_iter() + .chain(runs.iter().copied()) + .collect(); + let runs = &run_refs[..]; + // A frame `crate::capture` lists: every command of every list, in + // the order the GPU runs them (with `VICTORY_D3D12_DRED`, which + // notes them). + #[cfg(feature = "diagnostics")] + let traced = crate::capture::listed(crate::queue::presented() + 1); + #[cfg(feature = "diagnostics")] + if traced { + for (i, r) in runs.iter().enumerate() { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + for (k, (note, _)) in notes.iter().enumerate() { + tracing::info!( + target: "victory_gpu::trace", + "s{} l{i}/{} #{k}: {note}", + *submitted + 1, + runs.len() + ); + } + } + } + let split_preludes = !gpu_timing && split_uav_srv_prelude(); + let mut native_boundaries = Vec::new(); + let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); + // Where each run's lists start in `lists`. + let mut firsts = Vec::with_capacity(runs.len()); + let mut batch = Batch::default(); + for list in runs { + list.run_deferred(&mut batch); + firsts.push(lists.len()); + #[cfg(feature = "diagnostics")] + let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::PreludeUs); + if let Some((prelude, uav_to_srv)) = list.prelude(split_preludes) { + if uav_to_srv && !lists.is_empty() { + native_boundaries.push(lists.len()); + } + lists.push(Some(prelude)); + } + lists.push(list.list.cast().ok()); + } + batch.flush(); + #[cfg(feature = "diagnostics")] + batch.log_refreshes(*submitted + 1, runs.len()); + #[cfg(not(feature = "diagnostics"))] + let _ = submitted; + let prepared = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::FaultsPrep, + crate::copystat::page_faults().saturating_sub(faults), + ); + if !native_boundaries.is_empty() { + static FIRST_SPLIT: std::sync::Once = std::sync::Once::new(); + FIRST_SPLIT.call_once(|| { + tracing::info!( + native_calls = native_boundaries.len() + 1, + "split host submission at deferred UAV-to-SRV preludes" + ); + }); + } + // What a hang would be waiting on (`Host::wait_for` names it after 8 s). + *WAITING_ON.lock().unwrap_or_else(|e| e.into_inner()) = { + let pipelines: std::collections::BTreeSet = runs + .iter() + .flat_map(|l| { + l.pipelines + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + }) + .collect(); + format!("{} lists, pipelines {pipelines:?}", runs.len()) + }; + drop(run_refs); + #[cfg(not(feature = "diagnostics"))] + let _ = firsts; + PreparedSubmission { + lists, + #[cfg(feature = "diagnostics")] + firsts, + native_boundaries, + batch, + heaps, + uploads, + started, + prepared, + #[cfg(feature = "diagnostics")] + traced, + } + } + + /// Runs post-GPU completion work under `self.submitted` after the host + /// fence has completed: timing/removal checks, mark & shadow copy-back, + /// `after` callbacks, bottom-of-pipe writes, retirement, and info-queue logs. + fn finish_post_gpu( + &self, + runs: &[&HostList], + batch: Batch, + heaps: Vec>, + started: std::time::Instant, + prepared: std::time::Instant, + removed_in: Option, + ) { let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); @@ -2069,7 +2233,8 @@ impl Host { let faults = crate::copystat::page_faults(); // One list's lock at a time: a submission may name a list twice. let mut back: Vec<(std::sync::Arc, usize, usize, bool)> = Vec::new(); - let mut index: std::collections::HashMap<(usize, usize, usize), usize> = std::collections::HashMap::new(); + let mut index: std::collections::HashMap<(usize, usize, usize), usize> = + std::collections::HashMap::new(); // Shaders that read memory with no copy computed something else than // the console's: it stays out of title memory, where it broke the // title's own data (runs c1, c4), and so does what every program @@ -2113,7 +2278,9 @@ impl Host { .collect(); for b in back.iter_mut().filter(|b| b.3) { let copy = std::sync::Arc::as_ptr(&b.0) as usize; - b.3 = !held.iter().any(|&(c, a, n)| c == copy && a < b.1 + b.2 && b.1 < a + n); + b.3 = !held + .iter() + .any(|&(c, a, n)| c == copy && a < b.1 + b.2 && b.1 < a + n); } // Pages shaders marked first: the copy-backs below end what the // copies keep for them. @@ -2142,11 +2309,7 @@ impl Host { ); } } - let total_back_bytes: usize = back - .iter() - .filter(|b| b.3) - .map(|b| b.2) - .sum(); + let total_back_bytes: usize = back.iter().filter(|b| b.3).map(|b| b.2).sum(); if crate::shadow::parallel_copies_enabled() && total_back_bytes >= crate::shadow::PARALLEL_COPY_BACK_MIN_BYTES { @@ -2209,7 +2372,10 @@ impl Host { } COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::FaultsBack, crate::copystat::page_faults().saturating_sub(faults)); + crate::copystat::add( + crate::copystat::C::FaultsBack, + crate::copystat::page_faults().saturating_sub(faults), + ); for list in runs { for &(at, what, bytes) in &list.deferred().writes { what.write(at as *mut u8, bytes); @@ -2220,22 +2386,6 @@ impl Host { release_retired(); release_later(Box::new((batch, back, withheld, heaps))); self.log_messages(); - // A listed frame: what this submission's lists drew, as it is now - // (the dumps submit lists of their own). - #[cfg(feature = "diagnostics")] - if traced { - let sub = *submitted; - drop(submitted); - let mut targets: Vec<(usize, String)> = Vec::new(); - for r in runs { - for t in r.targets.lock().unwrap_or_else(|e| e.into_inner()).iter() { - if !targets.iter().any(|x| x.0 == t.0) { - targets.push(t.clone()); - } - } - } - crate::capture::dump_submission(sub, &targets); - } } /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations diff --git a/crates/victory-gpu/src/host/flight.rs b/crates/victory-gpu/src/host/flight.rs new file mode 100644 index 00000000..7a1e54ae --- /dev/null +++ b/crates/victory-gpu/src/host/flight.rs @@ -0,0 +1,789 @@ +//! Wait-Before-Prep Flight-1 GPU overlap (`VICTORY_FLIGHT1=1`) and opt-in +//! async submission mode (`VICTORY_ASYNC_SUBMIT=1`). +//! +//! At most one GPU submission (`InFlight`) is in flight at a time. While the +//! host GPU executes Flight N, the title's CPU threads immediately return from +//! submission and record Flight N+1 into fresh `HostList`s (`list::restart` +//! sees `Arc::strong_count > 1` and splits off spare lists). Before Flight N+1 +//! touches any shared CPU/GPU state (`evict_unused`, `sync_heaps`, +//! `bindless::uploads` / `texture::recycle`, `Shadow::update`, `Mark::arm`), +//! `finish_flight_locked` waits for Flight N's fence, checks its `Mark`, +//! copies back GPU writes, runs `after` closures and bottom-of-pipe writes, +//! recycles its `HostList`s, and delivers any attached title fence signals. +//! +//! A background `victory-flight` thread waits on `flight_event` without +//! holding `HELD` or `Host::submitted`, then acquires `Host::submitted` to +//! land the completed flight so fence waiters and BoP pollers wake promptly +//! even when the title submits no further work. + +use std::sync::Arc; +#[cfg(test)] +use std::sync::atomic::Ordering; + +use super::{Batch, Holding, Host, HostList, Mark}; +use crate::object::This; + +/// Whether Wait-Before-Prep Flight-1 overlap is enabled (`VICTORY_FLIGHT1=1`, +/// or implicitly enabled when `VICTORY_ASYNC_SUBMIT=1` unless +/// `VICTORY_FLIGHT1=0` is explicitly set; disabled when `VICTORY_GPU_TIMING` +/// is on). +pub(crate) fn flight1_enabled() -> bool { + #[cfg(test)] + match TEST_FLIGHT1.load(Ordering::Acquire) { + 1 => return false, + 2 => return true, + _ => {} + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + #[cfg(feature = "diagnostics")] + if super::timing() { + return false; + } + let on = match std::env::var("VICTORY_FLIGHT1").as_deref() { + Ok("1") => true, + Ok("0") => false, + _ => async_submit_env(), + }; + if on { + tracing::info!( + "Flight-1 GPU overlap enabled (VICTORY_FLIGHT1=1): wait-before-prep with background flight finisher" + ); + } + on + }) +} + +/// Whether submissions are queued to the dedicated `victory-submit` thread +/// (`VICTORY_ASYNC_SUBMIT=1`, off by default). +pub(crate) fn async_submit_enabled() -> bool { + #[cfg(test)] + match TEST_ASYNC_SUBMIT.load(Ordering::Acquire) { + 1 => return false, + 2 => return true, + _ => {} + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = async_submit_env(); + if on { + tracing::info!( + "Async submission worker enabled (VICTORY_ASYNC_SUBMIT=1): submissions prepared and launched on victory-submit" + ); + } + on + }) +} + +fn async_submit_env() -> bool { + std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") +} + +#[cfg(test)] +static TEST_FLIGHT1: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); +#[cfg(test)] +static TEST_ASYNC_SUBMIT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); +#[cfg(test)] +static TEST_MODE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(test)] +pub(crate) struct ModeGuard { + _lock: std::sync::MutexGuard<'static, ()>, + prev_flight1: u8, + prev_async: u8, +} + +#[cfg(test)] +impl ModeGuard { + pub(crate) fn new(flight1: bool, async_submit: bool) -> Self { + let lock = TEST_MODE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::queue::drain_submit(crate::queue::Why::Present); + if let Some(h) = super::host() { + h.finish_flight_now(); + } + let prev_flight1 = TEST_FLIGHT1.swap(if flight1 { 2 } else { 1 }, Ordering::AcqRel); + let prev_async = TEST_ASYNC_SUBMIT.swap(if async_submit { 2 } else { 1 }, Ordering::AcqRel); + Self { + _lock: lock, + prev_flight1, + prev_async, + } + } +} + +#[cfg(test)] +impl Drop for ModeGuard { + fn drop(&mut self) { + crate::queue::drain_submit(crate::queue::Why::Present); + if let Some(h) = super::host() { + h.finish_flight_now(); + } + TEST_FLIGHT1.store(self.prev_flight1, Ordering::Release); + TEST_ASYNC_SUBMIT.store(self.prev_async, Ordering::Release); + } +} + +/// Protected by `Host::flight` (leaf lock strictly below `HELD` and +/// `Host::submitted`, above only `Fence::waiters`). +#[derive(Default)] +pub(super) struct FlightState { + /// True from the moment a flight is launched until its post-GPU copy-back, + /// BoP writes, and attached signals have all completed. While `true`, + /// `attach_signal` queues behind the active flight instead of signalling + /// immediately. + active: bool, + /// The launched flight awaiting wait + landing; taken once by whichever + /// thread (`victory-flight` or the next submission) lands it under + /// `Host::submitted`. + in_flight: Option, + /// Title fences queued behind the active flight (each kept alive via + /// `fence::keep`). Delivered atomically before clearing `active`. + pending_signals: Vec<(usize, u64)>, + /// Whether the background `victory-flight` finisher thread has been spawned. + worker_started: bool, +} + +struct InFlight { + fence_value: u64, + segments: Vec>, + uploads: Option, + batch: Batch, + heaps: Vec>, + split_count: usize, + started: std::time::Instant, + prepared: std::time::Instant, + waited: bool, +} + +// SAFETY: Every field is `Send` (D3D12 objects are free-threaded; `HostList` +// and `Uploads` are `Send`; `Batch` holds `Arc` and ranges). +unsafe impl Send for InFlight {} + +impl Host { + /// Runs `segments` with Wait-Before-Prep Flight-1 overlap when enabled: + /// finishes any prior flight first, prepares and launches `segments` on + /// the host queue, and returns immediately while the GPU executes. + /// Falls back to synchronous execution when Flight-1 is disabled or when + /// per-submission diagnostics tracing is active on this frame. + pub(crate) fn execute_flight1(&self, segments: Vec>) { + if segments.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let traced = crate::capture::listed(crate::queue::presented() + 1); + #[cfg(not(feature = "diagnostics"))] + let traced = false; + if !flight1_enabled() || traced { + self.execute_sync_segments(segments); + return; + } + + let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let _holding = Holding::enter(); + // Wait-Before-Prep: drain Flight N-1 completely before Flight N + // touches any shared Shadow, descriptor heap, upload staging pool, or + // Mark buffer. + self.finish_flight_locked(&mut submitted, None); + + let prep = { + let run_refs: Vec<&HostList> = segments.iter().map(|s| &**s).collect(); + self.prepare_submission(&submitted, &run_refs, false) + }; + + let mut native_boundaries = prep.native_boundaries; + let mark = self.mark(); + if mark.is_none() { + native_boundaries.clear(); + } + let mut split_pool = (!native_boundaries.is_empty()) + .then(|| self.split_marks.lock().unwrap_or_else(|e| e.into_inner())); + if let Some(pool) = split_pool.as_deref_mut() { + if let Some(marks) = pool.as_mut() + && let Err(error) = (marks.len()..native_boundaries.len()).try_for_each(|_| { + marks.push(Mark::new(self)?); + Ok::<_, windows::core::Error>(()) + }) + { + tracing::warn!( + %error, + "could not make split submission marks, keeping the native batch together" + ); + *pool = None; + } + if pool.is_none() { + native_boundaries.clear(); + } + } + let split_marks = split_pool + .as_deref() + .and_then(Option::as_deref) + .unwrap_or(&[]); + + *submitted += 1; + let fence_value = *submitted; + #[cfg(feature = "diagnostics")] + crate::resource::life::note(0, crate::resource::life::SUBMITTED, fence_value, 0); + + let mut group = prep.lists; + if let Some(mark) = mark { + mark.arm(fence_value); + group.push(mark.list()); + } + let queue = self.queue(); + // SAFETY: closed lists; fence and events are ours. + let waited = unsafe { + let mut first = 0; + for (&end, m) in native_boundaries.iter().zip(split_marks) { + m.arm(fence_value); + let mut marked = group[first..end].to_vec(); + marked.push(m.list()); + #[cfg(test)] + super::tests::native_call(marked.len()); + queue.ExecuteCommandLists(&marked); + first = end; + } + #[cfg(test)] + super::tests::native_call(group.len() - first); + queue.ExecuteCommandLists(&group[first..]); + match queue.Signal(&self.fence, fence_value).and_then(|()| { + self.fence.SetEventOnCompletion(fence_value, self.event)?; + self.fence + .SetEventOnCompletion(fence_value, self.flight_event) + }) { + Ok(()) => true, + Err(e) => { + tracing::warn!(error = %e, "host flight submission not signalled"); + false + } + } + }; + drop(split_pool); + + let split_count = native_boundaries.len(); + let flight = InFlight { + fence_value, + segments, + uploads: prep.uploads, + batch: prep.batch, + heaps: prep.heaps, + split_count, + started: prep.started, + prepared: prep.prepared, + waited, + }; + { + let mut state = self.flight.lock().unwrap_or_else(|e| e.into_inner()); + debug_assert!(!state.active && state.in_flight.is_none()); + state.active = true; + state.in_flight = Some(flight); + if !state.worker_started { + state.worker_started = true; + spawn_flight_worker(); + } + } + self.flight_wake.notify_one(); + } + + /// Runs `segments` synchronously and recycles them afterward. Used by the + /// submit worker when `VICTORY_ASYNC_SUBMIT=1` with `VICTORY_FLIGHT1=0` + /// and as the fallback for traced frames. + pub(crate) fn execute_sync_segments(&self, segments: Vec>) { + let lists: Vec<&HostList> = segments.iter().map(|s| &**s).collect(); + self.execute_sync(&lists); + drop(lists); + segments.into_iter().for_each(crate::list::recycle); + } + + /// Attaches a title fence signal behind the active flight if one is in the + /// air. Returns `true` if attached (the caller must NOT call `fence::set` + /// immediately), or `false` if no flight is active. + /// + /// If `already_kept` is `false`, this calls `fence::keep(fence)` before + /// storing it. + pub(crate) fn attach_signal(&self, fence: This, value: u64, already_kept: bool) -> bool { + let mut state = self.flight.lock().unwrap_or_else(|e| e.into_inner()); + if !state.active { + return false; + } + if !already_kept { + crate::fence::keep(fence); + } + state.pending_signals.push((fence as usize, value)); + true + } + + /// Whether a flight is currently in the air or landing. + pub(crate) fn has_in_flight(&self) -> bool { + self.flight.lock().unwrap_or_else(|e| e.into_inner()).active + } + + /// Waits for and lands any active flight now. Returns `true` if a flight + /// was landed by this call. + pub(crate) fn finish_flight_now(&self) -> bool { + if !self.has_in_flight() { + return false; + } + let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let _holding = Holding::enter(); + self.finish_flight_locked(&mut submitted, None) + } + + /// Completes any active flight under `Host::submitted`. When + /// `only_if_fence` is `Some(v)`, only lands if the active flight matches + /// fence value `v` (used by `victory-flight` so it never blocks on a newer + /// flight while holding `Host::submitted`). + pub(super) fn finish_flight_locked( + &self, + submitted: &mut u64, + only_if_fence: Option, + ) -> bool { + let flight = { + let mut state = self.flight.lock().unwrap_or_else(|e| e.into_inner()); + match state.in_flight.as_ref() { + Some(f) if only_if_fence.is_none_or(|v| f.fence_value == v) => { + state.in_flight.take() + } + _ => return false, + } + }; + let Some(flight) = flight else { + return false; + }; + + if flight.waited { + self.wait_for(flight.fence_value); + } + #[cfg(test)] + super::tests::native_call_group(flight.waited); + + let mark = self.mark(); + let split_failed = if flight.split_count > 0 { + let pool = self.split_marks.lock().unwrap_or_else(|e| e.into_inner()); + pool.as_deref().is_some_and(|marks| { + marks + .iter() + .take(flight.split_count) + .any(|m| !m.saw(flight.fence_value)) + }) + } else { + false + }; + if flight.waited + && let Some(mark) = mark + && (!mark.saw(flight.fence_value) || split_failed) + // SAFETY: a plain query. + && unsafe { self.device.GetDeviceRemovedReason() }.is_ok() + { + self.lost(submitted, mark); + } + #[cfg(feature = "diagnostics")] + crate::resource::life::note(0, crate::resource::life::RAN, flight.fence_value, 0); + + { + let run_refs: Vec<&HostList> = flight + .uploads + .as_ref() + .map(|u| u.list()) + .into_iter() + .chain(flight.segments.iter().map(|s| &**s)) + .collect(); + self.finish_post_gpu( + &run_refs, + flight.batch, + flight.heaps, + flight.started, + flight.prepared, + None, + ); + } + + // Return the upload list to `bindless::LIST` and recycle host lists + // only after the GPU fence and post-GPU work have finished. + drop(flight.uploads); + flight.segments.into_iter().for_each(crate::list::recycle); + + // Deliver every title fence signal queued behind this flight + // atomically before clearing `active`, so later `queue::signal` calls + // can never overtake an attached signal. + let mut state = self.flight.lock().unwrap_or_else(|e| e.into_inner()); + for (fence, value) in state.pending_signals.drain(..) { + crate::fence::set(fence as This, value); + crate::fence::let_go(fence as This); + } + state.active = false; + true + } +} + +fn spawn_flight_worker() { + let _ = std::thread::Builder::new() + .name("victory-flight".into()) + .spawn(|| { + let Some(host) = super::host() else { + return; + }; + loop { + let (fence_value, waited) = { + let mut state = host.flight.lock().unwrap_or_else(|e| e.into_inner()); + while state.in_flight.is_none() { + state = host + .flight_wake + .wait(state) + .unwrap_or_else(|e| e.into_inner()); + } + let f = state.in_flight.as_ref().expect("in_flight present"); + (f.fence_value, f.waited) + }; + // Wait on the GPU fence WITHOUT holding `HELD` or + // `Host::submitted`. + if waited { + host.wait_for_on_event(host.flight_event, fence_value, 250); + } + let landed = { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let _holding = Holding::enter(); + host.finish_flight_locked(&mut submitted, Some(fence_value)) + }; + // Strictly AFTER dropping `Host::submitted`: wake held work or + // the submit worker in case this flight's BoP writes or fence + // signals unblocked another queue. + if landed { + crate::queue::on_flight_landed(); + } + } + }); +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + use super::*; + use crate::host::host; + use crate::object::{S_OK, This, slot}; + use crate::queue::Written; + + fn make_queue_and_fence() -> (This, This) { + let q = crate::queue::create_direct_for_test(); + let mut f = std::ptr::null(); + assert_eq!( + crate::fence::create( + std::ptr::null(), + 0, + 0, + &crate::fence::FENCE_IIDS[0], + &mut f + ), + S_OK + ); + (q, f) + } + + fn queue_signal(q: This, f: This, value: u64) { + let hr = crate::queue::signal_for_test(q, f, value); + assert_eq!(hr, S_OK); + } + + fn queue_execute(q: This, lists: &[This]) { + crate::queue::execute_for_test(q, lists); + } + + fn make_title_list() -> (This, This) { + let null = std::ptr::null(); + let alloc_iid = crate::object::guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ); + let list_iid = crate::object::guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ); + let mut alloc = null; + assert_eq!( + crate::list::create_allocator(null, 0, &alloc_iid, &mut alloc), + S_OK + ); + let mut list = null; + assert_eq!( + crate::list::create_list(null, 0, 0, alloc, null, &list_iid, &mut list), + S_OK + ); + (alloc, list) + } + + fn close_title_list(list: This) { + let close = slot:: i32>(list, 0x48); + assert_eq!(close(list), S_OK); + } + + fn reset_title_list(list: This, alloc: This) { + let reset = slot:: i32>(list, 0x50); + assert_eq!(reset(list, alloc, std::ptr::null()), S_OK); + } + + fn wait_fence(f: This, target: u64, timeout: Duration) -> bool { + let start = Instant::now(); + while crate::fence::value(f) < target { + if start.elapsed() >= timeout { + return false; + } + std::thread::sleep(Duration::from_millis(1)); + } + true + } + + /// Under `VICTORY_FLIGHT1=1`, a GPU copy + Shadow copy-back + `after` + /// callback + bottom-of-pipe write + attached `queue::signal` all land in + /// order via the background `victory-flight` finisher without requiring a + /// second submission. + #[test] + fn flight1_delivers_signals_bop_writes_and_copy_back_in_order() { + let Some(host) = host() else { + return; + }; + let _mode = ModeGuard::new(true, false); + + let (q, f) = make_queue_and_fence(); + let mut title_buf = vec![0u32; 16]; + let title_addr = title_buf.as_mut_ptr() as u64; + let shadow = crate::shadow::find(title_addr, 64).expect("shadow"); + + // Prepare source upload buffer containing 0xCAFE_BABE. + let (src_buf, src_ptr) = host.upload_buffer(64).expect("upload buffer"); + // SAFETY: mapped 64-byte upload buffer. + unsafe { + src_ptr.cast::().write_volatile(0xCAFE_BABE); + } + + let seg = Arc::new(host.new_list().expect("host list")); + // SAFETY: open host list, valid D3D12 buffers. + unsafe { + seg.list + .CopyBufferRegion(&shadow.buffer, shadow.offset(title_addr), &src_buf, 0, 4); + } + seg.keep(&src_buf); + shadow.gpu_writes(&seg, title_addr, 4, false); + + let after_ran = Arc::new(AtomicBool::new(false)); + let after_flag = after_ran.clone(); + let title_ptr_num = title_addr as usize; + let saw_copy_back_in_after = Arc::new(AtomicBool::new(false)); + let saw_cb = saw_copy_back_in_after.clone(); + let mut bop_word: u64 = 0; + let bop_ptr_num = (&raw mut bop_word) as usize; + let saw_bop_not_yet_written = Arc::new(AtomicBool::new(false)); + let saw_bop = saw_bop_not_yet_written.clone(); + + seg.defer_after(move || { + after_flag.store(true, Ordering::Release); + // SAFETY: title_buf and bop_word outlive the flight. + unsafe { + let copied = (title_ptr_num as *const u32).read_volatile(); + if copied == 0xCAFE_BABE { + saw_cb.store(true, Ordering::Release); + } + if (bop_ptr_num as *const u64).read_volatile() == 0 { + saw_bop.store(true, Ordering::Release); + } + } + }); + seg.defer_write(bop_ptr_num as *mut u8, Written::Value(0x1234_5678), 8); + seg.close(); + + host.execute_flight1(vec![seg]); + queue_signal(q, f, 7); + + // Background `victory-flight` must finish the flight and deliver the + // attached fence signal even with no further submissions. + assert!( + wait_fence(f, 7, Duration::from_secs(5)), + "victory-flight did not deliver attached fence signal" + ); + assert!(after_ran.load(Ordering::Acquire), "defer_after did not run"); + assert!( + saw_copy_back_in_after.load(Ordering::Acquire), + "copy_back must complete before defer_after" + ); + assert!( + saw_bop_not_yet_written.load(Ordering::Acquire), + "BoP writes must run after defer_after" + ); + // SAFETY: flight has landed and fence reached 7. + assert_eq!(unsafe { (&raw const bop_word).read_volatile() }, 0x1234_5678); + assert_eq!(title_buf[0], 0xCAFE_BABE); + assert!(!host.has_in_flight()); + } + + /// `Host::quiet()` drains any active Flight-1 work cleanly before + /// returning `Quiet` (preserving D3DMetal Issue #31's GPU-idle guarantee + /// around shader-visible heap null-fill) with zero deadlock. + #[test] + fn flight1_quiet_waits_for_in_flight_before_heap_creation() { + let Some(host) = host() else { + return; + }; + let _mode = ModeGuard::new(true, false); + + let mut bop_word: u32 = 0; + let seg = Arc::new(host.new_list().expect("host list")); + seg.defer_write((&raw mut bop_word).cast(), Written::Value(99), 4); + seg.close(); + + host.execute_flight1(vec![seg]); + // `quiet()` locks `submitted` and finishes any in-flight work. + // Force a direct `finish_flight_now` check via `quiet()` (note: off + // Wine `quiet()` returns None, so also test `finish_flight_now` + // directly when off Wine). + let q = host.quiet(); + if q.is_some() { + assert!( + !host.has_in_flight(), + "Host::quiet() returned while a GPU flight was still active" + ); + // SAFETY: flight has landed before `quiet()` returned. + assert_eq!(unsafe { (&raw const bop_word).read_volatile() }, 99); + drop(q); + } else { + host.finish_flight_now(); + assert!(!host.has_in_flight()); + // SAFETY: flight has landed after `finish_flight_now()`. + assert_eq!(unsafe { (&raw const bop_word).read_volatile() }, 99); + } + } + + /// Reproduces the 2-submission shadow overlap: + /// Flight 1 reads `OLD` (`0x11223300`) from a `Shadow` into `out1`, then + /// the CPU immediately mutates title memory to `NEW` (`0xAABBCC00`) and + /// submits Flight 2 reading the same `Shadow` into `out2`. + /// Because Flight-1 enforces Wait-Before-Prep, Flight 1 MUST observe + /// `OLD` and Flight 2 MUST observe `NEW` (never `NEW, NEW`) across 10 + /// consecutive iterations. + #[test] + fn flight1_never_clobbers_in_flight_shadow_data() { + let Some(host) = host() else { + return; + }; + let _mode = ModeGuard::new(true, false); + + // Allocate a page-aligned title buffer so Shadow tracks it cleanly. + let layout = std::alloc::Layout::from_size_align(4096, 4096).unwrap(); + // SAFETY: valid layout; freed after all flights finish. + let title_ptr = unsafe { std::alloc::alloc_zeroed(layout) }; + let title_addr = title_ptr as u64; + let shadow = crate::shadow::find(title_addr, 4096).expect("shadow"); + + let (out1_buf, out1_ptr) = host.mapped_buffer(64, true).expect("out1"); + let (out2_buf, out2_ptr) = host.mapped_buffer(64, true).expect("out2"); + + for iter in 0..10u32 { + let old_val = 0x1122_3300u32 | iter; + let new_val = 0xAABB_CC00u32 | iter; + // SAFETY: valid 4096-byte title buffer and 64-byte readback buffers. + unsafe { + title_ptr.cast::().write_volatile(old_val); + out1_ptr.cast::().write_volatile(0); + out2_ptr.cast::().write_volatile(0); + } + + let seg1 = Arc::new(host.new_list().expect("seg1")); + shadow.refresh(&seg1, title_addr, 64); + // SAFETY: open list, valid buffers. + unsafe { + seg1.list.CopyBufferRegion( + &out1_buf, + 0, + &shadow.buffer, + shadow.offset(title_addr), + 4, + ); + } + seg1.keep(&out1_buf); + seg1.close(); + + // Launch Flight 1 asynchronously! + host.execute_flight1(vec![seg1]); + + // Immediately overwrite title memory with NEW while Flight 1 is + // still in flight (exactly the #273 overlap window). + // SAFETY: valid title buffer. + unsafe { + title_ptr.cast::().write_volatile(new_val); + } + + let seg2 = Arc::new(host.new_list().expect("seg2")); + shadow.refresh(&seg2, title_addr, 64); + // SAFETY: open list, valid buffers. + unsafe { + seg2.list.CopyBufferRegion( + &out2_buf, + 0, + &shadow.buffer, + shadow.offset(title_addr), + 4, + ); + } + seg2.keep(&out2_buf); + seg2.close(); + + // Flight 2 MUST wait for Flight 1 before refreshing `shadow`. + host.execute_flight1(vec![seg2]); + host.finish_flight_now(); + + // SAFETY: both flights have landed. + let got1 = unsafe { out1_ptr.cast::().read_volatile() }; + // SAFETY: both flights have landed. + let got2 = unsafe { out2_ptr.cast::().read_volatile() }; + assert_eq!( + (got1, got2), + (old_val, new_val), + "iter {iter}: Shadow.data clobbered in flight! got ({got1:#x}, {got2:#x}), expected ({old_val:#x}, {new_val:#x})" + ); + } + + // SAFETY: all flights landed; free title buffer. + unsafe { std::alloc::dealloc(title_ptr, layout) }; + } + + /// Under `VICTORY_ASYNC_SUBMIT=1` + `VICTORY_FLIGHT1=1`, submits + /// multiple lists with immediate title `Reset` (exercising `list::restart` + /// early-reset splitting), interleaved `Signal`s, and `drain_submit` + /// (as called by `PresentX`), verifying strict FIFO completion order. + #[test] + fn async_submit_drains_cleanly_at_present_and_preserves_order() { + let Some(host) = host() else { + return; + }; + let _mode = ModeGuard::new(true, true); + + let (q, f) = make_queue_and_fence(); + let (alloc, list) = make_title_list(); + + let mut words = [0u64; 6]; + for (i, slot_word) in words.iter_mut().enumerate() { + if i > 0 { + reset_title_list(list, alloc); + } + let seg = crate::list::host_list(list).expect("host list"); + let val = (i as u64 + 1) * 100; + seg.defer_write((slot_word as *mut u64).cast(), Written::Value(val), 8); + close_title_list(list); + queue_execute(q, &[list]); + queue_signal(q, f, i as u64 + 1); + } + + // Simulates PresentX draining `victory-submit` + any active flight. + crate::queue::drain_submit(crate::queue::Why::Present); + + assert_eq!(crate::fence::value(f), 6); + assert!(!host.has_in_flight()); + for (i, &w) in words.iter().enumerate() { + assert_eq!(w, (i as u64 + 1) * 100, "submission {i} BoP mismatch"); + } + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 7a71c08d..e74c311f 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -128,7 +128,16 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { } } account().submissions += 1; - pump(&mut held, Why::Submission); + if crate::host::async_submit_enabled() { + drop(held); + ensure_submit_worker(); + wake_submit(); + } else if crate::host::flight1_enabled() { + drop(held); + pump_unlocked(Why::Submission); + } else { + pump(&mut held, Why::Submission); + } return; } static ONCE: AtomicBool = AtomicBool::new(false); @@ -137,8 +146,32 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { } } +#[cfg(all(windows, test))] +pub(crate) fn create_direct_for_test() -> This { + let null = std::ptr::null(); + let desc = QueueDesc { + kind: 0, + priority: 0, + flags: 0, + nodes: 0, + }; + let mut q = null; + assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + q +} + +#[cfg(all(windows, test))] +pub(crate) fn execute_for_test(this: This, lists: &[This]) { + execute(this, lists.len() as u32, lists.as_ptr()); +} + +#[cfg(all(windows, test))] +pub(crate) fn signal_for_test(this: This, fence: This, value: u64) -> HRESULT { + signal(this, fence, value) +} + /// What ran held work: the title's submission, a queue's Signal or Wait, a -/// CPU fence call, PresentX, or our timer. +/// CPU fence call, PresentX, our timer, or a completed Flight-1 landing. #[derive(Clone, Copy, Debug)] pub(crate) enum Why { Submission, @@ -147,10 +180,12 @@ pub(crate) enum Why { Fence, Present, Timer, + #[cfg(windows)] + Flight, } #[cfg(windows)] -use crate::hold::Item; +use crate::hold::{Item, Ready}; /// Every queue's held work. #[cfg(windows)] @@ -159,6 +194,225 @@ type Holding = crate::hold::Held>; #[cfg(windows)] static HELD: std::sync::Mutex = std::sync::Mutex::new(crate::hold::Held::new()); +/// Serializes unlocked pumping (`victory-submit`, `drain_submit`, and +/// `VICTORY_FLIGHT1=1` direct calls). Strictly above `HELD` in the lock DAG. +#[cfg(windows)] +static SUBMIT_DRAIN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(windows)] +static SUBMIT_WORK: (std::sync::Mutex, std::sync::Condvar) = + (std::sync::Mutex::new(false), std::sync::Condvar::new()); + +#[cfg(windows)] +thread_local! { + /// True while this thread holds `SUBMIT_DRAIN` (so nested `Host::execute` + /// calls on the submit worker do not re-enter `drain_submit`). + static ON_SUBMIT_THREAD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(windows)] +struct OnSubmit(bool); + +#[cfg(windows)] +impl OnSubmit { + fn enter() -> Self { + Self(ON_SUBMIT_THREAD.with(|c| c.replace(true))) + } +} + +#[cfg(windows)] +impl Drop for OnSubmit { + fn drop(&mut self) { + ON_SUBMIT_THREAD.with(|c| c.set(self.0)); + } +} + +#[cfg(windows)] +fn ensure_submit_worker() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new() + .name("victory-submit".into()) + .spawn(submit_worker); + }); +} + +#[cfg(windows)] +fn wake_submit() { + *SUBMIT_WORK.0.lock().unwrap_or_else(|e| e.into_inner()) = true; + SUBMIT_WORK.1.notify_one(); +} + +#[cfg(windows)] +fn submit_worker() { + loop { + { + let mut work = SUBMIT_WORK.0.lock().unwrap_or_else(|e| e.into_inner()); + while !*work { + work = SUBMIT_WORK.1.wait(work).unwrap_or_else(|e| e.into_inner()); + } + *work = false; + } + pump_unlocked(Why::Submission); + } +} + +#[cfg(windows)] +fn start_held_timer() { + static TIMER: std::sync::Once = std::sync::Once::new(); + TIMER.call_once(|| { + let _ = std::thread::Builder::new() + .name("victory held work".into()) + .spawn(|| loop { + std::thread::sleep(std::time::Duration::from_millis(2)); + pump_held_if_free(Why::Timer); + }); + }); +} + +/// Pumps all currently ready segments/signals from `HELD` while holding +/// `SUBMIT_DRAIN` and releasing `HELD` around every host GPU call. +#[cfg(windows)] +fn pump_ready_under_drain(why: Why) -> bool { + let Some(host) = crate::host::host() else { + return false; + }; + let fence = |f: usize| crate::fence::value(f as This); + let mut moved_any = false; + let mut pieces = 0u32; + let mut segments_count = 0u32; + let mut unknown_count = 0u32; + let mut waited_all = Vec::new(); + let started = std::time::Instant::now(); + let mut ran = std::time::Duration::ZERO; + loop { + let next = { + let mut held = held(); + if held.is_empty() { + None + } else { + for (queue, waits) in held.force_older_than(VALVE) { + account().forced += 1; + tracing::warn!( + queue = kind(queue), + ?waits, + "held work runs without its waits after {VALVE:?} (safety valve)" + ); + } + let item = held.take_ready(&read_value, &fence); + if item.is_none() && !held.is_empty() { + start_held_timer(); + } + item + } + }; + let Some(ready) = next else { + break; + }; + moved_any = true; + match ready { + Ready::Signal { fence, value } => { + if !crate::host::flight1_enabled() + || !host.attach_signal(fence as This, value, true) + { + crate::fence::set(fence as This, value); + crate::fence::let_go(fence as This); + } + } + Ready::Segments { + queue, + segments, + waited, + unknown, + } => { + pieces += 1; + segments_count += segments.len() as u32; + unknown_count += unknown; + waited_all.extend(waited); + let at = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::PumpExecutes, 1); + if crate::host::flight1_enabled() { + host.execute_flight1(segments); + } else { + host.execute_sync_segments(segments); + } + ran += at.elapsed(); + held().finish_running(queue); + } + } + } + if segments_count > 0 || unknown_count > 0 { + let mut a = account(); + a.pump += started.elapsed().saturating_sub(ran); + a.pieces += pieces; + a.segments += segments_count; + a.unknown += unknown_count; + for (queue, waited) in waited_all { + a.released.push((kind(queue), waited, why)); + } + } + moved_any +} + +#[cfg(windows)] +fn pump_unlocked(why: Why) { + let _drain = SUBMIT_DRAIN.lock().unwrap_or_else(|e| e.into_inner()); + let _on = OnSubmit::enter(); + pump_ready_under_drain(why); +} + +/// Drains all runnable queued work on `victory-submit` and waits for any +/// active Flight-1 submission to finish completely (repeating if landing a +/// flight unblocks additional held work). +#[cfg(windows)] +pub(crate) fn drain_submit(why: Why) { + let Some(host) = crate::host::host() else { + return; + }; + if ON_SUBMIT_THREAD.with(std::cell::Cell::get) { + host.finish_flight_now(); + return; + } + let _drain = SUBMIT_DRAIN.lock().unwrap_or_else(|e| e.into_inner()); + let _on = OnSubmit::enter(); + loop { + let moved = pump_ready_under_drain(why); + let landed = host.finish_flight_now(); + if !moved && !landed && !host.has_in_flight() { + break; + } + } +} + +/// Called by synchronous `Host::execute` callers (`present`, `resource.rs`, +/// `composite`, `capture`) before touching the GPU so they execute strictly +/// after any queued async-submit work or in-flight Flight-1 submission. +#[cfg(windows)] +pub(crate) fn before_sync() { + if (crate::host::async_submit_enabled() || crate::host::flight1_enabled()) + && !ON_SUBMIT_THREAD.with(std::cell::Cell::get) + { + drain_submit(Why::Submission); + } +} + +/// Called by `victory-flight` (and `Quiet::drop`) strictly AFTER releasing +/// `Host::submitted`, in case a landed flight's BoP writes or fence signals +/// unblocked work held in `HELD`. +#[cfg(windows)] +pub(crate) fn on_flight_landed() { + if crate::host::async_submit_enabled() { + ensure_submit_worker(); + wake_submit(); + } else if crate::host::flight1_enabled() + && let Ok(_drain) = SUBMIT_DRAIN.try_lock() + { + let _on = OnSubmit::enter(); + pump_ready_under_drain(Why::Flight); + } +} + #[cfg(windows)] fn held() -> std::sync::MutexGuard<'static, Holding> { HELD.lock().unwrap_or_else(|e| e.into_inner()) @@ -167,7 +421,16 @@ fn held() -> std::sync::MutexGuard<'static, Holding> { /// Runs held work that may run now (`why` for the frame line). pub(crate) fn pump_held(why: Why) { #[cfg(windows)] - pump(&mut held(), why); + { + if crate::host::async_submit_enabled() { + ensure_submit_worker(); + wake_submit(); + } else if crate::host::flight1_enabled() { + pump_unlocked(why); + } else { + pump(&mut held(), why); + } + } #[cfg(not(windows))] let _ = why; } @@ -176,8 +439,20 @@ pub(crate) fn pump_held(why: Why) { /// value, our timer). pub(crate) fn pump_held_if_free(why: Why) { #[cfg(windows)] - if let Ok(mut held) = HELD.try_lock() { - pump(&mut held, why); + { + if crate::host::async_submit_enabled() { + if !held().is_empty() { + ensure_submit_worker(); + wake_submit(); + } + } else if crate::host::flight1_enabled() { + if let Ok(_drain) = SUBMIT_DRAIN.try_lock() { + let _on = OnSubmit::enter(); + pump_ready_under_drain(why); + } + } else if let Ok(mut held) = HELD.try_lock() { + pump(&mut held, why); + } } #[cfg(not(windows))] let _ = why; @@ -239,13 +514,7 @@ fn pump(held: &mut Holding, why: Why) { if held.is_empty() { return; } - static TIMER: std::sync::Once = std::sync::Once::new(); - TIMER.call_once(|| { - let _ = std::thread::Builder::new().name("victory held work".into()).spawn(|| loop { - std::thread::sleep(std::time::Duration::from_millis(2)); - pump_held_if_free(Why::Timer); - }); - }); + start_held_timer(); } /// The value a wait tests (4 or 8 bytes), if the memory can be read. @@ -296,7 +565,7 @@ fn account_frame(frame: u64) { return; } let longest = a.released.iter().map(|r| r.1).max().unwrap_or_default(); - let mut by = [0u32; 6]; + let mut by = [0u32; 7]; for r in &a.released { by[r.2 as usize] += 1; } @@ -386,11 +655,34 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if held.holds_work(this as usize) { crate::fence::keep(fence); held.push(this as usize, Item::Signal(fence as usize, value)); + if crate::host::async_submit_enabled() { + drop(held); + ensure_submit_worker(); + wake_submit(); + } else if crate::host::flight1_enabled() { + drop(held); + pump_unlocked(Why::Signal); + } else { + pump(&mut held, Why::Signal); + } + } else if crate::host::flight1_enabled() + && crate::host::host().is_some_and(|h| h.attach_signal(fence, value, false)) + { + drop(held); } else { crate::fence::set(fence, value); + // Another queue may wait for this fence. + if crate::host::async_submit_enabled() { + drop(held); + ensure_submit_worker(); + wake_submit(); + } else if crate::host::flight1_enabled() { + drop(held); + pump_unlocked(Why::Signal); + } else { + pump(&mut held, Why::Signal); + } } - // Another queue may wait for this fence. - pump(&mut held, Why::Signal); } #[cfg(not(windows))] { @@ -411,7 +703,16 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { if crate::host::host().is_some() && crate::fence::value(fence) < value { let mut held = held(); held.push(this as usize, Item::FenceWait(fence as usize, value)); - pump(&mut held, Why::Wait); + if crate::host::async_submit_enabled() { + drop(held); + ensure_submit_worker(); + wake_submit(); + } else if crate::host::flight1_enabled() { + drop(held); + pump_unlocked(Why::Wait); + } else { + pump(&mut held, Why::Wait); + } } #[cfg(not(windows))] let _ = (this, value); @@ -622,6 +923,13 @@ extern "system" fn present( // What may run before the frame is shown does. // shortcut: PresentX does not wait behind work the queue still holds (it // shows the frame as far as it ran); the frame line names such work. + #[cfg(windows)] + if crate::host::async_submit_enabled() || crate::host::flight1_enabled() { + drain_submit(Why::Present); + } else { + pump_held(Why::Present); + } + #[cfg(not(windows))] pump_held(Why::Present); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; #[cfg(windows)] @@ -783,8 +1091,13 @@ extern "system" fn copy_page_mappings( return E_INVALIDARG; } #[cfg(windows)] - if held().holds_work(this as usize) { - account().mappings += 1; + { + if crate::host::async_submit_enabled() || crate::host::flight1_enabled() { + drain_submit(Why::Submission); + } + if held().holds_work(this as usize) { + account().mappings += 1; + } } #[cfg(not(windows))] let _ = this; From c67735cc7096d0590e100afc2166ce857b5a22b9 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 21:47:44 +0000 Subject: [PATCH 2/2] perf(gpu): fix Flight-1 GPU timing/lock hygiene and add coalescing take_ready_with --- crates/victory-gpu/src/hold.rs | 317 +++++++++++++++++++++++--- crates/victory-gpu/src/host.rs | 12 +- crates/victory-gpu/src/host/flight.rs | 43 +++- crates/victory-gpu/src/queue.rs | 29 ++- 4 files changed, 349 insertions(+), 52 deletions(-) diff --git a/crates/victory-gpu/src/hold.rs b/crates/victory-gpu/src/hold.rs index 652380c0..7914fbb2 100644 --- a/crates/victory-gpu/src/hold.rs +++ b/crates/victory-gpu/src/hold.rs @@ -85,28 +85,40 @@ pub(crate) struct Pumped { pub(crate) unknown: u32, } +/// Predicate checking whether a ready segment can join an in-progress +/// coalesced batch. +#[cfg(any(windows, test))] +pub(crate) type CanJoin<'a, S> = &'a dyn Fn(&[(S, bool)], &S) -> bool; + /// One ready step popped from [`Held`] so the caller can release the `HELD` /// lock while running it on the host GPU. #[cfg(any(windows, test))] pub(crate) enum Ready { - /// Consecutive ready segments from `queue`. `queue` stays marked running + /// Ready segments popped as one host submission (from one queue, or + /// coalesced across queues and bottom-of-pipe dependencies when + /// `coalesce` is enabled), paired with whether a global UAV barrier must + /// precede each segment, plus any mid-batch `Item::Signal`s to attach + /// behind the submission. Every queue in `queues` stays marked running /// until [`Held::finish_running`] is called so later submissions and - /// signals on the same queue wait behind it. + /// signals on those queues wait behind it. Segments { - queue: usize, - segments: Vec, + queues: Vec, + segments: Vec<(S, bool)>, + signals: Vec<(usize, u64)>, waited: Vec<(usize, Duration)>, unknown: u32, + coalesced_bop_waits: u32, + hazard_splits: u32, }, - /// A fence signal ready at the head of `queue`. + /// A fence signal ready at the head of a queue with no preceding segments. Signal { fence: usize, value: u64 }, } /// Every queue's held work. pub(crate) struct Held { queues: Vec<(usize, Fifo)>, - /// Queue whose popped segments are currently executing outside the lock. - running: Option, + /// Queues whose popped segments are currently launching outside the lock. + running: Vec, } /// A queue's items, each with when it was pushed and whether it is fresh @@ -123,7 +135,7 @@ impl Held { pub(crate) const fn new() -> Self { Held { queues: Vec::new(), - running: None, + running: Vec::new(), } } } @@ -239,17 +251,180 @@ impl Held { /// Pops the next ready batch of segments or ready fence signal so the /// caller can drop the `HELD` lock before invoking the host GPU. + /// When `coalesce` is `true`, accumulates ready segments across all + /// non-running queues (including segments whose memory waits are satisfied + /// by an earlier segment's deferred bottom-of-pipe writes via `will_write`, + /// gated at cross-queue / BoP / fence-wait boundaries by `can_join`) and + /// defers mid-batch `Item::Signal`s into `Ready::Segments::signals`. /// When [`Ready::Segments`] is returned, the caller must call - /// [`Self::finish_running`] with the same `queue` once the submission - /// call returns. + /// [`Self::finish_running`] with `queues` once the submission call returns. + #[cfg(any(windows, test))] + pub(crate) fn take_ready_with( + &mut self, + read: &dyn Fn(u64, u8) -> Option, + fence: &dyn Fn(usize) -> u64, + will_write: &dyn Fn(&S, &ValueWait) -> bool, + can_join: CanJoin<'_, S>, + coalesce: bool, + ) -> Option> { + if !coalesce { + return self.take_ready_per_queue(read, fence); + } + let mut piece: Vec<(S, bool)> = Vec::new(); + let mut signals: Vec<(usize, u64)> = Vec::new(); + let mut queues_touched: Vec = Vec::new(); + let mut waited: Vec<(usize, Duration)> = Vec::new(); + let mut unknown = 0u32; + let mut coalesced_bop_waits = 0u32; + let mut hazard_splits = 0u32; + let mut last_queue: Option = None; + let mut split_now = false; + + let mark_touched = |touched: &mut Vec, q: usize| { + if !touched.contains(&q) { + touched.push(q); + } + }; + + loop { + let mut moved = false; + for (queue, items) in &mut self.queues { + if self.running.contains(queue) { + continue; + } + let mut pending_fence_barrier = false; + let mut popped_pending_waits: Vec<(Item, Instant, bool)> = Vec::new(); + loop { + match items.front_mut() { + None => break, + Some((Item::FenceWait(f, v), _, fresh)) => { + let mem_ok = fence(*f) >= *v; + let pending_ok = !mem_ok + && signals.iter().any(|&(sf, sv)| sf == *f && sv >= *v); + if !mem_ok && !pending_ok { + *fresh = false; + break; + } + if let Some(entry) = items.pop_front() { + if pending_ok { + pending_fence_barrier = true; + popped_pending_waits.push(entry); + } + moved = true; + } + } + Some((Item::Signal(..), ..)) => { + if piece.is_empty() && signals.is_empty() { + if let Some((Item::Signal(f, v), ..)) = items.pop_front() { + self.queues.retain(|(_, q)| !q.is_empty()); + return Some(Ready::Signal { fence: f, value: v }); + } + break; + } + if let Some((Item::Signal(f, v), ..)) = items.pop_front() { + popped_pending_waits.clear(); + signals.push((f, v)); + mark_touched(&mut queues_touched, *queue); + moved = true; + } + } + Some((Item::Segment(seg, waits), since, fresh)) => { + let mut ok = true; + let mut via_bop = 0u32; + let mut seg_unknown = 0u32; + for wait in waits.iter() { + match wait.holds(read) { + Some(true) => {} + Some(false) => { + if piece + .iter() + .rev() + .any(|(prev, _)| will_write(prev, wait)) + { + via_bop += 1; + } else { + ok = false; + } + } + None => seg_unknown += 1, + } + } + let is_join_boundary = !piece.is_empty() + && (last_queue != Some(*queue) + || via_bop > 0 + || pending_fence_barrier); + if !ok { + *fresh = false; + unknown += seg_unknown; + for entry in popped_pending_waits.drain(..).rev() { + items.push_front(entry); + } + break; + } + if is_join_boundary && !can_join(&piece, seg) { + hazard_splits += 1; + split_now = true; + for entry in popped_pending_waits.drain(..).rev() { + items.push_front(entry); + } + break; + } + if !*fresh { + waited.push((*queue, since.elapsed())); + } + unknown += seg_unknown; + coalesced_bop_waits += via_bop; + let barrier_before = + via_bop > 0 || std::mem::take(&mut pending_fence_barrier); + popped_pending_waits.clear(); + if let Some((Item::Segment(s, _), ..)) = items.pop_front() { + piece.push((s, barrier_before)); + last_queue = Some(*queue); + mark_touched(&mut queues_touched, *queue); + moved = true; + } + } + } + } + for entry in popped_pending_waits.drain(..).rev() { + items.push_front(entry); + } + if split_now { + break; + } + } + if split_now || !moved { + break; + } + } + self.queues.retain(|(_, items)| !items.is_empty()); + if !piece.is_empty() { + for &q in &queues_touched { + if !self.running.contains(&q) { + self.running.push(q); + } + } + return Some(Ready::Segments { + queues: queues_touched, + segments: piece, + signals, + waited, + unknown, + coalesced_bop_waits, + hazard_splits, + }); + } + None + } + #[cfg(any(windows, test))] - pub(crate) fn take_ready( + fn take_ready_per_queue( &mut self, read: &dyn Fn(u64, u8) -> Option, fence: &dyn Fn(usize) -> u64, ) -> Option> { for (queue, items) in &mut self.queues { - if self.running == Some(*queue) { + if self.running.contains(queue) { continue; } let mut segments = Vec::new(); @@ -293,19 +468,22 @@ impl Held { waited.push((*queue, since.elapsed())); } if let Some((Item::Segment(s, _), ..)) = items.pop_front() { - segments.push(s); + segments.push((s, false)); } } } } if !segments.is_empty() { let q = *queue; - self.running = Some(q); + self.running.push(q); return Some(Ready::Segments { - queue: q, + queues: vec![q], segments, + signals: Vec::new(), waited, unknown, + coalesced_bop_waits: 0, + hazard_splits: 0, }); } } @@ -313,24 +491,22 @@ impl Held { None } - /// Clears the running marker set by [`Self::take_ready`] once the popped - /// batch has been handed to the host GPU. + /// Clears the running markers set by [`Self::take_ready_with`] once the + /// popped batch has been handed to the host GPU. #[cfg(any(windows, test))] - pub(crate) fn finish_running(&mut self, queue: usize) { - if self.running == Some(queue) { - self.running = None; - } + pub(crate) fn finish_running(&mut self, queues: &[usize]) { + self.running.retain(|q| !queues.contains(q)); self.queues.retain(|(_, items)| !items.is_empty()); } /// Whether no queue holds anything and none is currently running. pub(crate) fn is_empty(&self) -> bool { - self.running.is_none() && self.queues.is_empty() + self.running.is_empty() && self.queues.is_empty() } /// Whether `queue` holds anything or has a popped batch still launching. pub(crate) fn holds_work(&self, queue: usize) -> bool { - self.running == Some(queue) + self.running.contains(&queue) || self.queues.iter().any(|(q, items)| *q == queue && !items.is_empty()) } @@ -559,38 +735,105 @@ mod tests { held.push(1, Item::Segment("b", vec![])); let read = |_: u64, _| Some(0u64); let fence = |_: usize| 0u64; + let no_write = |_: &&str, _: &ValueWait| false; + let no_join = |_: &[(&str, bool)], _: &&str| false; - match held.take_ready(&read, &fence) { + match held.take_ready_with(&read, &fence, &no_write, &no_join, false) { Some(Ready::Segments { - queue, segments, .. + queues, segments, .. }) => { - assert_eq!(queue, 1); - assert_eq!(segments, ["a"]); + assert_eq!(queues, [1]); + assert_eq!(segments, [("a", false)]); } _ => panic!("expected segments"), } - // Queue 1 is marked running: holds_work stays true and take_ready - // must not pop its queued Signal before finish_running(1). + // Queue 1 is marked running: holds_work stays true and take_ready_with + // must not pop its queued Signal before finish_running(&[1]). assert!(held.holds_work(1)); assert!(!held.is_empty()); - assert!(held.take_ready(&read, &fence).is_none()); + assert!(held + .take_ready_with(&read, &fence, &no_write, &no_join, false) + .is_none()); - held.finish_running(1); - match held.take_ready(&read, &fence) { + held.finish_running(&[1]); + match held.take_ready_with(&read, &fence, &no_write, &no_join, false) { Some(Ready::Signal { fence: f, value }) => assert_eq!((f, value), (9, 1)), _ => panic!("expected signal"), } - match held.take_ready(&read, &fence) { + match held.take_ready_with(&read, &fence, &no_write, &no_join, false) { Some(Ready::Segments { - queue, segments, .. + queues, segments, .. }) => { - assert_eq!(queue, 1); - assert_eq!(segments, ["b"]); + assert_eq!(queues, [1]); + assert_eq!(segments, [("b", false)]); } _ => panic!("expected trailing segment"), } - held.finish_running(1); + held.finish_running(&[1]); assert!(!held.holds_work(1)); assert!(held.is_empty()); } + + #[test] + fn take_ready_coalesced_merges_cross_queue_bop_and_deferred_signals() { + let mut held = Held::default(); + // Queue 2 waits on BoP 0x100 >= 1 written by Queue 1's segment "g1". + held.push(2, Item::Segment("c1", vec![ge(0x100, 1)])); + // Queue 3 waits on fence 9 >= 1 signalled after "g1". + held.push(3, Item::FenceWait(9, 1)); + held.push(3, Item::Segment("c2", vec![])); + // Queue 1 produces "g1" (writes 0x100 = 1), signals fence 9, then "g2". + held.push(1, Item::Segment("g1", vec![])); + held.push(1, Item::Signal(9, 1)); + held.push(1, Item::Segment("g2", vec![])); + + let read = |_: u64, _| Some(0u64); + let fence = |_: usize| 0u64; + let will_write = |seg: &&str, wait: &ValueWait| *seg == "g1" && wait.address == 0x100; + let can_join = |_: &[(&str, bool)], next: &&str| *next != "c2"; + + // First coalesced batch picks up Queue 1 ("g1", deferred Signal(9,1), "g2") + // AND Queue 2 ("c1" via BoP with barrier_before=true), then splits before + // Queue 3 ("c2") because `can_join` rejects it at the join boundary. + match held.take_ready_with(&read, &fence, &will_write, &can_join, true) { + Some(Ready::Segments { + queues, + segments, + signals, + coalesced_bop_waits, + hazard_splits, + .. + }) => { + assert_eq!(queues, [1, 2]); + assert_eq!(segments, [("g1", false), ("g2", false), ("c1", true)]); + assert_eq!(signals, [(9, 1)]); + assert_eq!(coalesced_bop_waits, 1); + assert_eq!(hazard_splits, 1); + } + _ => panic!("expected coalesced batch"), + } + assert!(held.holds_work(1)); + assert!(held.holds_work(2)); + held.finish_running(&[1, 2]); + + // Queue 3's FenceWait(9, 1) was restored when "c2" split out, so "c2" + // stays blocked until fence 9 actually reaches 1. + assert!(held + .take_ready_with(&read, &fence, &will_write, &can_join, true) + .is_none()); + + // Once the first batch's signal (9, 1) has landed, Queue 3's "c2" runs. + let fence_after = |f: usize| if f == 9 { 1 } else { 0 }; + match held.take_ready_with(&read, &fence_after, &will_write, &can_join, true) { + Some(Ready::Segments { + queues, segments, .. + }) => { + assert_eq!(queues, [3]); + assert_eq!(segments, [("c2", false)]); + } + _ => panic!("expected c2 after fence"), + } + held.finish_running(&[3]); + assert!(held.is_empty()); + } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d3004364..674df4e3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1655,6 +1655,10 @@ impl Host { let mut next_log_secs = 1u64; let mut logged_hang = false; loop { + // SAFETY: our fence. + if unsafe { self.fence.GetCompletedValue() } >= value { + return; + } // SAFETY: our event and fence. let woke = unsafe { WaitForSingleObject(event, poll_ms) }; // SAFETY: as above. @@ -1797,7 +1801,7 @@ impl Host { let holding = Holding::enter(); // Ensure the GPU is completely idle before descriptor heap creation / // null-fill begins (VIctory-macOS issue #31). - let landed = self.finish_flight_locked(&mut held, None); + let landed = self.finish_flight_locked(&mut held, None, None); Some(Quiet { holding: Some(holding), held: Some(held), @@ -1822,7 +1826,7 @@ impl Host { // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let _holding = Holding::enter(); - self.finish_flight_locked(&mut submitted, None); + self.finish_flight_locked(&mut submitted, None, None); #[cfg(feature = "diagnostics")] let gpu_timing = timing(); @@ -1996,6 +2000,7 @@ impl Host { prep.heaps, prep.started, prep.prepared, + prep.prepared.elapsed(), removed_in, ); // A listed frame: what this submission's lists drew, as it is now @@ -2184,6 +2189,7 @@ impl Host { /// Runs post-GPU completion work under `self.submitted` after the host /// fence has completed: timing/removal checks, mark & shadow copy-back, /// `after` callbacks, bottom-of-pipe writes, retirement, and info-queue logs. + #[allow(clippy::too_many_arguments)] fn finish_post_gpu( &self, runs: &[&HostList], @@ -2191,9 +2197,9 @@ impl Host { heaps: Vec>, started: std::time::Instant, prepared: std::time::Instant, + gpu: std::time::Duration, removed_in: Option, ) { - let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); // The host resets a device whose submission runs for about 2 s. diff --git a/crates/victory-gpu/src/host/flight.rs b/crates/victory-gpu/src/host/flight.rs index 7a1e54ae..6ff9aecd 100644 --- a/crates/victory-gpu/src/host/flight.rs +++ b/crates/victory-gpu/src/host/flight.rs @@ -152,6 +152,7 @@ struct InFlight { split_count: usize, started: std::time::Instant, prepared: std::time::Instant, + launched: std::time::Instant, waited: bool, } @@ -183,7 +184,7 @@ impl Host { // Wait-Before-Prep: drain Flight N-1 completely before Flight N // touches any shared Shadow, descriptor heap, upload staging pool, or // Mark buffer. - self.finish_flight_locked(&mut submitted, None); + self.finish_flight_locked(&mut submitted, None, None); let prep = { let run_refs: Vec<&HostList> = segments.iter().map(|s| &**s).collect(); @@ -230,6 +231,7 @@ impl Host { group.push(mark.list()); } let queue = self.queue(); + let launched = std::time::Instant::now(); // SAFETY: closed lists; fence and events are ours. let waited = unsafe { let mut first = 0; @@ -269,6 +271,7 @@ impl Host { split_count, started: prep.started, prepared: prep.prepared, + launched, waited, }; { @@ -325,17 +328,20 @@ impl Host { } let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let _holding = Holding::enter(); - self.finish_flight_locked(&mut submitted, None) + self.finish_flight_locked(&mut submitted, None, None) } /// Completes any active flight under `Host::submitted`. When /// `only_if_fence` is `Some(v)`, only lands if the active flight matches /// fence value `v` (used by `victory-flight` so it never blocks on a newer - /// flight while holding `Host::submitted`). + /// flight while holding `Host::submitted`). `waited_at`, when provided by + /// `victory-flight`, records the exact instant the GPU fence completed so + /// lock-wait latency is never billed as GPU execution time. pub(super) fn finish_flight_locked( &self, submitted: &mut u64, only_if_fence: Option, + waited_at: Option, ) -> bool { let flight = { let mut state = self.flight.lock().unwrap_or_else(|e| e.into_inner()); @@ -350,9 +356,18 @@ impl Host { return false; }; - if flight.waited { - self.wait_for(flight.fence_value); - } + let gpu_done = if flight.waited { + // SAFETY: plain fence completion query. + if unsafe { self.fence.GetCompletedValue() } < flight.fence_value { + self.wait_for(flight.fence_value); + std::time::Instant::now() + } else { + waited_at.unwrap_or_else(std::time::Instant::now) + } + } else { + std::time::Instant::now() + }; + let gpu_duration = gpu_done.saturating_duration_since(flight.launched); #[cfg(test)] super::tests::native_call_group(flight.waited); @@ -393,6 +408,7 @@ impl Host { flight.heaps, flight.started, flight.prepared, + gpu_duration, None, ); } @@ -439,10 +455,23 @@ fn spawn_flight_worker() { if waited { host.wait_for_on_event(host.flight_event, fence_value, 250); } + let gpu_done = std::time::Instant::now(); + // Skip acquiring `Host::submitted` if `victory-submit` already + // claimed and began landing this flight while we waited. + let still_mine = host + .flight + .lock() + .unwrap_or_else(|e| e.into_inner()) + .in_flight + .as_ref() + .is_some_and(|f| f.fence_value == fence_value); + if !still_mine { + continue; + } let landed = { let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); let _holding = Holding::enter(); - host.finish_flight_locked(&mut submitted, Some(fence_value)) + host.finish_flight_locked(&mut submitted, Some(fence_value), Some(gpu_done)) }; // Strictly AFTER dropping `Host::submitted`: wake held work or // the submit worker in case this flight's BoP writes or fence diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index e74c311f..19fcd39c 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -299,7 +299,12 @@ fn pump_ready_under_drain(why: Why) -> bool { "held work runs without its waits after {VALVE:?} (safety valve)" ); } - let item = held.take_ready(&read_value, &fence); + let no_write = + |_: &std::sync::Arc, _: &crate::hold::ValueWait| false; + let no_join = |_: &[(std::sync::Arc, bool)], + _: &std::sync::Arc| false; + let item = + held.take_ready_with(&read_value, &fence, &no_write, &no_join, false); if item.is_none() && !held.is_empty() { start_held_timer(); } @@ -320,25 +325,39 @@ fn pump_ready_under_drain(why: Why) -> bool { } } Ready::Segments { - queue, + queues, segments, + signals, waited, unknown, + coalesced_bop_waits, + hazard_splits, } => { + let _ = (coalesced_bop_waits, hazard_splits); pieces += 1; segments_count += segments.len() as u32; unknown_count += unknown; waited_all.extend(waited); + let run_segments: Vec> = + segments.into_iter().map(|(s, _)| s).collect(); let at = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::PumpExecutes, 1); if crate::host::flight1_enabled() { - host.execute_flight1(segments); + host.execute_flight1(run_segments); } else { - host.execute_sync_segments(segments); + host.execute_sync_segments(run_segments); + } + for (fence, value) in signals { + if !crate::host::flight1_enabled() + || !host.attach_signal(fence as This, value, true) + { + crate::fence::set(fence as This, value); + crate::fence::let_go(fence as This); + } } ran += at.elapsed(); - held().finish_running(queue); + held().finish_running(&queues); } } }