From ef51870ee13e51d86995eade01e585a1196b4103 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:03 -0600 Subject: [PATCH 01/13] Card steps: the plan joins its ranges once a round, each place is looked up once One by one, every fill of the 2,800 a frame sorted the ranges again: the unmeasured 16 ms before a submission's preparing (profile cpu-1). Up to 12,288 steps a submission. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/card_steps.rs | 94 ++++++++++++++++------- 1 file changed, 67 insertions(+), 27 deletions(-) diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 881d1b2..808fa7c 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -88,7 +88,7 @@ pub(super) fn stage() -> u32 { const BETWEEN: u64 = 4 << 20; /// The most steps of a submission done this way. -const MOST: usize = 4096; +const MOST: usize = 12288; /// How a fill's bytes get where its list reads them, if the card brings /// them. @@ -247,6 +247,9 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { } } while !more.is_empty() { + // (Joined once for the round: one by one the 2,800 fills of a frame + // sorted the ranges each time, 16 ms of the submitting thread.) + let (mut reads, mut writes) = (Vec::new(), Vec::new()); for i in std::mem::take(&mut more) { takes(&does[i])?; taken[i] = true; @@ -254,10 +257,14 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { if w.0 < w.1 && meet(r, w) { return Err("a copy onto itself"); } - join_ranges(&mut read, [r]); - join_ranges(&mut written, [w]); + reads.push(r); + writes.push(w); } } + join_ranges(&mut read, reads); + if writes.iter().any(|w| w.0 < w.1) { + join_ranges(&mut written, writes); + } if taken.iter().filter(|t| **t).count() > MOST { return Err("too many steps depend on it"); } @@ -288,7 +295,9 @@ fn plan(does: &[Does], stage: u32) -> Result, &'static str> { let mut behind: Vec<(usize, usize)> = Vec::new(); for (i, d) in does.iter().enumerate() { if taken[i] { - if let Some((_, w)) = reads_writes(d) { + if let Some((_, w)) = reads_writes(d) + && w.0 < w.1 + { join_ranges(&mut behind, [w]); } continue; @@ -368,9 +377,25 @@ fn holder(writers: &[Writer], from: usize, to: usize) -> Result, &'s /// Whether every page of `[from, to)` can be read (through the kernel: /// asking Windows walks the page tables, milliseconds in the title's heap). -fn mapped(from: usize, to: usize) -> bool { - let mut bytes = vec![0u8; to - from]; - read_into(from as *const u8, &mut bytes) +/// `room`: for what is read. +fn mapped(from: usize, to: usize, room: &mut Vec) -> bool { + if room.len() < to - from { + room.resize(to - from, 0); + } + read_into(from as *const u8, &mut room[..to - from]) +} + +/// A table by addresses and numbers of ours. +type HashMap = std::collections::HashMap>; + +/// Where the bytes of the fill that is `step` (its list by address, its place +/// in it) go. +fn fill_to(runs: &[&HostList], step: (usize, usize)) -> Option { + let list = runs.iter().find(|l| std::ptr::from_ref::(l) as usize == step.0)?; + match list.deferred().copies.get(step.1)? { + Step::Fill(_, _, _, to) => to.clone(), + _ => None, + } } /// A step done on the card. @@ -475,7 +500,7 @@ static DONE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::Ato /// list by address, their place in it). pub(super) struct Taken { own: Own, - steps: std::collections::HashSet<(usize, usize)>, + steps: std::collections::HashSet<(usize, usize), std::hash::BuildHasherDefault>, copied: Vec<(Arc, usize, usize)>, } @@ -543,8 +568,6 @@ impl Host { fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result, &'static str> { let mut does = Vec::new(); - // Where the fills' bytes go. - let mut fills = std::collections::HashMap::new(); // Which step each is. One list's lock at a time: a submission may // name a list twice. let mut steps = Vec::new(); @@ -561,12 +584,7 @@ impl Host { src: *src, len: *len, asked: read_blocked(written, *src, *len), - to: { - if let Some(to) = to { - fills.insert(does.len(), to.clone()); - } - to.is_some() - }, + to: to.is_some(), }, Step::Texture(staging) => { let (at, len) = staging.memory(); @@ -605,7 +623,11 @@ impl Host { let mut ops: Vec = Vec::with_capacity(chosen.len()); // The places read (host copy, address, bytes, level): where in the // buffer between their bytes are. - let mut places = std::collections::HashMap::new(); + let mut places: HashMap<(usize, usize, usize, u32), u64> = HashMap::default(); + // Some 2,800 fills a frame, of a few hundred places: what holds each + // is looked for once, as long as no copy is added to the writers. + let mut held: HashMap<(usize, usize), Arc> = HashMap::default(); + let mut room = Vec::new(); let mut end = 0u64; for &(i, level) in &chosen { let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else { @@ -617,7 +639,14 @@ impl Host { if len == 0 { return Err("nothing to read"); } - let from = holder(&writers, src, src + len)?; + let from = match held.get(&(src, len)) { + Some(from) => from.clone(), + None => { + let from = holder(&writers, src, src + len)?; + held.insert((src, len), from.clone()); + from + } + }; let place = (Arc::as_ptr(&from) as usize, src, len, level); let at = match places.get(&place) { Some(&at) => at, @@ -625,7 +654,7 @@ impl Host { if end + len as u64 > BETWEEN { return Err("too much at once"); } - if !mapped(src, src + len) { + if !mapped(src, src + len, &mut room) { return Err("not all of what it reads is mapped"); } let at = end; @@ -640,7 +669,7 @@ impl Host { if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) { return Err("another host copy of what it writes is read"); } - if !mapped(dst, dst + len) { + if !mapped(dst, dst + len, &mut room) { return Err("not all of what it writes is mapped"); } // What the steps behind it read of it is in that host @@ -651,11 +680,12 @@ impl Host { to: dst + len, copy: true, }); + held.clear(); To::Copy(to, dst) } - _ => match fills.get(&i) { - Some(FillTo::Slot(heap, index)) => To::Slot(*heap, *index), - Some(FillTo::Buffer(buffer)) => To::Buffer(buffer.clone()), + _ => match fill_to(runs, steps[i]) { + Some(FillTo::Slot(heap, index)) => To::Slot(heap, index), + Some(FillTo::Buffer(buffer)) => To::Buffer(buffer), None => continue, }, }; @@ -671,13 +701,23 @@ impl Host { return Err("no host list or buffer for it"); }; // First every refresh, then the writes: the bytes compared with are - // the title's. + // the title's. (One step for each host copy, over all that is read of + // it: a flush brings a copy up to date from the first range asked for + // to the last, whatever the steps.) + let mut spans: ByCopy<(Arc, usize, usize)> = ByCopy::default(); for op in &ops { - op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64); - if let To::Copy(to, dst) = &op.to { - to.refresh(&own.list, *dst as u64, op.len as u64); + let to = match &op.to { + To::Copy(to, dst) => Some((to, *dst)), + _ => None, + }; + for (shadow, at) in std::iter::once((&op.from.0, op.from.1)).chain(to) { + let span = spans.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| (shadow.clone(), at, at + op.len)); + (span.1, span.2) = (span.1.min(at), span.2.max(at + op.len)); } } + for (shadow, from, to) in spans.into_values() { + shadow.refresh(&own.list, from as u64, (to - from) as u64); + } let mut copied = Vec::new(); for op in &ops { if let To::Copy(to, dst) = &op.to { From 74005234a2eab431aac0916ed14063e37d09af84 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:03 -0600 Subject: [PATCH 02/13] The title's bytes under flights' writes go up by whole words (VICTORY_UNDER_WORDS=0: by bytes) Words are pairs of one dispatch and are not counted against the 4,096 copies a submission sends up, at which it stood until the flights had landed. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 1 + crates/victory-gpu/src/host/send.rs | 32 ++++++++++++++++++++++++++++- crates/victory-gpu/src/shadow.rs | 10 +++++++-- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..2373a17 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3161,6 +3161,7 @@ mod torn; pub(crate) mod upcheck; #[cfg(test)] +pub(crate) use send::{goes_as_words, words_under}; mod late_tests { use super::{continues, join_ranges, touches}; diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 9227399..1373481 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -30,6 +30,36 @@ pub(super) fn own() -> bool { /// Runs up to this many bytes go as pairs. const SHORT: usize = 256; +/// Whether a run of `len` bytes at offset `at` of a copy goes as pairs. +fn short(at: usize, len: usize) -> bool { + len <= SHORT && at % 4 == 0 && len % 4 == 0 +} + +/// Whether a run of `len` bytes at offset `at` of a copy in the card's memory +/// is no copy command of its own, but pairs of one dispatch. +pub(crate) fn goes_as_words(at: usize, len: usize) -> bool { + own() && short(at, len) +} + +/// Whether the title's bytes that go in under flights' writes +/// (`Shadow::merge_under_writes`) go in by whole words +/// (`VICTORY_UNDER_WORDS=0`: by the bytes that changed, as before). +/// +/// By bytes nearly every run (a float's three low bytes) was a copy command +/// of its own, and a submission with more than 4,096 of them stood until the +/// flights had landed: 4 to 14 ms of a steady frame (session play-1125-0203: +/// "more changed runs than a submission sends up"), for some 20 KB. Whole +/// words are pairs of one dispatch, and are not counted. +/// +/// A word is taken to be the title's or the shaders', not shared: where the +/// title changed a byte of a word of which a flight's shader writes another +/// byte, that byte is as it was before the flight. The landing rests on the +/// same ([`crate::shadow::exact_back`]). +pub(crate) fn words_under() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| own() && std::env::var_os("VICTORY_UNDER_WORDS").is_none_or(|v| v != "0")) +} + const SCATTER: &str = r#" #define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" cbuffer Part : register(b0) { uint at; uint count; }; @@ -142,7 +172,7 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, us pass(host)?; // Runs of whole words of the copy: only those are pairs. (A byte beside // them in a word may be the card's.) - let short = |&(a, b): &(usize, usize)| b - a <= SHORT && a % 4 == 0 && b % 4 == 0; + let short = |&(a, b): &(usize, usize)| short(a, b - a); let mut at = 0u64; let mut copies = Vec::with_capacity(dirty.len()); for (_, ranges) in dirty { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 8b127df..72d4315 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3198,8 +3198,12 @@ impl Shadow { // SAFETY: inside the mapping of the copy's CPU side, // which only the submitting thread writes. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let runs = changed_runs(title, held); - if runs.len() > *runs_left { + // Whole words go up as pairs, all of them in one + // dispatch: only what is a copy of its own counts. + let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) }; + let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m); + let copies = runs.iter().filter(own).count(); + if copies > *runs_left { note_stale(2); return true; } @@ -3229,6 +3233,8 @@ impl Shadow { // written here and nothing around them. unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; held[r..r + m].copy_from_slice(&title[r..r + m]); + MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed); + self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m))); MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } From d4943c43fbf688fdb33b16ee327ce250d7f6110d Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:04 -0600 Subject: [PATCH 03/13] Snapshot memory, host lists and send memory kept for reuse (VICTORY_SNAPSHOT_POOL=8: as before) Made anew and given back all the time: 30 % of the submitting thread in the opening (profile cpu-1: allocations of snapshots 11, preludes 12, lists dropped 5, send memory 3). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host/send.rs | 4 ++- crates/victory-gpu/src/list.rs | 7 +++-- crates/victory-gpu/src/shadow.rs | 46 ++++++++++++++++++++--------- 3 files changed, 40 insertions(+), 17 deletions(-) diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 1373481..1962988 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -129,7 +129,9 @@ fn memory(host: &Host, size: u64) -> Option { return Some(spare.swap_remove(i)); } } - let size = size.next_multiple_of(8 << 20); + // By doubles, so that the next of about this size finds it: what + // submissions send differs from frame to frame. + let size = size.max(8 << 20).next_power_of_two(); let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || "bytes a submission sends up".into()); Some(Memory { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 140b755..a919fb5 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -218,11 +218,14 @@ unsafe impl Send for Idle {} #[cfg(windows)] static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); -/// The most host lists kept idle, and the most upload memory they may keep +/// The most host lists kept idle (128 were too few: flights land several at +/// a time, so lists were thrown away and others made in the same frame, with +/// their preludes and buffers, 12 % of the submitting thread in the opening, +/// profile cpu-1), and the most upload memory they may keep /// between them (a list keeps scratch chunks over a reset only while lists /// do not share them, `VICTORY_SCRATCH_POOL=0`). #[cfg(windows)] -const IDLE_MOST: (usize, u64) = (128, 256 << 20); +const IDLE_MOST: (usize, u64) = (512, 256 << 20); /// Whether host lists that have run are used again (on by default; /// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before). diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 72d4315..b140a27 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1197,20 +1197,40 @@ fn pooled(n: usize) -> Vec { v } -/// Returns a snapshot buffer to the pool: at most 8 kept, the largest, and -/// of those the largest one and the next ones up to `KEPT` bytes in all. +/// How many snapshot buffers are kept (`VICTORY_SNAPSHOT_POOL`; `8`: as +/// before). +/// +/// A frame gives some 330 ranges of copies in the PC's memory to shaders, and +/// most are of copies of their own; with two or three frames in the air eight +/// buffers were the eight largest, and every other snapshot was memory fresh +/// from the kernel and given back to it: 11 % of the submitting thread in the +/// opening (profile cpu-1: `NtAllocateVirtualMemory` under +/// [`Shadow::writing`]), and the page faults of filling it. +fn snapshots_kept() -> usize { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_SNAPSHOT_POOL").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1024)) +} + +/// Returns a snapshot buffer to the pool: at most [`snapshots_kept`] kept, +/// the largest, and of those the largest one and the next ones up to `KEPT` +/// bytes in all. fn give_back(v: Vec) { const KEPT: usize = 512 << 20; let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); pool.push(v); pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); - pool.truncate(8); - let (mut seen, mut total) = (0, 0usize); - pool.retain(|v| { - seen += 1; + let (mut kept, mut total) = (0, 0usize); + for v in pool.iter().take(snapshots_kept()) { total = total.saturating_add(v.capacity()); - seen == 1 || total <= KEPT - }); + if kept > 0 && total > KEPT { + break; + } + kept += 1; + } + // (Given back to the kernel without the lock: milliseconds.) + let gone = pool.split_off(kept); + drop(pool); + drop(gone); } const NOT_WATCHED: u8 = 2; @@ -3207,14 +3227,14 @@ impl Shadow { note_stale(2); return true; } - *runs_left -= runs.len(); + *runs_left -= copies; let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec()); - for (r, m) in runs { + for &(r, m) in &runs { held[r..r + m].copy_from_slice(&title[r..r + m]); - self.card_changed(at + r, at + r + m); - MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } + MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed); + self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m))); if let Some(was) = was { crate::host::upcheck::note(self.id, at, &was, held); } @@ -3233,8 +3253,6 @@ impl Shadow { // written here and nothing around them. unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; held[r..r + m].copy_from_slice(&title[r..r + m]); - MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed); - self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m))); MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); } From 30317314afd4511cc3663bdf5388708e5ce961aa Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:04 -0600 Subject: [PATCH 04/13] The heaps' records are brought up to date beside the preparing (VICTORY_HEAP_SYNC_ASIDE=0); a made slot is told without the lock (VICTORY_QUICK_MIRROR=0) Changed pages are compared sixteen records at a time. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 114 ++++++++++++++++++++-- crates/victory-gpu/src/descriptor/host.rs | 96 ++++++++++++++++-- crates/victory-gpu/src/host.rs | 11 ++- 3 files changed, 201 insertions(+), 20 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..043dd26 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -161,6 +161,96 @@ fn mirror(handle: u64) { } } +/// Whether [`sync_heaps`] is done (`VICTORY_HEAP_SYNC=0`: not). +#[cfg(windows)] +fn sync_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) +} + +/// Whether a submission's [`sync_heaps`] is done by a thread of its own +/// beside the rest of the preparing (`VICTORY_HEAP_SYNC_ASIDE=0`: in front of +/// it, as before). +/// +/// It took 13 ms a frame of the submitting thread (session play-1125-0203: +/// 230 changed heap pages and 470,000 slots in 30 submissions). What it makes +/// are the host heap's descriptors, which the card reads: it has to be done +/// before the lists go to the queue, and nothing of the preparing looks at +/// them (what a draw reads through a table it made itself, when recorded). +#[cfg(windows)] +fn sync_aside() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| sync_on() && std::env::var_os("VICTORY_HEAP_SYNC_ASIDE").is_none_or(|v| v != "0")) +} + +/// The thread's work: rounds asked for, rounds done. +#[cfg(windows)] +static SYNC_ROUNDS: (std::sync::Mutex<(u64, u64)>, std::sync::Condvar) = (std::sync::Mutex::new((0, 0)), std::sync::Condvar::new()); + +/// [`sync_heaps`], begun; done when it is dropped (with [`sync_aside`]), or +/// when this returns. +#[cfg(windows)] +pub(crate) struct SyncedHeaps(Option); + +#[cfg(windows)] +pub(crate) fn begin_sync_heaps() -> SyncedHeaps { + if !sync_aside() { + sync_heaps(); + return SyncedHeaps(None); + } + static STARTED: std::sync::Once = std::sync::Once::new(); + static THREAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + STARTED.call_once(|| { + let made = std::thread::Builder::new().name("victory-heap-sync".into()).spawn(|| { + let rounds = || SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + /// A round is over, however it ends. + struct Over; + impl Drop for Over { + fn drop(&mut self) { + SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()).1 += 1; + SYNC_ROUNDS.1.notify_all(); + } + } + loop { + let mut r = rounds(); + while r.0 == r.1 { + r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); + } + drop(r); + let _over = Over; + let _ = std::panic::catch_unwind(sync_heaps); + } + }); + THREAD.store(made.is_ok(), std::sync::atomic::Ordering::Release); + }); + if !THREAD.load(std::sync::atomic::Ordering::Acquire) { + sync_heaps(); + return SyncedHeaps(None); + } + let mut rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + rounds.0 += 1; + let mine = rounds.0; + drop(rounds); + SYNC_ROUNDS.1.notify_all(); + SyncedHeaps(Some(mine)) +} + +#[cfg(windows)] +impl Drop for SyncedHeaps { + fn drop(&mut self) { + let Some(mine) = self.0 else { + return; + }; + let began = std::time::Instant::now(); + let mut rounds = SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner()); + while rounds.1 < mine { + rounds = SYNC_ROUNDS.1.wait(rounds).unwrap_or_else(|e| e.into_inner()); + } + drop(rounds); + SYNCED[6].fetch_add(began.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + } +} + /// Mirrors records copied directly into placed shader-visible heaps. Calls /// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave /// only write-watch pages to reveal which slots changed. @@ -173,8 +263,7 @@ fn mirror(handle: u64) { #[cfg(windows)] pub(crate) fn sync_heaps() { use std::sync::atomic::Ordering::Relaxed; - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) { + if !sync_on() { return; } let started = std::time::Instant::now(); @@ -278,28 +367,30 @@ pub(crate) fn sync_heaps() { /// shader-visible heaps looked at, slots on them, slots whose record was /// not the one last seen and was mirrored, the microseconds it took; then /// new records left to the draws that read them through a table, and new -/// records that waited for one ([`host::HostHeap::copied_wait`]). +/// records that waited for one ([`host::HostHeap::copied_wait`]); and the +/// microseconds submissions waited for it ([`sync_aside`]). #[cfg(windows)] -pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { - let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); if pages == 0 { return; } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \ - draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms", + draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)", pages as f64 / frames, looked as f64 / frames, mirrored as f64 / frames, tabled as f64 / frames, later as f64 / frames, - micros as f64 / 1000.0 / frames + micros as f64 / 1000.0 / frames, + waited as f64 / 1000.0 / frames ); } @@ -320,6 +411,15 @@ fn changed_slots( first.min(last)..last } +/// `f` of the title heap at `heap`, if that heap still exists; it stays +/// until `f` is done. +#[cfg(windows)] +pub(crate) fn with_heap(heap: usize, f: impl FnOnce(&Heap) -> T) -> Option { + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + // SAFETY: registered heaps are live (removed when dropped). + heaps.iter().any(|&(_, _, h)| h == heap).then(|| f(unsafe { &*(heap as *const Heap) })) +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..8418b21 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -26,6 +26,9 @@ pub(crate) struct HostHeap { sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, + /// The same for a slot whose descriptor is made and stays (else 0): what + /// [`HostHeap::mirror`] asks first, without the lock. Changed under it. + quick: Vec, /// The records of the title's heap as the pass over records copied in /// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first /// use. @@ -1070,6 +1073,7 @@ impl HostHeap { dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), + quick: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), copied: Mutex::new(Vec::new()), waiting: Mutex::default(), away: Mutex::default(), @@ -1606,6 +1610,7 @@ impl HostHeap { /// Makes host slot `index` null again, as it is before its view is /// made: a null view of the kind it held. fn unmake(&self, made: &mut [u64], index: u32) { + self.quick_is(index, 0); let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { return; }; @@ -2019,15 +2024,7 @@ impl HostHeap { return; }; let records = &records[..last.len()]; - if last == records { - return; - } - for (n, (old, new)) in last.chunks_exact_mut(step).zip(records.chunks_exact(step)).enumerate() { - if old != new { - old.copy_from_slice(new); - out.push(first + n as u32); - } - } + changed_records(last, records, step, first, out); } /// Whether new records of draws' tables are left to the draws @@ -2099,12 +2096,24 @@ impl HostHeap { let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; // Generations start at 1, so a made slot's key is never 0. let key = u64::from(generation) << 32 | u64::from(i); + // Made from this record, and nothing has changed it: most of the + // asks, from five recording threads, behind one lock while another + // held it to make a descriptor (15 % of a recording thread's time in + // the opening, profile cpu-1). + if tag == VIEW_TAG + && quick_mirror() + && self.quick.get(index as usize).is_some_and(|k| k.load(std::sync::atomic::Ordering::Acquire) == key) + && let Some(view) = view_at(i, generation) + { + return Some(view); + } let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); let Some(view) = view else { // Not a view of ours (never written, or of a resource the // title released): nothing to read. if made[index as usize] != 0 { + self.quick_is(index, 0); made[index as usize] = 0; self.make_null(index); let _ = self.note_buffer(index, None, false); @@ -2147,6 +2156,7 @@ impl HostHeap { KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); return Some(view); } + self.quick_is(index, 0); made[index as usize] = if later { 0 } else { key }; let kept = if later { None @@ -2157,10 +2167,19 @@ impl HostHeap { null_for(&view, self.cpu(index)); } self.keep(index, kept.flatten()); + self.quick_is(index, made[index as usize]); } Some(view) } + /// Slot `index` is made from record `key` and stays so (0: not). Under + /// the lock of `made`. + fn quick_is(&self, index: u32, key: u64) { + if let Some(quick) = self.quick.get(index as usize) { + quick.store(key, std::sync::atomic::Ordering::Release); + } + } + /// Whether slot `index` is backed by a made host descriptor (tests). #[cfg(test)] pub(crate) fn made(&self, index: u32) -> bool { @@ -2987,6 +3006,65 @@ fn keep_views() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) } +/// Whether a slot already made from its record is told so without the lock +/// (`VICTORY_QUICK_MIRROR=0`: with it, as before). +fn quick_mirror() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUICK_MIRROR").is_none_or(|v| v != "0")) +} + +/// The records (`step` bytes each, the first is slot `first`) that differ +/// between `last` and `records` (of one length) go into `out` and `last`. +/// Most of a changed page is as it was: it is looked at sixteen records at a +/// time. +fn changed_records(last: &mut [u8], records: &[u8], step: usize, first: u32, out: &mut Vec) { + const AT_A_TIME: usize = 16; + let block = AT_A_TIME * step; + for (b, (old, new)) in last.chunks_mut(block).zip(records.chunks(block)).enumerate() { + if old == new { + continue; + } + for (n, (old, new)) in old.chunks_exact_mut(step).zip(new.chunks_exact(step)).enumerate() { + if old != new { + old.copy_from_slice(new); + out.push(first + (b * AT_A_TIME + n) as u32); + } + } + } +} + +#[cfg(test)] +mod changed_records_tests { + use super::changed_records; + + #[test] + fn changed_records_are_those_that_differ_one_by_one() { + for (step, count) in [(32usize, 128usize), (32, 2048), (16, 77), (32, 5), (32, 17)] { + let mut seed = 7u64; + let mut random = move || { + seed = seed.wrapping_mul(0x5851_F42D_4C95_7F2D).wrapping_add(0x1405_7B7E_F767_814F); + (seed >> 33) as usize + }; + let mut last: Vec = (0..step * count).map(|_| random() as u8).collect(); + let mut now = last.clone(); + let mut differ = Vec::new(); + for slot in 0..count { + if random() % 9 == 0 { + now[slot * step + random() % step] ^= 1 + (random() % 255) as u8; + differ.push(1000 + slot as u32); + } + } + let mut out = Vec::new(); + changed_records(&mut last, &now, step, 1000, &mut out); + assert_eq!(out, differ); + assert_eq!(last, now); + out.clear(); + changed_records(&mut last, &now, step, 1000, &mut out); + assert!(out.is_empty()); + } + } +} + /// Whether both are shader views of one texture the title placed in /// memory: the same address and the same resource description, whatever /// part of it each shows. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2373a17..4dbda49 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4852,7 +4852,7 @@ impl Host { } // Descriptors the title copied into placed heaps directly, before // command lists that index those slots are submitted. - crate::descriptor::sync_heaps(); + let heaps_synced = crate::descriptor::begin_sync_heaps(); // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; let runs = match &own { @@ -4885,9 +4885,6 @@ impl Host { SWEPT.store(now_ms(), Ordering::Relaxed); } let behind = late && flying(); - // The slots that waited for a texture's host copy, before the - // lists that may read them run. - crate::descriptor::make_waiting(); let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; // The ranges shaders write are counted for it (with the relay). crate::shadow::preparing(this_submission); @@ -5019,6 +5016,12 @@ impl Host { split.part(5); let back = crate::picked::with(declared_writes(runs), &picked.written); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); + drop(heaps_synced); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + #[cfg(feature = "diagnostics")] + split.part(15); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); submitting(0, 0); #[cfg(feature = "diagnostics")] From 92feb49bf18d2e01c9bb3d0ccceb3876073b2727 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:04 -0600 Subject: [PATCH 05/13] A thread asks the write watch ahead of the submissions (VICTORY_ASK_EARLY); the time ahead of the preparing is split VICTORY_ASK_EARLY=0: no such thread. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 29 ++++++++- crates/victory-gpu/src/watch.rs | 112 ++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4dbda49..7283546 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4835,11 +4835,17 @@ impl Host { // what they write. // Or the reads are done on the card, behind the flights. let own = if late { self.card_steps(runs) } else { None }; + #[cfg(feature = "diagnostics")] + let ahead = Split::begin(); + #[cfg(feature = "diagnostics")] + SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() && let Some(why) = late_blocked(runs) { + #[cfg(feature = "diagnostics")] + ahead.part(12); if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. @@ -4855,6 +4861,8 @@ impl Host { let heaps_synced = crate::descriptor::begin_sync_heaps(); // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; + #[cfg(feature = "diagnostics")] + ahead.part(13); let runs = match &own { Some(own) => { with = std::iter::once(own.list()).chain(runs.iter().copied()).collect(); @@ -4895,6 +4903,8 @@ impl Host { crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. + ahead.part(14); + #[cfg(feature = "diagnostics")] let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); #[cfg(feature = "diagnostics")] @@ -6489,9 +6499,12 @@ impl std::hash::Hasher for AddressHash { /// of the steps: the refreshes, and the copies and fills (those with the /// refreshes a copy of title memory flushes). Of the asking, which ranges it /// is of. Of the refreshes, those before ranges are given to shaders, one -/// copy at a time: nanoseconds, and how many. +/// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for +/// the submission lock, the steps done on the card planned ([`card_steps`]), +/// the flights waited for, the heaps' records and what is swept; and, at the +/// end, the wait for the heaps' records. #[cfg(feature = "diagnostics")] -static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; +static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; /// Since the last frame-rate line: flushes of refreshes, their refreshes, /// those known to copy nothing, and those done on several threads. @@ -6532,7 +6545,9 @@ fn split_line(frames: f64) { "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ - card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})", + card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \ + planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \ + for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)", ms[0], ms[8], ms[1], @@ -6563,6 +6578,7 @@ fn split_line(frames: f64) { a[10], a[9], a[2], + let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); a[3], a[4], a[5], @@ -6587,6 +6603,13 @@ fn split_line(frames: f64) { /// /// A submission brings some sixty copies up to date, one after the other /// on the submitting thread: for each, the pages the title wrote are asked + ms[11], + ms[12], + ms[13], + ms[14], + ms[15], + e[0], + e[1] / 1e3, /// for and read through the kernel into the copy. That is the frame line's /// "copies", 45-50 ms a frame, and the copies have nothing to do with one /// another: each refresh writes its own copy and its own notes, and reads diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 9afcd11..38cfe92 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -239,6 +239,7 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { ask_run(&pieces[i..k], &mut asked, &mut written); i = k; } + note_hot(&written); let mut j = journal_mut(); j.ahead_asked = next_asking(); j.ahead = asked; @@ -271,6 +272,116 @@ pub(crate) fn slow_asks() -> [u64; 3] { [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } +/// Whether a thread asks, between a submission's askings, about the memory +/// they found written (`VICTORY_ASK_EARLY=` between its rounds, 2 if not +/// given; `0`: no such thread). +/// +/// An asking's cost is the pages it finds written and resets, some 1.4 +/// microseconds each, and the title writes 7,000 a frame: the first +/// submission that refreshes its 174 MB heap stood 8 to 10 ms in one call +/// (session play-1125-0203). Asked a little at a time while the title +/// records, the same pages are in the journal when the submission comes, and +/// its own asking finds those written since. +/// +/// Nothing is seen later than before: a page goes into the journal as found +/// written by an asking of its own number, as from any thread that asks, and +/// the submission still asks for itself. A page the title writes again after +/// such a round faults once more. +fn early() -> Option { + static EVERY: std::sync::OnceLock> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + let ms = match std::env::var("VICTORY_ASK_EARLY") { + Ok(v) => v.trim().parse::().unwrap_or(2.0), + Err(_) => 2.0, + }; + std::time::Duration::try_from_secs_f64(ms / 1000.0).ok().filter(|d| !d.is_zero()) + }) +} + +/// The pieces of memory (by [`EARLY_PIECE`] pages) that submissions' askings +/// found written lately: how many pages each, halved every round of 64. +static HOT: Mutex> = Mutex::new(BTreeMap::new()); +/// The pieces asked in a round, at most. +const EARLY_MOST: usize = 24; +/// The pages of a piece: 2 MiB. +const EARLY_PIECE: usize = (2 << 20) / PAGE; +/// Told when a submission asked. +static HOT_MOVED: Condvar = Condvar::new(); + +/// Since the last frame line: pieces asked early, the microseconds of it. +static EARLY: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`EARLY`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn early_asks() -> [u64; 2] { + [0, 1].map(|i| EARLY[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// A submission's asking found `written` (pages). +fn note_hot(written: &[usize]) { + let Some(every) = early() else { + return; + }; + let mut hot = HOT.lock().unwrap_or_else(|e| e.into_inner()); + for page in written { + let n = hot.entry(page / EARLY_PIECE).or_default(); + *n = (*n + 1).min(1 << 10); + } + HOT_MOVED.notify_one(); + drop(hot); + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("victory-ask-early".into()).spawn(move || ask_early(every)); + }); +} + +fn ask_early(every: std::time::Duration) { + use std::sync::atomic::Ordering::Relaxed; + // So many rounds without a submission's asking: wait for one. + const IDLE: u32 = 100; + let mut round = 0u32; + let mut idle = 0; + let mut last = 0u64; + loop { + std::thread::sleep(every); + let pieces: Vec = { + let mut hot = HOT.lock().unwrap_or_else(|e| e.into_inner()); + let now = ASKED.load(Relaxed); + idle = if now == last { idle + 1 } else { 0 }; + while idle > IDLE { + hot = HOT_MOVED.wait(hot).unwrap_or_else(|e| e.into_inner()); + idle = 0; + } + round += 1; + if round % 64 == 0 { + hot.retain(|_, n| { + *n /= 2; + *n > 0 + }); + } + // The most written: a piece with a few pages is as dear to ask as + // one with many. + let mut most: Vec<(u32, usize)> = hot.iter().filter(|h| *h.1 >= 16).map(|(&p, &n)| (n, p)).collect(); + most.sort_unstable_by(|a, b| b.cmp(a)); + most.into_iter().take(EARLY_MOST).map(|(_, p)| p).collect() + }; + let began = std::time::Instant::now(); + let mut asked = 0; + for piece in pieces { + // (A submission's asking stands: what it holds is answered from + // the journal, and costs nothing here.) + if published(piece * EARLY_PIECE * PAGE, (piece + 1) * EARLY_PIECE * PAGE) { + continue; + } + asked += 1; + let _ = writes(piece * EARLY_PIECE * PAGE, (piece + 1) * EARLY_PIECE * PAGE, false); + } + EARLY[0].fetch_add(asked, Relaxed); + EARLY[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + last = ASKED.load(Relaxed); + } +} + /// The submission's refreshes are done: `writes` asks the kernel again. pub(crate) fn ask_ahead_done() { let mut j = journal_mut(); @@ -341,6 +452,7 @@ fn ask_rest(ranges: &[(usize, usize)]) { ahead.push((first, last)); } } + note_hot(&written); let mut j = journal_mut(); // A number of its own, and the one this asking stands under: between // the two parts another thread may have asked about a range of the From c2734ec5cde970f1297045db0ac3b958e12fa06b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:05 -0600 Subject: [PATCH 06/13] A submission's fills of upload memory are done together on several threads (VICTORY_WIDE_FILLS=0: one by one) 5 ms of the submitting thread. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7283546..cc96adf 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4973,6 +4973,7 @@ impl Host { #[cfg(feature = "diagnostics")] split.part(2); // The snapshots of the ranges shaders may write, if they were left + batch.fill(); // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. { @@ -6395,6 +6396,7 @@ impl HostList { if let Some(bytes) = p.prepare(free) { batch.placed.push((p.shadow.clone(), p.dst, bytes)); } + batch.fill(); (started, p.len) } Step::Refresh(shadow, address, len) => { @@ -6411,12 +6413,19 @@ impl HostList { let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); + if wide_fills() { + batch.fills.push((dst, src, len)); + bytes += len as u64; + continue; + } + let started = std::time::Instant::now(); } work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. if matches!(step, Step::Run(_)) { crate::watch::ask_once_end(); + batch.fill(); } #[cfg(feature = "diagnostics")] { @@ -6435,6 +6444,7 @@ impl HostList { #[cfg(feature = "diagnostics")] let snapshot = std::time::Instant::now(); shadow.writing(*address, *len); + batch.fill(); #[cfg(feature = "diagnostics")] { add(C::GpuWrites, 1); @@ -6705,6 +6715,22 @@ impl Batch { (r.1, r.2) = (r.1.min(address), r.2.max(end)); } None => { + /// Fills not done yet (destination, source, bytes): [`wide_fills`]. + fills: Vec<(usize, usize, usize)>, +} + +/// Whether the fills of a submission's upload memory are done together on +/// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the +/// lists name them). +/// +/// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the +/// submitting thread. Each reads title memory and writes memory of its own +/// that the card alone reads, when the lists run; they are done before the +/// next step that writes title memory or runs code of ours, and before the +/// submission goes on from its steps. +fn wide_fills() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh()) self.index.insert(key, self.refreshes.len()); self.refreshes.push((shadow.clone(), address, end)); } @@ -6790,6 +6816,33 @@ impl Batch { FLUSHES[0].fetch_add(1, Ordering::Relaxed); FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } + /// The fills noted are done. + fn fill(&mut self) { + // Below this many the threads cost more than they save. + const FEW: usize = 96; + const PART: usize = 64; + if self.fills.is_empty() { + return; + } + let started = std::time::Instant::now(); + if self.fills.len() < FEW { + for (dst, src, len) in self.fills.drain(..) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + } else { + let fills = std::mem::take(&mut self.fills); + crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| { + for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + }); + } + let took = started.elapsed(); + PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); + } + } fn flush_all(&mut self) { From 630aef45a4b20d26b7d07830695fb6ec43377eef Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:50:05 -0600 Subject: [PATCH 07/13] The pass over the heap's buffer views is made beside the recording (VICTORY_HEAP_PASS_ASIDE=0: in it) 12 to 17 ms of one recording thread at the frame's first list that needs it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 305 +++++++++++++++------------ crates/victory-gpu/src/host.rs | 188 ++++++++++------- crates/victory-gpu/src/host/aside.rs | 98 +++++++++ 3 files changed, 372 insertions(+), 219 deletions(-) create mode 100644 crates/victory-gpu/src/host/aside.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..a15156c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -678,6 +678,161 @@ fn set(roots: &mut Vec, slot: u32, root: Root) { roots[slot] = root; } +/// The pass over the buffer views of `heap` that shaders pick by index +/// ([`State::heap_buffers`]): their host slots are made, and the host copies +/// they show are to be refreshed. +fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64) -> Vec { + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + type Ranges = HeapRanges>; + static RANGES: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let (passes, ranges) = kept + .get_or_insert_with(Default::default) + .entry(std::ptr::from_ref(host) as usize) + .or_insert_with(|| (0, HeapRanges(Vec::new()))); + let changed = host.buffer_changes(); + let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); + let slots = if all { + ranges.0.clear(); + host.buffer_slots() + } else if heap_spread() { + // The written ones, and this pass's part of the others. + let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); + ranges.forget_part(part, parts); + let mut slots = host.buffer_slots_of(part, parts); + slots.extend(changed); + slots + } else { + changed + }; + *passes += 1; + // Whether the device was there before the pass: a view that removes + // it is named below. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + let mut unordered = Vec::new(); + for (n, &index) in slots.iter().enumerate() { + ranges.set(index, None); + // A draw's table's: the draw brings what it reads up to date. + if host.copied_tabled(index, frame) { + continue; + } + let Some(handle) = heap.handle(index) else { + continue; + }; + let Some(view) = host.mirror(index, handle, true) else { + continue; + }; + // Every 64 views while the device lives (a cheap query). + if alive + && n % 64 == 63 + && let Some(why) = crate::descriptor::host::device_removed() + { + alive = false; + GONE.store(true, Ordering::Relaxed); + let last: Vec = slots[n - 63..=n] + .iter() + .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) + .map(|s| s.chars().take(200).collect()) + .collect(); + tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); + crate::host::log_removal_context(); + } + // The copy the slot shows (`buffer_copy`), not the one the + // view's range alone would find. + let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { + continue; + }; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } + if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) { + unordered.push((shadow.clone(), address, address + len)); + } + ranges.set(index, Some((shadow, address, address + len))); + } + if crate::picked::on() { + crate::picked::shown(unordered, all); + } + #[cfg(feature = "diagnostics")] + let looked = std::time::Instant::now(); + // Per host copy, the span its picked views cover. + let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); + let mut views = 0u32; + for (shadow, from, to) in ranges.ranges() { + views += 1; + let key = std::sync::Arc::as_ptr(shadow) as usize; + let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + drop(kept); + let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh. + // It was once refreshed only every 120 frames (unmapped pages read + // one by one cost 14 GB a frame in run 11, before they were + // remembered): streamed geometry then drew from stale buffers, and + // the garbage ended runs (the card stopped answering 14-90 frames + // into the opening cutscene; with every frame it ran on). The pass + // costs some 30 ms a frame this way. + static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + let mut found = Vec::with_capacity(spans.len()); + for (shadow, from, to) in spans.values() { + if shadow.unwatched() { + // By the copy's number: a copy made where one let go was + // (`shadow::let_go_idle`) has never been refreshed. + let key = shadow.id() as usize; + // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from)))); + } + #[cfg(feature = "diagnostics")] + let refreshed = std::time::Instant::now(); + crate::watch::look_at_holes(); + #[cfg(feature = "diagnostics")] + for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked]) { + sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index" + ); + } + found +} + impl State { pub(crate) fn reset(&mut self, pipeline: This) { *self = State::default(); @@ -1609,155 +1764,25 @@ impl State { return Some(gpu); } let started = std::time::Instant::now(); - // Per host heap: the host copy and range each slot's buffer view - // reads, kept from pass to pass. Only the slots written since the - // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s - // at best); all of them every 16 passes, because a view of a - // released resource goes stale without a write, and a slot written - // before its memory had a host copy is only made then. - type Ranges = HeapRanges>; - static RANGES: std::sync::Mutex>> = - std::sync::Mutex::new(None); - let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let (passes, ranges) = kept - .get_or_insert_with(Default::default) - .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, HeapRanges(Vec::new()))); - let changed = host.buffer_changes(); - let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); - let slots = if all { - ranges.0.clear(); - host.buffer_slots() - } else if heap_spread() { - // The written ones, and this pass's part of the others. - let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); - ranges.forget_part(part, parts); - let mut slots = host.buffer_slots_of(part, parts); - slots.extend(changed); - slots + if crate::host::aside::on() { + let at = std::ptr::from_ref(heap) as usize; + list.refreshes_coming(move || { + crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame))) + .flatten() + .unwrap_or_default() + }); } else { - changed - }; - *passes += 1; - // Whether the device was there before the pass: a view that removes - // it is named below. - static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); - let mut unordered = Vec::new(); - for (n, &index) in slots.iter().enumerate() { - ranges.set(index, None); - // A draw's table's: the draw brings what it reads up to date. - if host.copied_tabled(index, frame) { - continue; + for (shadow, from, to) in heap_buffer_pass(heap, host, frame) { + shadow.refresh(list, from, to - from); } - let Some(handle) = heap.handle(index) else { - continue; - }; - let Some(view) = host.mirror(index, handle, true) else { - continue; - }; - // Every 64 views while the device lives (a cheap query). - if alive - && n % 64 == 63 - && let Some(why) = crate::descriptor::host::device_removed() - { - alive = false; - GONE.store(true, Ordering::Relaxed); - let last: Vec = slots[n - 63..=n] - .iter() - .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) - .map(|s| s.chars().take(200).collect()) - .collect(); - tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); - crate::host::log_removal_context(); - } - // The copy the slot shows (`buffer_copy`), not the one the - // view's range alone would find. - let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { - continue; - }; - #[cfg(feature = "diagnostics")] - if host.shows(index, &shadow.buffer) == Some(false) { - HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); - } - if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) { - unordered.push((shadow.clone(), address, address + len)); - } - ranges.set(index, Some((shadow, address, address + len))); - } - if crate::picked::on() { - crate::picked::shown(unordered, all); - } - #[cfg(feature = "diagnostics")] - let looked = std::time::Instant::now(); - // Per host copy, the span its picked views cover. - let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); - let mut views = 0u32; - for (shadow, from, to) in ranges.ranges() { - views += 1; - let key = std::sync::Arc::as_ptr(shadow) as usize; - let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); - span.1 = span.1.min(*from); - span.2 = span.2.max(*to); - } - drop(kept); - let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); - // Memory that is not write-watched is copied whole by every refresh. - // It was once refreshed only every 120 frames (unmapped pages read - // one by one cost 14 GB a frame in run 11, before they were - // remembered): streamed geometry then drew from stale buffers, and - // the garbage ended runs (the card stopped answering 14-90 frames - // into the opening cutscene; with every frame it ran on). The pass - // costs some 30 ms a frame this way. - static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); - let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); - let whole = whole.get_or_insert_with(Default::default); - for (shadow, from, to) in spans.values() { - if shadow.unwatched() { - // By the copy's number: a copy made where one let go was - // (`shadow::let_go_idle`) has never been refreshed. - let key = shadow.id() as usize; - // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). - static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); - let every = *EVERY.get_or_init(|| { - std::env::var("VICTORY_UNWATCHED_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(1) - }); - match whole.get(&key) { - Some(&last) if frame < last + every => continue, - _ => { - whole.insert(key, frame); - } - } - } - shadow.refresh(list, *from, to - from); } #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); - crate::watch::look_at_holes(); self.heap_textures(list, heap, host); #[cfg(feature = "diagnostics")] - for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { - sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); - } + HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - static LOGGED: AtomicU64 = AtomicU64::new(0); - // The first pass and every growth of the set by half. - let seen = LOGGED.load(Ordering::Relaxed); - if u64::from(views) > seen + seen / 2 { - LOGGED.store(u64::from(views), Ordering::Relaxed); - tracing::info!( - slots = slots.len(), - views, - copies = spans.len(), - mb = bytes >> 20, - ms = started.elapsed().as_millis(), - "buffer views of the heap made ready for shaders that pick them by index" - ); - } Some(gpu) } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cc96adf..b671536 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -903,6 +903,9 @@ pub(crate) struct HostList { /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and /// how many batches of this recording have a place in them. batch_args: Mutex<(Vec, u32)>, + /// Refreshes of host copies that a thread of ours is still finding, and + /// where among the list's steps they belong ([`aside`]). + coming: Mutex)>>, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -3154,14 +3157,15 @@ fn late_line(frames: f64) { } } +pub(crate) mod aside; mod card_steps; mod place; mod send; +pub(crate) use send::{goes_as_words, words_under}; mod torn; pub(crate) mod upcheck; #[cfg(test)] -pub(crate) use send::{goes_as_words, words_under}; mod late_tests { use super::{continues, join_ranges, touches}; @@ -3546,6 +3550,7 @@ impl Host { card_budget: OnceLock::new(), indirect_args: Mutex::default(), batch_args: Mutex::default(), + coming: Mutex::default(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -4830,22 +4835,22 @@ impl Host { let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let was_working = working(true); submitting(1, runs.len()); + #[cfg(feature = "diagnostics")] + let ahead = Split::begin(); + #[cfg(feature = "diagnostics")] + SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); // Flights in the air ([`late`]): a submission that is waited for // settles them first, one sent ahead only if preparing it reads // what they write. // Or the reads are done on the card, behind the flights. let own = if late { self.card_steps(runs) } else { None }; #[cfg(feature = "diagnostics")] - let ahead = Split::begin(); - #[cfg(feature = "diagnostics")] - SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); + ahead.part(12); if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() && let Some(why) = late_blocked(runs) { - #[cfg(feature = "diagnostics")] - ahead.part(12); if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. @@ -4856,13 +4861,13 @@ impl Host { self.settle(&mut submitted, why); } } + #[cfg(feature = "diagnostics")] + ahead.part(13); // Descriptors the title copied into placed heaps directly, before // command lists that index those slots are submitted. let heaps_synced = crate::descriptor::begin_sync_heaps(); // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; - #[cfg(feature = "diagnostics")] - ahead.part(13); let runs = match &own { Some(own) => { with = std::iter::once(own.list()).chain(runs.iter().copied()).collect(); @@ -4898,13 +4903,13 @@ impl Host { crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] + ahead.part(14); + #[cfg(feature = "diagnostics")] let lock = (started - called).as_micros() as u64; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. - ahead.part(14); - #[cfg(feature = "diagnostics")] let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); #[cfg(feature = "diagnostics")] @@ -4968,12 +4973,12 @@ impl Host { } lists.push(list.list.cast().ok()); } + batch.fill(); batch.flush(); crate::watch::ask_once_end(); #[cfg(feature = "diagnostics")] split.part(2); // The snapshots of the ranges shaders may write, if they were left - batch.fill(); // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. { @@ -5011,6 +5016,12 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(4); + drop(heaps_synced); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + #[cfg(feature = "diagnostics")] + split.part(15); let prepared = std::time::Instant::now(); if late { *submitted += 1; @@ -5027,12 +5038,6 @@ impl Host { split.part(5); let back = crate::picked::with(declared_writes(runs), &picked.written); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); - drop(heaps_synced); - // The slots that waited for a texture's host copy, before the - // lists that may read them run. - crate::descriptor::make_waiting(); - #[cfg(feature = "diagnostics")] - split.part(15); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); submitting(0, 0); #[cfg(feature = "diagnostics")] @@ -5485,6 +5490,7 @@ impl HostList { } self.batches_common(); self.card_budget_out(); + self.take_coming(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -5502,12 +5508,35 @@ impl HostList { } } + /// `work` finds, on a thread of ours, refreshes that belong at this + /// place among the list's steps; they are there when the list is closed. + pub(crate) fn refreshes_coming(&self, work: impl FnOnce() -> Vec + Send + 'static) { + self.take_coming(); + let at = self.deferred().copies.len(); + let coming = aside::begin(work); + *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = Some((at, coming)); + } + + /// The refreshes that were still to come are put among the steps. + fn take_coming(&self) { + let Some((at, coming)) = self.coming.lock().unwrap_or_else(|e| e.into_inner()).take() else { + return; + }; + let found = coming.wait(); + let mut deferred = self.deferred(); + let at = at.min(deferred.copies.len()); + deferred + .copies + .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); + } + /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); self._alive.used(); + *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None; *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -6367,6 +6396,7 @@ impl HostList { { copies += 1; } + batch.fill(); batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. @@ -6379,24 +6409,29 @@ impl HostList { (started, len) } &Step::Fill(dst, src, len, _) => { - let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { copies += 1; } + if wide_fills() { + batch.fills.push((dst, src, len)); + bytes += len as u64; + continue; + } + let started = std::time::Instant::now(); copy_mapped(dst as *mut u8, src as *const u8, len, false); (started, len) } Step::Placed(p) => { let started = std::time::Instant::now(); let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len); + batch.fill(); if free { batch.title_written(); } if let Some(bytes) = p.prepare(free) { batch.placed.push((p.shadow.clone(), p.dst, bytes)); } - batch.fill(); (started, p.len) } Step::Refresh(shadow, address, len) => { @@ -6409,23 +6444,17 @@ impl HostList { continue; } Step::Run(work) | Step::Host(work, _) => { + batch.fill(); #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); - if wide_fills() { - batch.fills.push((dst, src, len)); - bytes += len as u64; - continue; - } - let started = std::time::Instant::now(); } work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. if matches!(step, Step::Run(_)) { crate::watch::ask_once_end(); - batch.fill(); } #[cfg(feature = "diagnostics")] { @@ -6444,7 +6473,6 @@ impl HostList { #[cfg(feature = "diagnostics")] let snapshot = std::time::Instant::now(); shadow.writing(*address, *len); - batch.fill(); #[cfg(feature = "diagnostics")] { add(C::GpuWrites, 1); @@ -6548,6 +6576,7 @@ impl Split { fn split_line(frames: f64) { let ms: Vec = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); @@ -6574,6 +6603,13 @@ fn split_line(frames: f64) { ms[4], ms[5], if crate::watch::light() { "on" } else { "off" }, + ms[11], + ms[12], + ms[13], + ms[14], + ms[15], + e[0], + e[1] / 1e3, ); tracing::info!( "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ @@ -6588,7 +6624,6 @@ fn split_line(frames: f64) { a[10], a[9], a[2], - let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); a[3], a[4], a[5], @@ -6601,10 +6636,12 @@ fn split_line(frames: f64) { s[3], ); tracing::info!( - "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", + "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \ + first two beside the recording (VICTORY_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close", h[0], h[1], h[2], + aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames, ); } @@ -6613,13 +6650,6 @@ fn split_line(frames: f64) { /// /// A submission brings some sixty copies up to date, one after the other /// on the submitting thread: for each, the pages the title wrote are asked - ms[11], - ms[12], - ms[13], - ms[14], - ms[15], - e[0], - e[1] / 1e3, /// for and read through the kernel into the copy. That is the frame line's /// "copies", 45-50 ms a frame, and the copies have nothing to do with one /// another: each refresh writes its own copy and its own notes, and reads @@ -6685,6 +6715,22 @@ struct Batch { /// What copies at their place in the submission's lists put into title /// memory ([`place`]): the host copy, the title address, the bytes. placed: Vec<(std::sync::Arc, usize, Vec)>, + /// Fills not done yet (destination, source, bytes): [`wide_fills`]. + fills: Vec<(usize, usize, usize)>, +} + +/// Whether the fills of a submission's upload memory are done together on +/// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the +/// lists name them). +/// +/// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the +/// submitting thread. Each reads title memory and writes memory of its own +/// that the card alone reads, when the lists run; they are done before the +/// next step that writes title memory or runs code of ours, and before the +/// submission goes on from its steps. +fn wide_fills() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh()) } /// Whether a submission's textures are brought up to date on several @@ -6715,22 +6761,6 @@ impl Batch { (r.1, r.2) = (r.1.min(address), r.2.max(end)); } None => { - /// Fills not done yet (destination, source, bytes): [`wide_fills`]. - fills: Vec<(usize, usize, usize)>, -} - -/// Whether the fills of a submission's upload memory are done together on -/// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the -/// lists name them). -/// -/// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the -/// submitting thread. Each reads title memory and writes memory of its own -/// that the card alone reads, when the lists run; they are done before the -/// next step that writes title memory or runs code of ours, and before the -/// submission goes on from its steps. -fn wide_fills() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh()) self.index.insert(key, self.refreshes.len()); self.refreshes.push((shadow.clone(), address, end)); } @@ -6786,6 +6816,33 @@ fn wide_fills() -> bool { self.textures.clear(); } + /// The fills noted are done. + fn fill(&mut self) { + // Below this many the threads cost more than they save. + const FEW: usize = 96; + const PART: usize = 64; + if self.fills.is_empty() { + return; + } + let started = std::time::Instant::now(); + if self.fills.len() < FEW { + for (dst, src, len) in self.fills.drain(..) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + } else { + let fills = std::mem::take(&mut self.fills); + crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| { + for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) { + copy_mapped(dst as *mut u8, src as *const u8, len, false); + } + }); + } + let took = started.elapsed(); + PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); + } + /// The textures due are brought up to date. fn refresh_textures(&mut self) { if self.due.len() < 2 || !wide_textures() { @@ -6816,33 +6873,6 @@ fn wide_fills() -> bool { FLUSHES[0].fetch_add(1, Ordering::Relaxed); FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } - /// The fills noted are done. - fn fill(&mut self) { - // Below this many the threads cost more than they save. - const FEW: usize = 96; - const PART: usize = 64; - if self.fills.is_empty() { - return; - } - let started = std::time::Instant::now(); - if self.fills.len() < FEW { - for (dst, src, len) in self.fills.drain(..) { - copy_mapped(dst as *mut u8, src as *const u8, len, false); - } - } else { - let fills = std::mem::take(&mut self.fills); - crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| { - for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) { - copy_mapped(dst as *mut u8, src as *const u8, len, false); - } - }); - } - let took = started.elapsed(); - PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed); - } - } fn flush_all(&mut self) { diff --git a/crates/victory-gpu/src/host/aside.rs b/crates/victory-gpu/src/host/aside.rs new file mode 100644 index 0000000..051debc --- /dev/null +++ b/crates/victory-gpu/src/host/aside.rs @@ -0,0 +1,98 @@ +//! Work for a list that a thread of ours does while the title records on: +//! the pass over the heap's buffer views (`crate::draw`), which took 12 to 17 +//! ms of one recording thread at the frame's first list that needs it, with +//! the submission of that list, and of those behind it, waiting. +//! `VICTORY_HEAP_PASS_ASIDE=0`: done where it is needed, as before. +//! +//! What it finds are refreshes of host copies, which are steps of the list +//! for its submission, and what it makes are descriptors, which the card +//! reads when the list runs: both are there when the list is closed +//! (`HostList::close` waits), and the refreshes stand at the place in the +//! list's steps where the pass was begun. + +use super::*; + +/// A host copy, and the title memory of it (from, to). +pub(crate) type Refresh = (std::sync::Arc, u64, u64); + +/// What is being found, until it is. +pub(crate) struct Coming(Mutex>>, std::sync::Condvar); + +/// Since the last frame line: microseconds lists waited at their close. +pub(crate) static WAITED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +impl Coming { + /// What was found. + pub(crate) fn wait(&self) -> Vec { + let began = std::time::Instant::now(); + let mut found = self.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(found) = found.take() { + WAITED.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + return found; + } + found = self.1.wait(found).unwrap_or_else(|e| e.into_inner()); + } + } + + fn found(&self, what: Vec) { + *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(what); + self.1.notify_all(); + } +} + +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_PASS_ASIDE").is_none_or(|v| v != "0")) +} + +type Job = Box; + +/// `work` begins on the thread for it, one after another; here and now if +/// there is no such thread. +pub(crate) fn begin(work: impl FnOnce() -> Vec + Send + 'static) -> std::sync::Arc { + static THREAD: OnceLock>>> = OnceLock::new(); + let coming = std::sync::Arc::new(Coming(Mutex::new(None), std::sync::Condvar::new())); + let told = coming.clone(); + let job: Job = Box::new(move || { + // (However it ends, the list that waits goes on.) + let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)).unwrap_or_default(); + told.found(found); + }); + let thread = THREAD.get_or_init(|| { + let (send, jobs) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("victory-aside".into()) + .spawn(move || jobs.into_iter().for_each(|job| job())) + .ok() + .map(|_| Mutex::new(send)) + }); + match thread { + Some(send) => { + if let Err(job) = send.lock().unwrap_or_else(|e| e.into_inner()).send(job) { + (job.0)(); + } + } + None => job(), + } + coming +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_is_found_is_waited_for_and_a_panic_lets_the_list_go_on() { + let (go, wait) = std::sync::mpsc::channel::<()>(); + let coming = begin(move || { + let _ = wait.recv(); + Vec::new() + }); + assert!(coming.0.lock().unwrap().is_none()); + go.send(()).unwrap(); + assert!(coming.wait().is_empty()); + assert!(begin(|| panic!("a panic of the work")).wait().is_empty()); + assert!(begin(Vec::new).wait().is_empty()); + } +} From 6bc69a0e7bb1c54502df00ca0ee9a19a4c6ec8df Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:37 -0600 Subject: [PATCH 08/13] Refreshes copy and send the 4 KiB parts of a page that were written (VICTORY_PAGE_PARTS=0: the 64 KiB page); the early asking is off Where the kernel or a landing names them; what is checked stays a page. VICTORY_ASK_EARLY= turns the early asking on. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 3 +- crates/victory-gpu/src/shadow.rs | 66 +++++++++++++ crates/victory-gpu/src/watch.rs | 155 ++++++++++++++++++++++++++----- 3 files changed, 200 insertions(+), 24 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b671536..b3457e9 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8756,7 +8756,8 @@ mod refresh_tests { assert_eq!(look(true, "taken"), 0); // SAFETY: the test's own memory. unsafe { ((region + 600) as *mut u8).write_volatile(1) }; - assert_eq!(look(false, "written at its end"), PAGE - 500); + // (The kernel names the 4 KiB, the guards only the block.) + assert_eq!(look(false, "written at its end"), if view { PAGE } else { 4096 } - 500); assert_eq!(look(true, "taken again"), 0); // Outside the range, on its last page. // SAFETY: as above. diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index b140a27..b1e8388 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2388,6 +2388,66 @@ fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(u .collect() } +/// `runs` (from, to, whether the copy held it before), cut in those of pages +/// held before (`pages`: page number and asking, in order) to the parts of +/// each page that were written since (`parts`: a bit for each 4 KiB). +fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u16]) -> Vec<(usize, usize, bool)> { + const PART: usize = PAGE / 16; + if parts.iter().all(|&p| p == u16::MAX) { + return runs; + } + let mut out: Vec<(usize, usize, bool)> = Vec::with_capacity(runs.len() + pages.len()); + let mut pages = pages.iter().zip(parts).peekable(); + for (from, to, known) in runs { + if !known { + out.push((from, to, known)); + continue; + } + while let Some((&(page, _), &parts)) = pages.next_if(|((page, _), _)| page * PAGE < to) { + for k in (0..16).filter(|k| parts >> k & 1 != 0) { + let (a, b) = ((page * PAGE + k * PART).max(from), (page * PAGE + (k + 1) * PART).min(to)); + if a >= b { + continue; + } + match out.last_mut() { + Some((_, end, true)) if *end == a => *end = b, + _ => out.push((a, b, true)), + } + } + } + } + out +} + +#[cfg(test)] +mod parts_tests { + use super::{PAGE, by_parts}; + + #[test] + fn runs_are_cut_to_the_parts_written() { + const P: usize = PAGE / 16; + let at = |page: usize, part: usize| page * PAGE + part * P; + // Pages 10 and 11 again (from the middle of 10's part 1 on), 12 + // never taken, 14 again. + let runs = vec![ + (at(10, 1) + 100, at(12, 0), true), + (at(12, 0), at(13, 0), false), + (at(14, 0), at(14, 9) + 7, true), + ]; + let pages = [(10, 5), (11, 5), (14, 6)]; + assert_eq!(by_parts(runs.clone(), &pages, &[u16::MAX; 3]), runs); + assert_eq!( + by_parts(runs, &pages, &[0b1000_0000_0000_0011, 0b11, 0b10_0000_0000]), + [ + (at(10, 1) + 100, at(10, 2), true), + (at(10, 15), at(11, 2), true), + (at(12, 0), at(13, 0), false), + (at(14, 9), at(14, 9) + 7, true), + ] + ); + } +} + #[cfg(test)] mod stale_tests { use super::*; @@ -3451,6 +3511,8 @@ impl Shadow { // since, is as it was. let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 }; let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>); + // Pages taken before and written since: in the order of their runs. + let mut again_at: Vec<(usize, u64)> = Vec::new(); let last = (to - 1) / PAGE; for page in from / PAGE..=last { let write = match writes.peek() { @@ -3471,6 +3533,9 @@ impl Shadow { } // Cut where pages taken before meet pages never taken. let again = taken != 0; + if again { + again_at.push((page, taken)); + } if let Some((first, known)) = run && known != again { @@ -3486,6 +3551,7 @@ impl Shadow { if let Some((first, known)) = run { runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known)); } + let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at)); let bytes = self.take_all(runs); if crate::watch::light() { // All of the range is in the copy as of this asking. diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 38cfe92..94684f5 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -36,6 +36,58 @@ pub(crate) const PAGE: usize = 64 << 10; /// The kernel's page, the unit of its answers. const KERNEL_PAGE: usize = 4096; +/// The parts of a page. +const PARTS: usize = PAGE / KERNEL_PAGE; +/// All of them. +const WHOLE: u16 = u16::MAX; + +/// Whether the parts of a page that the kernel names are kept, and a refresh +/// copies those (`VICTORY_PAGE_PARTS=0`: the 64 KiB page, as before). +/// +/// The kernel says which 4 KiB pages were written, and a copy took the 64 KiB +/// around each: 29 MB a frame written so were most of 114 MB copied, and as +/// much sent up and hashed again on the card (session play-1125-0203, run +/// cpu-2). What is checked is as before, a page. +fn parts_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PAGE_PARTS").is_none_or(|v| v != "0")) +} + +impl Journal { + /// Page `page` was found written by asking `now`: the parts in `parts` + /// (a bit each). The asking that found it written before (0: none). + fn note(&mut self, page: usize, parts: u16, now: u64) -> u64 { + let before = self.written.insert(page, now).unwrap_or(0); + if parts == WHOLE || !parts_on() { + self.parts.remove(&page); + return before; + } + let all = self.parts.entry(page).or_insert([before; PARTS]); + for (k, at) in all.iter_mut().enumerate() { + if parts >> k & 1 != 0 { + *at = now; + } + } + before + } + + /// The parts of `page` written by an asking after `taken`. + fn parts_since(&self, page: usize, taken: u64) -> u16 { + match self.parts.get(&page) { + Some(all) => all.iter().enumerate().filter(|(_, at)| **at > taken).fold(0, |m, (k, _)| m | 1 << k), + None => WHOLE, + } + } +} + +/// Of the pages of a copy that were written after it took them (page number, +/// the asking it took the page at): the parts to take again, a bit for each +/// 4 KiB, in the same order. +pub(crate) fn parts_written(pages: &[(usize, u64)]) -> Vec { + let j = journal(); + pages.iter().map(|&(page, taken)| j.parts_since(page, taken)).collect() +} + /// Numbers the askings; 0 is "never". Counted up with the journal held /// (shared will do: what notes an answer holds it alone). static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -68,6 +120,10 @@ pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { struct Journal { /// Page number → the asking that last found it written. written: BTreeMap, + /// The same for each of a page's sixteen parts ([`KERNEL_PAGE`]), where + /// the parts are known ([`parts_on`]); a page that is not here was + /// written whole, as far as anyone knows. + parts: std::collections::HashMap>, /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) /// and the asking that did: `writes` answers for a range inside one /// from the journal, without another kernel call. @@ -87,6 +143,7 @@ struct Journal { /// it, found it waiting for that lock (run pooloff1). static JOURNAL: RwLock = RwLock::new(Journal { written: BTreeMap::new(), + parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), ahead: Vec::new(), ahead_asked: 0, kept: false, @@ -142,9 +199,9 @@ thread_local! { } /// The pages of `[first, last)` the kernel says were written since it was -/// last asked, in order, each once; `None` if the range is not write-watched +/// last asked, in order, each once, with their written parts; `None` if the range is not write-watched /// memory of one reservation. The caller holds the range ([`Asking`]). -fn kernel_written(first: usize, last: usize) -> Option> { +fn kernel_written(first: usize, last: usize) -> Option> { use windows_sys::Win32::System::Memory::GetWriteWatch; const WRITE_WATCH_FLAG_RESET: u32 = 1; FOUND.with(|found| { @@ -185,8 +242,14 @@ fn kernel_written(first: usize, last: usize) -> Option> { tally(0, 1); tally(1, ((last - first) * (PAGE >> 10)) as u64); } - let mut pages: Vec = found[..count].iter().map(|&at| at / PAGE).collect(); - pages.dedup(); + let mut pages: Vec<(usize, u16)> = Vec::new(); + for &at in &found[..count] { + let (page, part) = (at / PAGE, 1u16 << (at % PAGE / KERNEL_PAGE)); + match pages.last_mut() { + Some((last, parts)) if *last == page => *parts |= part, + _ => pages.push((page, part)), + } + } Some(pages) }) } @@ -244,7 +307,9 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { j.ahead_asked = next_asking(); j.ahead = asked; let now = j.ahead_asked; - j.written.extend(written.into_iter().map(|page| (page, now))); + for (page, parts) in written { + j.note(page, parts, now); + } } /// Since the last frame line: the kernel askings that took a millisecond @@ -273,8 +338,9 @@ pub(crate) fn slow_asks() -> [u64; 3] { } /// Whether a thread asks, between a submission's askings, about the memory -/// they found written (`VICTORY_ASK_EARLY=` between its rounds, 2 if not -/// given; `0`: no such thread). +/// they found written (`VICTORY_ASK_EARLY=` between its rounds; off +/// unless given: in run cpu-2 the submissions' own askings were none the +/// cheaper for its 650 a frame, 12 to 18 ms where 9 were). /// /// An asking's cost is the pages it finds written and resets, some 1.4 /// microseconds each, and the title writes 7,000 a frame: the first @@ -292,7 +358,7 @@ fn early() -> Option { *EVERY.get_or_init(|| { let ms = match std::env::var("VICTORY_ASK_EARLY") { Ok(v) => v.trim().parse::().unwrap_or(2.0), - Err(_) => 2.0, + Err(_) => 0.0, }; std::time::Duration::try_from_secs_f64(ms / 1000.0).ok().filter(|d| !d.is_zero()) }) @@ -318,12 +384,12 @@ pub(crate) fn early_asks() -> [u64; 2] { } /// A submission's asking found `written` (pages). -fn note_hot(written: &[usize]) { +fn note_hot(written: &[(usize, u16)]) { let Some(every) = early() else { return; }; let mut hot = HOT.lock().unwrap_or_else(|e| e.into_inner()); - for page in written { + for (page, _) in written { let n = hot.entry(page / EARLY_PIECE).or_default(); *n = (*n + 1).min(1 << 10); } @@ -460,7 +526,9 @@ fn ask_rest(ranges: &[(usize, usize)]) { // part's number that write was older than the copy, and never copied. let now = next_asking(); j.ahead_asked = now; - j.written.extend(written.into_iter().map(|page| (page, now))); + for (page, parts) in written { + j.note(page, parts, now); + } j.kept = !ahead.is_empty(); j.ahead = ahead; } @@ -489,10 +557,12 @@ pub(crate) fn wrote(at: usize, len: usize) { // until the next asking copy the pages again. j.ahead_asked = now; for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { - j.written.insert(page, now); + j.note(page, WHOLE, now); } for (_, others) in elsewhere(at, len) { - j.written.extend(others.into_iter().map(|other| (other / PAGE, now))); + for other in others { + j.note(other / PAGE, WHOLE, now); + } } } @@ -509,7 +579,7 @@ fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec)> { /// fails, as a run across two reservations or into memory that is not /// write-watched does. A piece alone is left to [`writes`]. Adds what was /// asked to `asked` and the pages found written to `written`. -fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec) { +fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>) { if pieces.len() < 2 { return; } @@ -575,7 +645,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve } #[cfg(feature = "diagnostics")] let guarding = std::time::Instant::now(); - let written = guard(first * PAGE, last * PAGE); + let written = guard(first * PAGE, last * PAGE).map(|pages| pages.into_iter().map(|p| (p, WHOLE)).collect::>()); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -598,14 +668,16 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let answer = { let mut j = journal_mut(); let now = next_asking(); - j.written.extend(pages.iter().map(|&page| (page, now))); + for &(page, parts) in &pages { + j.note(page, parts, now); + } (now, of(&j)) }; // Noted: what the guards made clean of it is known by its bits from // now on. (The range is still held: no other asking of any of it came // between.) if guards_asked && light() { - publish(&pages); + publish(&pages.iter().map(|p| p.0).collect::>()); } Some(answer) } @@ -1098,16 +1170,21 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, let mut j = journal_mut(); let now = next_asking(); noted = now; - let mut last = usize::MAX; + let mut blocks: Vec<(usize, u16)> = Vec::with_capacity(spans.len()); for &page in pages { - let block = page * KERNEL_PAGE / PAGE; - if block != last { - before.push((block, j.written.insert(block, now).unwrap_or(0))); - last = block; + let (block, part) = (page / PARTS, 1u16 << (page % PARTS)); + match blocks.last_mut() { + Some((last, parts)) if *last == block => *parts |= part, + _ => blocks.push((block, part)), } } + for (block, parts) in blocks { + before.push((block, j.note(block, parts, now))); + } for (_, others) in &elsewhere { - j.written.extend(others.iter().map(|other| (other / PAGE, now))); + for other in others { + j.note(other / PAGE, WHOLE, now); + } } } for &(at, len) in spans { @@ -2114,6 +2191,38 @@ fn writable(at: usize) -> bool { n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE } +#[cfg(test)] +mod parts_tests { + use super::*; + + #[test] + fn the_parts_of_a_page_written_since_it_was_taken() { + let mut j = Journal { + written: BTreeMap::new(), + parts: std::collections::HashMap::with_hasher(std::hash::BuildHasherDefault::new()), + ahead: Vec::new(), + ahead_asked: 0, + kept: false, + }; + assert_eq!(j.parts_since(7, 0), WHOLE); + assert_eq!(j.note(7, WHOLE, 3), 0); + // Parts 0 and 5 at 4, part 5 again at 6: at 2 the whole page is due. + assert_eq!(j.note(7, 0b10_0001, 4), 3); + assert_eq!(j.note(7, 0b10_0000, 6), 4); + assert_eq!(j.parts_since(7, 2), WHOLE); + assert_eq!(j.parts_since(7, 3), 0b10_0001); + assert_eq!(j.parts_since(7, 4), 0b10_0000); + assert_eq!(j.parts_since(7, 5), 0b10_0000); + assert_eq!(j.parts_since(7, 6), 0); + // Written whole: all of it, whoever took it before. + assert_eq!(j.note(7, WHOLE, 8), 6); + assert_eq!(j.parts_since(7, 7), WHOLE); + // A page never written before: what was not named was never written. + assert_eq!(j.note(9, 0b100, 9), 0); + assert_eq!(j.parts_since(9, 5), 0b100); + } +} + #[cfg(test)] mod tests { use super::*; From 3ffc66634eee1d6762290609bf6694a7e1d5689c Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:38 -0600 Subject: [PATCH 09/13] Copies that shaders write are brought up to date together ahead of a submission's steps (VICTORY_REFRESH_AHEAD=0: one by one) 580 a frame, 3.4 to 6.5 ms of the submitting thread. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 137 +++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b3457e9..276d1d5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4965,6 +4965,9 @@ impl Host { split.part(1); // What flights in the air may write. let air = line().written.clone(); + if ahead_of_writes() { + batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i))); + } for list in runs { list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); @@ -6717,6 +6720,86 @@ struct Batch { placed: Vec<(std::sync::Arc, usize, Vec)>, /// Fills not done yet (destination, source, bytes): [`wide_fills`]. fills: Vec<(usize, usize, usize)>, + /// Copies (by address) brought up to date ahead of the steps, and the + /// range (from, to) ([`Batch::refresh_ahead`]). + ahead: ByCopy<(usize, usize)>, +} + +/// Whether the copies that a submission's shaders write are brought up to +/// date together, on several threads, ahead of its steps +/// (`VICTORY_REFRESH_AHEAD=0`: each before the step that gives it to them). +/// +/// 580 copies a frame, one after the other on the submitting thread, 3.4 to +/// 6.5 ms (session play-1125-0203). +fn ahead_of_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light()) +} + +/// What a step is to the copies' refreshes, for [`written_spans`]. +enum Touch { + /// A refresh of a copy (by address), from, to. + Refresh(usize, usize, usize), + /// The copy is given to shaders. + Write(usize), + /// Title memory is written. + Title, + Nothing, +} + +/// Of `steps`, up to the first that writes title memory: the copies given to +/// shaders, each with the range its refreshes before that cover. +fn written_spans(steps: impl Iterator) -> Vec<(usize, usize, usize)> { + // (From, to, given to shaders.) + let mut spans: ByCopy<(usize, usize, bool)> = ByCopy::default(); + for step in steps { + match step { + Touch::Refresh(copy, from, to) => { + let span = spans.entry(copy).or_insert((from, to, false)); + if !span.2 { + (span.0, span.1) = (span.0.min(from), span.1.max(to)); + } + } + // (Not refreshed before: nothing of it is due.) + Touch::Write(copy) => { + if let Some(span) = spans.get_mut(©) { + span.2 = true; + } + } + Touch::Title => break, + Touch::Nothing => {} + } + } + spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect() +} + +#[cfg(test)] +mod written_spans_tests { + use super::{Touch, written_spans}; + + #[test] + fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() { + use Touch::{Nothing, Refresh, Title, Write}; + let mut found = written_spans( + [ + Refresh(1, 10, 20), + Refresh(2, 0, 5), + Nothing, + Refresh(1, 30, 40), + Write(1), + Refresh(1, 0, 100), + Write(3), + Refresh(3, 1, 2), + Refresh(4, 7, 9), + Write(4), + Title, + Write(2), + ] + .into_iter(), + ); + found.sort_unstable(); + assert_eq!(found, [(1, 10, 40), (4, 7, 9)]); + } } /// Whether the fills of a submission's upload memory are done together on @@ -6755,6 +6838,9 @@ impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; let key = std::sync::Arc::as_ptr(shadow) as usize; + if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) { + return; + } match self.index.get(&key) { Some(&at) => { let r = &mut self.refreshes[at]; @@ -6770,6 +6856,8 @@ impl Batch { /// Before shaders are given a range of `shadow`'s copy: its pending /// refresh is done, the others stay pending. fn flush_one(&mut self, shadow: &std::sync::Arc) { + // From here on it is refreshed around what the shaders write. + self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize)); let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { return; }; @@ -6813,9 +6901,58 @@ impl Batch { /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); + self.ahead.clear(); self.textures.clear(); } + /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills + /// that `taken` names are not done on the CPU. + fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) { + let mut copies: ByCopy> = ByCopy::default(); + let mut touches = Vec::new(); + 'steps: for list in runs { + for (i, step) in list.deferred().copies.iter().enumerate() { + touches.push(match step { + Step::Refresh(shadow, at, len) => { + let key = std::sync::Arc::as_ptr(shadow) as usize; + copies.entry(key).or_insert_with(|| shadow.clone()); + Touch::Refresh(key, *at, *at + *len) + } + Step::GpuWrite(shadow, ..) => Touch::Write(std::sync::Arc::as_ptr(shadow) as usize), + Step::Copy(..) if taken(list, i) => Touch::Nothing, + Step::Copy(..) | Step::Run(_) | Step::Placed(_) => break 'steps, + _ => Touch::Nothing, + }); + } + } + let due: Vec<_> = written_spans(touches.into_iter()) + .into_iter() + .filter_map(|(key, from, to)| Some((copies.get(&key)?.clone(), from, to))) + .collect(); + for (shadow, from, to) in &due { + self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to)); + } + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + let started = std::time::Instant::now(); + let before = PREPARING[0].load(Ordering::Relaxed); + crate::shadow::wide_each(due.len(), move |i| { + let (shadow, from, to) = &due[i]; + if !shadow.nothing_new(*from, *to - *from) { + Self::update(shadow, *from, *to); + } + }); + // The time counted is the time it took, not the threads' sum. + let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); + PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + let ns = began.elapsed().as_nanos() as u64; + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[9].fetch_add(ns, Ordering::Relaxed); + } + } + /// The fills noted are done. fn fill(&mut self) { // Below this many the threads cost more than they save. From 5ead1cfb0bf7a4bdf541c7b54ea5f0f703b4b5e2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:38 -0600 Subject: [PATCH 10/13] The heaps' records are also looked at between submissions (VICTORY_HEAP_SYNC_EARLY=0: not) Every 4 ms while submissions come, on the thread for it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 36 +++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 043dd26..27a8c97 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -183,6 +183,20 @@ fn sync_aside() -> bool { *ON.get_or_init(|| sync_on() && std::env::var_os("VICTORY_HEAP_SYNC_ASIDE").is_none_or(|v| v != "0")) } +/// How long that thread waits for a submission before it makes a round of its +/// own (`VICTORY_HEAP_SYNC_EARLY=`, 4 if not given; `0`: none). The title +/// copies its records while it records, and the first submission of a frame +/// found all of them: 8 ms waited for (run cpu-2). A round made meanwhile +/// leaves it those written since. +#[cfg(windows)] +fn sync_early() -> Option { + static EVERY: std::sync::OnceLock> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + let ms = std::env::var("VICTORY_HEAP_SYNC_EARLY").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4u64); + (ms > 0).then(|| std::time::Duration::from_millis(ms)) + }) +} + /// The thread's work: rounds asked for, rounds done. #[cfg(windows)] static SYNC_ROUNDS: (std::sync::Mutex<(u64, u64)>, std::sync::Condvar) = (std::sync::Mutex::new((0, 0)), std::sync::Condvar::new()); @@ -211,13 +225,29 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { SYNC_ROUNDS.1.notify_all(); } } + // Between the rounds asked for, while submissions come. + let mut last = std::time::Instant::now(); loop { let mut r = rounds(); - while r.0 == r.1 { - r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); + let mut asked = r.0 != r.1; + while !asked { + let Some(every) = sync_early().filter(|_| last.elapsed().as_millis() < 500) else { + r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); + asked = r.0 != r.1; + continue; + }; + let (back, over) = SYNC_ROUNDS.1.wait_timeout(r, every).unwrap_or_else(|e| e.into_inner()); + r = back; + asked = r.0 != r.1; + if over.timed_out() { + break; + } } drop(r); - let _over = Over; + let _over = asked.then(|| { + last = std::time::Instant::now(); + Over + }); let _ = std::panic::catch_unwind(sync_heaps); } }); From ffca1949e2ca24a1dcf885dffaef53859fa95e58 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:45:39 -0600 Subject: [PATCH 11/13] The title's page mappings are mapped in runs, and not again where they are (VICTORY_MAP_RUNS=0: page by page) 13 % of the title's main thread while walking (profile cpu-1: two kernel calls for each 64 KiB page). Co-Authored-By: Claude Opus 5.5 --- crates/victory-hle/src/modules/xmem.rs | 167 ++++++++++++++++++++++++- 1 file changed, 165 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 02ba024..00a5217 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -979,10 +979,142 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( /// heap. Page by page; false if a source page is not mapped physical memory. pub fn map_alias(to: u64, from: u64, len: u64) -> bool { let (to, from, len) = (to as usize, from as usize, len as usize); + let started = std::time::Instant::now(); let mut physical = physical(); // As in `XMemMapPhysicalPages`: no read in place meets the gap. let _changing = victory_gpu::title_memory_remapping(); - unmap(&mut physical, to, len); + let ok = if alias_runs() { alias_in_runs(&mut physical, to, from, len) } else { alias_pages(&mut physical, to, from, len) }; + alias_line([1, (len / PAGE) as u64, 0, 0, started.elapsed().as_micros() as u64]); + ok +} + +/// Whether the pages of one mapping are mapped in runs (`VICTORY_MAP_RUNS=0`: +/// each with a call of its own, as before). +/// +/// While the player walks, the title maps and unmaps thousands of pages of its +/// tiled heap a second (what it streams in), and did it on the thread its +/// frame waits for: 13 % of that thread's time in the two kernel calls for +/// each 64 KiB page (profile cpu-1: `NtUnmapViewOfSectionEx`, +/// `NtMapViewOfSectionEx`). Pages next to one another in the heap and in the +/// section are one view; a page that shows what it is to show is left alone. +fn alias_runs() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MAP_RUNS").is_none_or(|v| v != "0")) +} + +/// Since the last line: calls of [`map_alias`], their pages, pages that +/// showed the same already, views mapped, microseconds. The line itself, at +/// most every five seconds. +fn alias_line(add: [u64; 5]) { + use std::sync::atomic::AtomicU64; + static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + static SAID: Mutex> = Mutex::new(None); + for (count, n) in COUNTS.iter().zip(add) { + count.fetch_add(n, Ordering::Relaxed); + } + if add[0] == 0 { + return; + } + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + let before = said.get_or_insert_with(std::time::Instant::now); + let secs = before.elapsed().as_secs_f64(); + if secs < 5.0 { + return; + } + *before = std::time::Instant::now(); + let [calls, pages, same, views, us] = [0, 1, 2, 3, 4].map(|i| COUNTS[i].swap(0, Ordering::Relaxed) as f64 / secs); + tracing::info!( + "page mappings of the title's queues per second: {calls:.0} calls for {pages:.0} pages, {same:.0} of them as they were, {views:.0} \ + views mapped, {:.1} ms (VICTORY_MAP_RUNS)", + us / 1e3 + ); +} + +/// What title memory at `at` shows, if it shows a physical page. +fn shown_slice(physical: &Physical, at: usize) -> Option { + let (base, (_, s)) = physical.views.range(..=at).next_back().filter(|(base, (size, _))| at < **base + *size)?; + Some(Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) +} + +fn follows(a: &Slice, b: &Slice) -> bool { + Arc::ptr_eq(&a.section, &b.section) && a.index + 1 == b.index +} + +/// [`map_alias`], in runs ([`alias_runs`]). +fn alias_in_runs(physical: &mut Physical, to: usize, from: usize, len: usize) -> bool { + if from == 0 || len == 0 { + unmap(physical, to, len); + return true; + } + let pages = len.div_ceil(PAGE); + // What is to be shown, up to the first page that has no source. + let wanted: Vec = (0..pages).map_while(|k| shown_slice(physical, from + k * PAGE)).collect(); + let same: Vec = wanted + .iter() + .enumerate() + .map(|(k, w)| shown_slice(physical, to + k * PAGE).is_some_and(|s| Arc::ptr_eq(&s.section, &w.section) && s.index == w.index)) + .collect(); + let mut k = 0; + while k < wanted.len() { + let mut end = k + 1; + while end < wanted.len() && same[end] == same[k] && (same[k] || follows(&wanted[end - 1], &wanted[end])) { + end += 1; + } + let (at, bytes) = (to + k * PAGE, (end - k) * PAGE); + if same[k] { + // The title says so because it put other bytes there. + victory_gpu::title_memory_written(at, bytes, true); + alias_line([0, 0, (end - k) as u64, 0, 0]); + } else { + unmap(physical, at, bytes); + if !map_run(physical, at, end - k, &wanted[k]) { + return false; + } + } + k = end; + } + if wanted.len() < pages { + unmap(physical, to + wanted.len() * PAGE, len - wanted.len() * PAGE); + return false; + } + true +} + +/// Maps `pages` pages of a section, from `slice` on, at `base`, where only +/// placeholders are: as one view, or page by page if that cannot be. +fn map_run(physical: &mut Physical, base: usize, pages: usize, slice: &Slice) -> bool { + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + if pages > 1 { + // Each page a placeholder of its own (harmless where it is one, or + // not at the edge of one), then all of them one. + // SAFETY: both act on placeholders only. + let one = unsafe { + for k in 0..pages { + VirtualFree((base + k * PAGE) as *mut c_void, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER); + } + VirtualFree(base as *mut c_void, pages * PAGE, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS) != 0 + }; + if one { + alias_line([0, 0, 0, 1, 0]); + return map(physical, base, pages * PAGE, slice.clone()); + } + } + alias_line([0, 0, 0, pages as u64, 0]); + (0..pages).all(|k| { + let slice = Slice { + index: slice.index + k, + section: slice.section.clone(), + }; + map(physical, base + k * PAGE, PAGE, slice) + }) +} + +/// [`map_alias`], page by page. +fn alias_pages(physical: &mut Physical, to: usize, from: usize, len: usize) -> bool { + unmap(physical, to, len); for k in (0..len).step_by(PAGE) { if from == 0 { break; @@ -1000,7 +1132,7 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { else { return false; }; - if !map(&mut physical, to + k, PAGE, slice) { + if !map(physical, to + k, PAGE, slice) { return false; } } @@ -1483,6 +1615,37 @@ mod tests { assert!(map_alias(b as u64, 0, PAGE as u64)); assert_eq!(query(b).host.State, MEM_RESERVE); assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64)); + // All three in their order again, three at once at `b`, from the + // middle on another page, and back. + let scattered = [at(a, 1)]; + assert_eq!(XMemMapPhysicalPagesScatter(scattered.as_ptr(), 1, pages[1..].as_ptr()), 1); + // SAFETY: mapped read-write, both. + let same = |k: usize, page: usize, value: u8| unsafe { + at(a, page).cast::().add(64).write(value); + assert_eq!(at(b, k).cast::().add(64).read(), value, "page {k}"); + }; + for _ in 0..2 { + assert!(map_alias(b as u64, a as u64, 3 * PAGE as u64)); + for k in 0..3 { + same(k, k, 40 + k as u8); + } + } + assert!(map_alias(at(b, 1) as u64, a as u64, PAGE as u64)); + same(0, 0, 51); + same(1, 0, 52); + same(2, 2, 53); + assert!(map_alias(b as u64, at(a, 1) as u64, 2 * PAGE as u64)); + same(0, 1, 54); + same(1, 2, 55); + same(2, 2, 56); + // A source that ends: what came before it is mapped, the rest not. + assert!(map_alias(at(a, 1) as u64, 0, PAGE as u64)); + assert!(!map_alias(b as u64, a as u64, 2 * PAGE as u64)); + same(0, 0, 57); + assert_eq!(query(at(b, 1)).host.State, MEM_RESERVE); + same(2, 2, 58); + assert!(map_alias(b as u64, 0, 3 * PAGE as u64)); + assert_eq!(query(at(b, 2)).host.State, MEM_RESERVE); assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); assert_eq!(XMemIsToolsMemAvailable(), 0); } From 9ec6973b4840ae1c47169f46fc973381a2d722ed Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:38:51 -0600 Subject: [PATCH 12/13] AMD's wait instructions are replaced in place at their first fault (VICTORY_PATCH_WAITS=0: emulated each time) monitorx and mwaitx raised an illegal instruction exception at every pass of the title's wait loops. Diagnostics builds log the faulting console instructions a second by kind and place. Co-Authored-By: Claude Opus 5.5 --- crates/victory-loader/src/console_insn.rs | 227 +++++++++++++++++++++- 1 file changed, 225 insertions(+), 2 deletions(-) diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index 946230d..775961c 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -46,6 +46,154 @@ static EMULATED: AtomicU64 = AtomicU64::new(0); static ASKED: AtomicU64 = AtomicU64::new(0); static ZEROED: AtomicU64 = AtomicU64::new(0); +/// Whether `monitorx` and `mwaitx` are replaced in the title's code the first time they fault +/// (`monitorx` by a 3-byte no-op, `mwaitx` by `pause` and a no-op), so that they never fault +/// again. Emulated, each pass of such a wait loop is two trips into Windows and back, through +/// every vectored handler, and no lighter a wait for it: the emulation does no more than +/// `pause` either, and the loop looks at its value again after it. On by default; +/// `VICTORY_PATCH_WAITS=0` emulates each time, as before. +fn patches_waits() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PATCH_WAITS").is_none_or(|v| v != "0")) +} + +/// What replaces the 3 bytes of a wait instruction. +fn wait_patch(what: ConsoleOnly) -> Option<[u8; 3]> { + match what { + ConsoleOnly::Monitorx => Some([0x0f, 0x1f, 0x00]), + ConsoleOnly::Mwaitx => Some([0xf3, 0x90, 0x90]), + _ => None, + } +} + +/// The aligned 8 bytes `word` around address `at` with the 3 bytes at `at` replaced; `None` +/// where they do not all lie in those 8. +fn with_patch(word: u64, at: usize, patch: [u8; 3]) -> Option { + let offset = at & 7; + if offset + patch.len() > 8 { + return None; + } + let mut bytes = word.to_le_bytes(); + bytes[offset..offset + patch.len()].copy_from_slice(&patch); + Some(u64::from_le_bytes(bytes)) +} + +/// One thread at a time changes code: a second one would take the first one's loosened +/// protection for the page's own. +static PATCHING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Replaces the 3 bytes at `at`, which are `was`, by `patch`, in one store that other threads +/// see whole: whether they are replaced now (not where they cross 8 aligned bytes, or the page +/// cannot be written). +/// +/// # Safety +/// `at` is in code that stays mapped, and `patch` does for it what `was` does. +unsafe fn patch(at: usize, was: [u8; 3], patch: [u8; 3]) -> bool { + use std::sync::atomic::Ordering::SeqCst; + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if (at & 7) + 3 > 8 { + return false; + } + let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner()); + let word = (at & !7) as *mut u64; + let here = (at & 7)..(at & 7) + 3; + let mut old = 0u32; + // SAFETY: the aligned 8 bytes around the instruction lie in one page of mapped code, made + // writable for the store and put back. + unsafe { + if VirtualProtect(word.cast(), 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return false; + } + let done = AtomicU64::from_ptr(word) + .fetch_update(SeqCst, SeqCst, |now| if now.to_le_bytes()[here.clone()] == was { with_patch(now, at, patch) } else { None }) + // (Another thread's fault at the same place: done already.) + .map_or_else(|now| now.to_le_bytes()[here.clone()] == patch, |_| true); + VirtualProtect(word.cast(), 8, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), word.cast(), 8); + done + } +} + +/// Diagnostics: how often each place in the title's code raises one of these exceptions, the +/// busiest logged every five seconds. +#[cfg(feature = "diagnostics")] +mod sites { + use super::{AtomicU64, Relaxed}; + use std::sync::atomic::AtomicUsize; + + /// Address, what is there (an index into [`NAMES`]), exceptions since the last line. + static SITES: [(AtomicUsize, AtomicUsize, AtomicU64); 512] = + [const { (AtomicUsize::new(0), AtomicUsize::new(0), AtomicU64::new(0)) }; 512]; + const NAMES: [&str; 8] = ["other", "clwb", "monitorx", "mwaitx", "clzero", "clzero loop", "rdpru", "extrq/insertq"]; + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + static PATCHED: AtomicU64 = AtomicU64::new(0); + + pub(super) fn patched() { + PATCHED.fetch_add(1, Relaxed); + } + + pub(super) fn count(at: usize, what: super::ConsoleOnly) { + use super::ConsoleOnly as C; + let kind = match what { + C::Clwb => 1, + C::Monitorx => 2, + C::Mwaitx => 3, + C::Clzero => 4, + C::ClzeroLoop { .. } => 5, + C::Rdpru => 6, + C::Extrq { .. } | C::Insertq { .. } => 7, + _ => 0, + }; + let mut i = (at ^ at >> 9) % SITES.len(); + for _ in 0..8 { + let s = &SITES[i]; + let there = s.0.compare_exchange(0, at, Relaxed, Relaxed).unwrap_or_else(|there| there); + if there == 0 || there == at { + s.1.store(kind, Relaxed); + s.2.fetch_add(1, Relaxed); + break; + } + i = (i + 1) % SITES.len(); + } + // Now and then: is a line due? Never waited for. + if let Ok(mut last) = LAST.try_lock() { + let since = *last.get_or_insert_with(std::time::Instant::now); + if since.elapsed().as_secs() >= 5 { + let s = since.elapsed().as_secs_f64(); + *last = Some(std::time::Instant::now()); + drop(last); + line(s); + } + } + } + + fn line(seconds: f64) { + let mut all: Vec<(u64, usize, usize)> = + SITES.iter().map(|s| (s.2.swap(0, Relaxed), s.0.load(Relaxed), s.1.load(Relaxed))).filter(|s| s.0 > 0).collect(); + all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0)); + let mut kinds = [0u64; NAMES.len()]; + for s in &all { + kinds[s.2] += s.0; + } + let kinds: Vec = NAMES + .iter() + .zip(kinds) + .filter(|(_, n)| *n > 0) + .map(|(name, n)| format!("{name} {:.0}", n as f64 / seconds)) + .collect(); + let top: Vec = + all.iter().take(8).map(|s| format!("{:#x} {} {:.0}", s.1, NAMES[s.2], s.0 as f64 / seconds)).collect(); + tracing::info!( + "console CPU instructions that fault, a second: {}; wait instructions replaced in place so far: {}; the busiest places: {}", + kinds.join(", "), + PATCHED.load(Relaxed), + top.join(", ") + ); + } +} + fn readable(va: usize, bytes: usize) -> bool { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; // SAFETY: plain data filled in by the query. @@ -135,12 +283,17 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)"); } } + #[cfg(feature = "diagnostics")] + if what != ConsoleOnly::Ud2 { + sites::count(rip, what); + } match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { // nothing to write back on the PC: patched to NOPs, no exception next time use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; let mut old = 0u32; + let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: the instruction's own bytes, made writable for the patch and restored. unsafe { if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { @@ -149,8 +302,20 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } } } - ConsoleOnly::Monitorx => {} - ConsoleOnly::Mwaitx => std::hint::spin_loop(), + ConsoleOnly::Monitorx | ConsoleOnly::Mwaitx => { + // Without a prefix, so 3 bytes: replaced, the next pass does not fault. + if len == 3 + && patches_waits() + && let Some(new) = wait_patch(what) + // SAFETY: the title's code, where the instruction just faulted; both + // replacements are waits that wait for nothing, as the emulation is. + && unsafe { patch(rip, [code[0], code[1], code[2]], new) } + { + #[cfg(feature = "diagnostics")] + sites::patched(); + } + std::hint::spin_loop(); + } ConsoleOnly::Clzero => { // with an address-size prefix (0x67) the line is at EAX, zero-extended let a32 = code[..len - 3].contains(&0x67); @@ -255,3 +420,61 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } CONTINUE_EXECUTION } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wait_instructions_are_replaced_inside_eight_aligned_bytes() { + let word = u64::from_le_bytes([1, 2, 0x0f, 0x01, 0xfb, 6, 7, 8]); + let new = with_patch(word, 0x1002, [0xf3, 0x90, 0x90]).unwrap(); + assert_eq!(new.to_le_bytes(), [1, 2, 0xf3, 0x90, 0x90, 6, 7, 8]); + assert!(with_patch(word, 0x1005, [0; 3]).is_some()); + assert!(with_patch(word, 0x1006, [0; 3]).is_none(), "crosses into the next eight"); + } + + /// `monitorx; mwaitx; ret` in a page of its own: each is replaced at its first fault, + /// and the page is protected as before. + #[test] + fn a_wait_faults_once_and_the_page_keeps_its_protection() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualFree, + VirtualProtect, VirtualQuery, + }; + // SAFETY: memory of our own, read, written and run within its page. + unsafe { + let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE).cast::(); + assert!(!page.is_null()); + let code = [0x0f, 0x01, 0xfa, 0x0f, 0x01, 0xfb, 0xc3]; + // Both within the aligned eight bytes at 8; and one over the end of its eight + // (at 22), which is left alone. + std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(8), code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(22), code.len()); + let mut old = 0; + assert_ne!(VirtualProtect(page.cast(), 4096, PAGE_EXECUTE_READ, &mut old), 0); + let at = page as usize; + let mut context: CONTEXT = std::mem::zeroed(); + for rip in [at + 8, at + 11, at + 22] { + context.Rip = rip as u64; + assert_eq!(emulate(&mut context), CONTINUE_EXECUTION); + assert_eq!(context.Rip, rip as u64 + 3); + } + if patches_waits() { + let now = std::slice::from_raw_parts(page.add(8), 7); + assert_eq!(now, [0x0f, 0x1f, 0x00, 0xf3, 0x90, 0x90, 0xc3]); + // They run now. + let run: extern "system" fn() = std::mem::transmute(page.add(8)); + run(); + // A second thread that faulted at the same place meanwhile. + assert!(patch(at + 8, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00])); + assert!(!patch(at + 22, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its eight bytes"); + } + assert_eq!(std::slice::from_raw_parts(page.add(22), 3), [0x0f, 0x01, 0xfa]); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(page.cast(), &mut m, size_of_val(&m)); + assert_eq!(m.Protect, PAGE_EXECUTE_READ); + VirtualFree(page.cast(), 0, MEM_RELEASE); + } + } +} From 92cce2ac9d11539bd0a379a4cc702389aef8daad Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:38:51 -0600 Subject: [PATCH 13/13] Submissions are prepared and sent by a thread of ours (VICTORY_ASYNC_SUBMIT=1, off) The idea is fxceless/victory-fork's, commit f85101b6. Here one line holds what all queues were given, presents too, in the order of the calls. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/fence.rs | 1 + crates/victory-gpu/src/host.rs | 7 +- crates/victory-gpu/src/queue.rs | 111 +++- crates/victory-gpu/src/queue/behind.rs | 758 +++++++++++++++++++++++++ 4 files changed, 868 insertions(+), 9 deletions(-) create mode 100644 crates/victory-gpu/src/queue/behind.rs diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index b066fd6..d3103b0 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -101,6 +101,7 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c #[cfg(windows)] if crate::host::late() { drop(waiters); + crate::queue::before_sync(); crate::host::settle_for_fence(); if fence.value.load(Ordering::Acquire) >= value { return S_OK; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c505bcb..2bbfa54 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -285,7 +285,9 @@ pub(crate) fn submissions() -> (u64, u64) { /// Drops `object` once every submission running now has finished: at once /// if none is. pub(crate) fn retire(object: T) { - let started = STARTED.load(Ordering::Acquire); + // (Those the title made and the host has not begun get the next numbers.) + let queued = crate::queue::queued(); + let started = STARTED.load(Ordering::Acquire) + queued; if started <= FINISHED.load(Ordering::Acquire) { RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); drop(object); @@ -4625,6 +4627,8 @@ impl Host { /// Runs closed lists and waits for them, and with [`late`] for /// everything sent to the card before them, which is settled first. pub(crate) fn execute(&self, runs: &[&HostList]) { + // Behind what the title's queues were given before it. + crate::queue::before_sync(); let _ = self.submit(runs, false); } @@ -7680,6 +7684,7 @@ impl Meter { crate::shadow::exact_line(frames); crate::descriptor::sync_line(frames); late_line(frames); + crate::queue::behind_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 069a431..47fd0b7 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -7,6 +7,9 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; +#[cfg(windows)] +mod behind; + const QUEUE_IIDS: [Iid; 4] = [ guid( 0x0ec870a6, @@ -307,6 +310,11 @@ fn hold(this: This, what: impl FnOnce() -> Held) -> bool { /// one. #[cfg(windows)] pub(crate) fn release_held(all: bool) { + if behind::on() { + // What queues stand at is looked at by the thread that runs them. + behind::wake(); + return; + } // One caller at a time, so a queue's submissions keep their order. static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); if lock(&WAITING).is_empty() { @@ -423,6 +431,30 @@ pub(crate) fn release_held(all: bool) { } } +/// Before a submission of ours that is waited for, or a wait for flights by +/// a thread of the title's: what the title gave its queues before goes to the +/// card first ([`behind`]). +#[cfg(windows)] +pub(crate) fn before_sync() { + if behind::on() { + behind::drain(); + } +} + +/// Submissions the title made that the host has not begun ([`behind`]). +#[cfg(windows)] +pub(crate) fn queued() -> u64 { + behind::queued() +} + +/// For the frame-rate line. +#[cfg(windows)] +pub(crate) fn behind_line(frames: f64) { + if behind::on() { + behind::line(frames); + } +} + /// Whether a queue may pass `wait`: memory holds the value, or, with /// submissions sent to the card without a wait (`crate::host::late`), it /// will once those in the air have run. @@ -521,6 +553,10 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + if behind::on() && !this.is_null() { + behind::submit(this, lists); + return; + } if cuts() && !this.is_null() { submit_cut(this, lists); return; @@ -614,6 +650,11 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + #[cfg(windows)] + if behind::on() && !this.is_null() { + behind::signal(this, fence, value); + return S_OK; + } // A queue that waits signals after what it holds. #[cfg(windows)] if hold(this, || Held::Signal(fence as usize, value)) { @@ -651,6 +692,10 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { } #[cfg(feature = "diagnostics")] crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + if behind::on() && waits() { + behind::wait(this, fence, value); + return S_OK; + } let behind = { let mut held = lock(&queue(this).held); let behind = !held.is_empty() || now < value; @@ -755,17 +800,21 @@ pub(crate) fn presented() -> u64 { /// shortcut: one plane, no scaling or placement, the source expected in /// the common state. extern "system" fn present( - _: This, + this: This, planes: u32, plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + #[cfg(not(windows))] + let _ = this; #[cfg(all(windows, feature = "diagnostics"))] crate::copystat::present_begins(); // Submissions sent to the card and not waited for are settled first, // and what that frees runs in its own order, before anything is forced. #[cfg(windows)] - if crate::host::late() && !crate::host::late_free_present() { + if behind::on() { + // The present goes into the line of what the queues were given. + } else if crate::host::late() && !crate::host::late_free_present() { crate::host::settle_for_present(); release_held(false); crate::host::settle_for_present(); @@ -777,7 +826,9 @@ extern "system" fn present( // shortcut: what a queue still holds at a present runs now, whatever // its fence: a wait is not kept across frames. #[cfg(windows)] - release_held(forces()); + if !behind::on() { + release_held(forces()); + } let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); @@ -811,10 +862,36 @@ extern "system" fn present( { crate::capture::frame_drew(frame, crate::draw::drawn()); if crate::capture::listed(frame) { + before_sync(); crate::capture::dump_targets(frame); } } #[cfg(windows)] + if behind::on() && !this.is_null() { + const COPY_SOURCE: u32 = 0x800; + let texture = if planes > 0 + // SAFETY: the title passes `planes` plane descriptions. + && let Some(plane) = unsafe { plane_parameters.as_ref() } + && plane.count > 0 + && !plane.resources.is_null() + { + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + // The state the lists recorded so far leave it in (the next + // frame's, recorded before this is shown, go on from there). + crate::resource::host_copy(resource).map(|copy| { + let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + crate::resource::host_transition(resource, state); + (resource as usize, copy, state) + }) + } else { + None + }; + let resource = texture.as_ref().map_or(0, |t| t.0); + behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource }); + return S_OK; + } + #[cfg(windows)] if planes > 0 // SAFETY: the title passes `planes` plane descriptions. && let Some(plane) = unsafe { plane_parameters.as_ref() } @@ -828,17 +905,35 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let shown = host.present(texture, state, frame); + show(texture, state, Shown { frame, resource: resource as usize }); crate::resource::host_transition(resource, state); - #[cfg(feature = "diagnostics")] - blinks(frame, resource, state, shown); - #[cfg(not(feature = "diagnostics"))] - let _ = shown; + let _ = host; } #[cfg(not(windows))] let _ = (planes, plane_parameters); S_OK } +/// The frame a present shows, and the title's resource it shows. +#[cfg(windows)] +#[derive(Clone, Copy)] +struct Shown { + frame: u64, + resource: usize, +} + +/// Shows `texture`, in host state `state`, in our window. +#[cfg(windows)] +fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) { + let Some(host) = crate::host::host() else { + return; + }; + let shown = host.present(texture, state, what.frame); + #[cfg(feature = "diagnostics")] + blinks(what.frame, what.resource as This, state, shown); + #[cfg(not(feature = "diagnostics"))] + let _ = (shown, what.resource); +} + /// Diagnostics: logs a presented frame that is black after one that was /// not, with what was presented and how many draws ran since. #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs new file mode 100644 index 0000000..8089997 --- /dev/null +++ b/crates/victory-gpu/src/queue/behind.rs @@ -0,0 +1,758 @@ +//! Submissions prepared and sent by a thread of ours, in order, instead of by +//! the thread of the title that submits them (`VICTORY_ASYNC_SUBMIT=1`). +//! +//! The idea and the argument are fxceless/victory-fork's, commit f85101b6 +//! (GPL-3.0-or-later, as this): a profile had the title's render thread inside +//! `queue::execute` for 202 of 292 ms of a frame while its recording threads +//! and the card stood idle, and the title does nothing with the result of that +//! work: it only has to be done before the lists run, in order. (Here, at +//! 77-79 ms a frame: 58 ms of it in the submit calls, the card idle for 37 ms +//! behind them.) What differs from that commit: one line for all queues, kept +//! in the order of the title's calls; the present stands in it too; nobody but +//! our thread runs what is in it. +//! +//! With the switch a submission's lists are taken from the title's lists (as +//! they are for every flight, `crate::list::detach`) and put in the [`Lane`], +//! with what they wait for, the queues' fence waits and signals, and the +//! presents. [`Lane::serve`], on a thread of ours, takes from it whatever is +//! free to run, the oldest first; within a queue the order is the title's, +//! always. What tells the title that work is done (fence values, +//! bottom-of-pipe writes) is told by the flights as before, when the card has +//! run them: later than the title's call by more than before, never earlier. +//! +//! What the title may do between its submit call and the moment our thread +//! prepares the lists, and why that is all right: +//! +//! - Reset or release the lists and allocators: their host sides, upload +//! memory and draw state were taken out of them. +//! - Write upload memory, descriptors, constants for later lists: those of +//! lists submitted are the card's to read until a fence behind them is +//! reached, on the console as here; no fence behind them is reached before +//! the lists have run ([`signal`] goes into the line behind them). +//! - Signal, wait, present on the queue: in the line behind them. +//! - Write a fence or a value in memory by the CPU: at once; our thread looks +//! at what it stands at again ([`wake`], and every millisecond). +//! - Map pages (`CopyPageMappingsBatchX`): at once, as before, where the lists +//! on the card may be reading them too; the bytes of uploads were read when +//! the lists were recorded. +//! - Ask for something that has to see earlier submissions done (a read-back, +//! a fence waited for without an event): [`drain`] first. +//! - Release a texture or a view's memory: what is retired waits for what is +//! in the line too ([`queued`]). +//! +//! The line is bounded: a present returns when the one before it was shown +//! ([`frames_most`]), and a submission when at most [`runs_most`] are in the +//! line. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +use super::This; + +/// One thing in the line: what it stands at, if it does, and what it does. +pub(super) trait Work: Send { + /// What has to be met before it goes. + type Ask; + fn ask(&self) -> Option; + fn met(ask: &Self::Ask) -> bool; + /// Whether it is a present: everything before it goes first, met or not. + fn shows(&self) -> bool; + /// Whether it is a submission. + fn runs(&self) -> bool; + /// Does it. `forced`: its wait was not met. + fn go(self, forced: bool); +} + +struct Entry { + number: u64, + queue: usize, + what: W, +} + +struct State { + /// In the order of the title's calls, whatever queue they were made on. + items: VecDeque>, + /// The number the next entry gets. + next: u64, + /// The queue whose entry is being done now (it is no longer in `items`; + /// what that queue is given stays behind it all the same). + running: Option, + /// Times a look at the line was asked for, and the last of them that a + /// whole look has followed. + asked: u64, + served: u64, + /// Presents and submissions in the line or being done. + presents: usize, + runs: usize, +} + +/// See the module's text. +pub(super) struct Lane { + state: Mutex>, + /// Something to look at. + work: Condvar, + /// Something was done, or a look at the line ended. + moved: Condvar, +} + +impl Lane { + pub(super) const fn new() -> Self { + Lane { + state: Mutex::new(State { + items: VecDeque::new(), + next: 0, + running: None, + asked: 0, + served: 0, + presents: 0, + runs: 0, + }), + work: Condvar::new(), + moved: Condvar::new(), + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn put(state: &mut State, queue: usize, what: W) { + state.presents += usize::from(what.shows()); + state.runs += usize::from(what.runs()); + let number = state.next; + state.next += 1; + state.items.push_back(Entry { number, queue, what }); + } + + /// Adds to the end of the line, and has it looked at. + pub(super) fn push(&self, queue: usize, what: impl IntoIterator) { + let mut state = self.lock(); + for what in what { + Self::put(&mut state, queue, what); + } + state.asked += 1; + drop(state); + self.work.notify_one(); + } + + /// Adds `what` if `queue` has anything in the line or being done (or + /// `always`); else does `now`, with nothing of the queue's able to come + /// in between. + pub(super) fn push_behind(&self, queue: usize, always: bool, what: W, now: impl FnOnce()) { + let mut state = self.lock(); + if always || state.running == Some(queue) || state.items.iter().any(|e| e.queue == queue) { + Self::put(&mut state, queue, what); + } else { + now(); + } + state.asked += 1; + drop(state); + self.work.notify_one(); + } + + /// Has the line looked at: something an entry stands at may have moved. + pub(super) fn wake(&self) { + let mut state = self.lock(); + if state.items.is_empty() { + return; + } + state.asked += 1; + drop(state); + self.work.notify_one(); + } + + /// Waits until everything in the line that is free to run has been done + /// (what comes in after this call may not be). + pub(super) fn drain(&self) { + let mut state = self.lock(); + if state.items.is_empty() && state.running.is_none() { + return; + } + state.asked += 1; + let ticket = state.asked; + self.work.notify_one(); + while state.served < ticket { + state = self.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + /// Waits until at most `most` presents are in the line. + pub(super) fn wait_presents(&self, most: usize) { + let mut state = self.lock(); + while state.presents > most { + state = self.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + /// Waits until at most `most` submissions are in the line, or what is + /// left of it stands at something. + pub(super) fn wait_runs(&self, most: usize) { + let mut state = self.lock(); + while state.runs > most && state.served < state.asked { + state = self.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + /// Looks at the line for as long as the process runs. + fn serve(&self) -> ! { + loop { + let (asked, limit) = { + let mut state = self.lock(); + while state.asked == state.served { + if state.items.is_empty() { + state = self.work.wait(state).unwrap_or_else(|e| e.into_inner()); + } else { + // It stands at something the CPU may write without + // a call of ours. + let (back, out) = + self.work.wait_timeout(state, Duration::from_millis(1)).unwrap_or_else(|e| e.into_inner()); + state = back; + if out.timed_out() { + break; + } + } + } + (state.asked, state.next) + }; + self.look(limit); + let mut state = self.lock(); + state.served = state.served.max(asked); + drop(state); + self.moved.notify_all(); + } + } + + /// Does what is free to run of the entries before number `limit`. + pub(super) fn look(&self, limit: u64) { + while self.step(limit) {} + } + + /// Does one entry: the oldest that is the first of its queue and free to + /// run. Whether there was one. Only one thread calls this. + fn step(&self, limit: u64) -> bool { + // Each queue's first entry, oldest first. + let mut heads: Vec<(u64, usize, Option, bool)> = Vec::new(); + { + let state = self.lock(); + for e in state.items.iter().take_while(|e| e.number < limit) { + if !heads.iter().any(|h| h.1 == e.queue) { + heads.push((e.number, e.queue, e.what.ask(), e.what.shows())); + } + } + } + let Some(&(first, ..)) = heads.first() else { + return false; + }; + let ready = heads.iter().find(|(number, _, ask, shows)| match ask { + Some(ask) => W::met(ask), + // A present comes behind everything given before it. + None => !shows || *number == first || !super::forces(), + }); + let (number, forced) = match ready { + Some(head) => (head.0, false), + None => { + // Nothing is free to run. With a present in the line the + // oldest goes on regardless: a wait is not kept across + // frames (`super::present`). + let state = self.lock(); + if !super::forces() || !state.items.iter().any(|e| e.number < limit && e.what.shows()) { + return false; + } + (first, true) + } + }; + let entry = { + let mut state = self.lock(); + let Some(at) = state.items.iter().position(|e| e.number == number) else { + return false; + }; + let Some(entry) = state.items.remove(at) else { + return false; + }; + state.running = Some(entry.queue); + entry + }; + let (shows, runs) = (entry.what.shows(), entry.what.runs()); + entry.what.go(forced); + { + let mut state = self.lock(); + state.running = None; + state.presents -= usize::from(shows); + state.runs -= usize::from(runs); + } + self.moved.notify_all(); + true + } +} + +/// What the title's queues put in the line. +enum Job { + /// The queue waits for the fence (its address) to reach the value. + Wait(usize, u64), + /// A part of a submission waits for a memory value. + Value(crate::list::ValueWait), + /// A submission, or a part of one: the lists' host sides and the order + /// they run in. + Run(usize, Vec, Vec), + /// A signal of the queue's. + Signal(usize, u64), + /// A frame is shown: the texture and the state its lists leave it in. + Present(Option<(std::sync::Arc, u32)>, super::Shown), +} + +// SAFETY: D3D12 objects are free-threaded; a job is touched by whoever put it +// in the line and then, once it is taken out, by our thread alone (the flights +// it becomes are handed to other threads the same way). +unsafe impl Send for Job {} + +enum Ask { + Wait(usize, u64), + Value(crate::list::ValueWait), +} + +impl Work for Job { + type Ask = Ask; + + fn ask(&self) -> Option { + match self { + &Job::Wait(fence, value) => Some(Ask::Wait(fence, value)), + Job::Value(wait) => Some(Ask::Value(*wait)), + _ => None, + } + } + + fn met(ask: &Ask) -> bool { + match ask { + &Ask::Wait(fence, value) => crate::fence::completed(fence as This) >= value, + Ask::Value(wait) => super::value_met(wait), + } + } + + fn shows(&self) -> bool { + matches!(self, Job::Present(..)) + } + + fn runs(&self) -> bool { + matches!(self, Job::Run(..)) + } + + fn go(self, forced: bool) { + let began = Instant::now(); + if forced { + STATS[FORCED].fetch_add(1, Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Forced, 1); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("a queue still stood at a wait at a present: it was not met")); + } + match self { + Job::Wait(..) | Job::Value(..) => {} + Job::Run(queue, lists, order) => { + let _ = queue; + #[cfg(feature = "diagnostics")] + crate::capture::op(queue, || format!("RUN submission of {} lists (its thread's)", order.len())); + match crate::host::host() { + Some(host) => host.execute_late(lists, order), + None => drop(lists), + } + QUEUED.fetch_sub(1, Relaxed); + } + Job::Signal(fence, value) => { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + Job::Present(texture, shown) => { + if let Some((texture, state)) = texture { + super::show(&texture.texture, state, shown); + } + QUEUED.fetch_sub(1, Relaxed); + } + } + STATS[BUSY].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + } +} + +static LANE: Lane = Lane::new(); + +/// Submissions and presents in the line that have not been given to the host +/// yet. +static QUEUED: AtomicU64 = AtomicU64::new(0); + +/// Since the last frame-rate line: submissions put in the line, presents, the +/// times they found things in it (the sum of their numbers) and the most; what +/// threads of the title waited, in microseconds, for room in the line, at a +/// present, and for a drain, and the drains; what our thread worked; waits +/// not met at a present. +static STATS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; +const RUNS: usize = 0; +const PRESENTS: usize = 1; +const DEPTH: usize = 2; +const DEEPEST: usize = 3; +const ROOM: usize = 4; +const AT_PRESENT: usize = 5; +const DRAINING: usize = 6; +const DRAINS: usize = 7; +const BUSY: usize = 8; +const FORCED: usize = 9; + +/// How many submissions may be in the line when a submit call returns +/// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's). +fn runs_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| number("VICTORY_SUBMIT_DEPTH").unwrap_or(64).max(1)) +} + +/// How many presents may be in the line when a present call returns +/// (`VICTORY_SUBMIT_FRAMES`; 1: the frame before is sent, this one may not be; +/// 0: both are). +fn frames_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| number("VICTORY_SUBMIT_FRAMES").unwrap_or(1)) +} + +fn number(name: &str) -> Option { + std::env::var(name).ok()?.trim().parse().ok() +} + +thread_local! { + /// This is the thread that does what is in the line. + static OURS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether submissions are prepared by a thread of ours +/// (`VICTORY_ASYNC_SUBMIT=1`; needs flights with the present sent ahead, as +/// the relay has them, and lists cut at their waits). +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") { + return false; + } + if !crate::host::late_free_present() || !super::cuts() { + tracing::warn!("VICTORY_ASYNC_SUBMIT=1 needs the relay and lists cut at their waits: submissions are prepared by the thread that makes them"); + return false; + } + let worker = || { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL}; + // SAFETY: this thread's own priority. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + OURS.set(true); + let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| LANE.serve())); + if ended.is_err() { + // Nothing would ever be sent again, and the title's thread + // would stand at its next present for good. + crate::host::fail(format_args!("the thread that prepares and sends submissions panicked")); + } + }; + match std::thread::Builder::new().name("victory-submit".into()).spawn(worker) { + Ok(_) => { + tracing::info!( + frames = frames_most(), + runs = runs_most(), + "submissions are prepared and sent by a thread of ours, not by the thread that submits (VICTORY_ASYNC_SUBMIT=1)" + ); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread to prepare submissions: the threads that make them do"); + false + } + } + }) +} + +/// Submissions in the line that the host has not begun +/// (`crate::host::retire` waits for them too). +pub(super) fn queued() -> u64 { + QUEUED.load(Relaxed) +} + +/// Something a queue may stand at moved. +pub(super) fn wake() { + LANE.wake(); +} + +/// Before something that has to see the submissions made so far sent: they +/// are, as far as they are free to run. Not on our own thread, which is +/// inside one of them. +pub(super) fn drain() { + if OURS.get() { + return; + } + let began = Instant::now(); + LANE.drain(); + STATS[DRAINING].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + STATS[DRAINS].fetch_add(1, Relaxed); +} + +/// A submission of `lists` to queue `this`. +pub(super) fn submit(this: This, lists: &[This]) { + let queue = this as usize; + // In one piece up to the first list that waits for a memory value, as + // `super::submit_cut` runs them; the rest part by part. + let first = lists.iter().position(|&l| crate::list::cut_list(l)).unwrap_or(lists.len()); + #[cfg(feature = "diagnostics")] + crate::capture::op(queue, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {} lists {named:?} to the line (the first {first} in one piece)", + super::queue(this).kind + ) + }); + let mut jobs: Vec = Vec::new(); + if first > 0 { + let (taken, order) = crate::list::detach(&lists[..first]); + jobs.push(Job::Run(queue, taken, order)); + } + if first < lists.len() { + for (waits, taken, order) in crate::list::detach_parts(&lists[first..]) { + jobs.extend(waits.into_iter().map(Job::Value)); + jobs.push(Job::Run(queue, taken, order)); + } + } + let runs = jobs.iter().filter(|j| j.runs()).count() as u64; + let before = QUEUED.fetch_add(runs, Relaxed); + STATS[RUNS].fetch_add(runs, Relaxed); + STATS[DEPTH].fetch_add(before, Relaxed); + STATS[DEEPEST].fetch_max(before + runs, Relaxed); + LANE.push(queue, jobs); + if before + runs > runs_most() as u64 { + let began = Instant::now(); + LANE.wait_runs(runs_most()); + STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + } +} + +/// A signal of queue `this`: behind what it has in the line; if that is +/// nothing, behind the flights in the air, or now. +pub(super) fn signal(this: This, fence: This, value: u64) { + let fence = fence as usize; + LANE.push_behind(this as usize, false, Job::Signal(fence, value), || { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + }); +} + +/// Queue `this` waits for `fence`: nothing if it has nothing in the line and +/// the fence is there already. +pub(super) fn wait(this: This, fence: This, value: u64) { + let always = crate::fence::completed(fence) < value; + LANE.push_behind(this as usize, always, Job::Wait(fence as usize, value), || {}); +} + +/// A present on queue `this` of `texture`, in the state the lists recorded so +/// far leave it in. +pub(super) fn present(this: This, texture: Option<(std::sync::Arc, u32)>, shown: super::Shown) { + QUEUED.fetch_add(1, Relaxed); + STATS[PRESENTS].fetch_add(1, Relaxed); + LANE.push(this as usize, [Job::Present(texture, shown)]); + let began = Instant::now(); + LANE.wait_presents(frames_most()); + STATS[AT_PRESENT].fetch_add(began.elapsed().as_micros() as u64, Relaxed); +} + +/// For the frame-rate line. +pub(super) fn line(frames: f64) { + let s: Vec = STATS.iter().map(|s| s.swap(0, Relaxed) as f64).collect(); + let ms = |i: usize| s[i] / 1000.0 / frames; + tracing::info!( + "submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \ + when one was added (at most {:.0}); that thread worked {:.1} ms; threads of the title waited {:.1} ms for room in the \ + line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}", + s[RUNS] / frames, + s[PRESENTS] / frames, + s[DEPTH] / s[RUNS].max(1.0), + s[DEEPEST], + ms(BUSY), + ms(ROOM), + ms(AT_PRESENT), + ms(DRAINING), + s[DRAINS] / frames, + s[FORCED] / frames + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + type Log = Arc>>; + + /// A job of a test: what it stands at, and what it does. + enum T { + /// Stands until the fence has the value. + Wait(usize, u64), + Run(&'static str, Log), + /// Runs once the gate is open: a submission that takes long. + Slow(&'static str, Log, Arc<(Mutex, Condvar)>), + Signal(usize, u64, Log), + Present(&'static str, Log), + } + + impl Work for T { + type Ask = (usize, u64); + fn ask(&self) -> Option<(usize, u64)> { + match self { + &T::Wait(fence, value) => Some((fence, value)), + _ => None, + } + } + fn met(ask: &(usize, u64)) -> bool { + crate::fence::completed(ask.0 as This) >= ask.1 + } + fn shows(&self) -> bool { + matches!(self, T::Present(..)) + } + fn runs(&self) -> bool { + matches!(self, T::Run(..) | T::Slow(..)) + } + fn go(self, forced: bool) { + match self { + T::Wait(..) => { + if forced { + FORCED_HERE.with(|f| f.set(f.get() + 1)); + } + } + T::Run(name, log) | T::Present(name, log) => log.lock().unwrap().push(name.into()), + T::Slow(name, log, gate) => { + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + log.lock().unwrap().push(name.into()); + } + T::Signal(fence, value, log) => { + log.lock().unwrap().push(format!("signal {value}")); + crate::fence::set(fence as This, value); + } + } + } + } + + thread_local! { + static FORCED_HERE: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + fn fence() -> usize { + let mut f = std::ptr::null(); + assert_eq!(crate::fence::create(std::ptr::null(), 0, 0, &crate::fence::FENCE_IIDS[0], &mut f), super::super::S_OK); + f as usize + } + + fn value(f: usize) -> u64 { + crate::fence::completed(f as This) + } + + fn look(lane: &Lane) { + let limit = lane.lock().next; + lane.look(limit); + } + + /// A queue's order is kept, a wait for another queue's signal holds only + /// what is behind it on its own queue, and the oldest goes first. + #[test] + fn queues_keep_their_order_and_wait_for_each_others_fences() { + let lane = Lane::new(); + let log: Log = Default::default(); + let f = fence(); + let run = |name| T::Run(name, log.clone()); + // The compute queue waits for what the graphics queue signals later. + lane.push(2, [T::Wait(f, 1), run("compute")]); + lane.push(1, [run("draw 1")]); + lane.push_behind(1, false, T::Signal(f, 1, log.clone()), || panic!("the queue is not empty")); + lane.push(1, [run("draw 2")]); + look(&lane); + assert_eq!(*log.lock().unwrap(), ["draw 1", "signal 1", "compute", "draw 2"]); + assert_eq!(value(f), 1); + // Nothing in the line: a signal is at once. + let mut done = false; + lane.push_behind(1, false, T::Signal(f, 2, log.clone()), || done = true); + assert!(done); + } + + /// A wait that nothing meets holds its queue until a present, which + /// comes behind everything given before it and before what comes after. + #[test] + fn a_present_goes_behind_everything_before_it_met_or_not() { + let lane = Lane::new(); + let log: Log = Default::default(); + let f = fence(); + let run = |name| T::Run(name, log.clone()); + lane.push(2, [T::Wait(f, 9), run("held")]); + lane.push(1, [run("draw")]); + look(&lane); + assert_eq!(*log.lock().unwrap(), ["draw"], "the wait holds its queue and no other"); + lane.push(1, [T::Present("present", log.clone())]); + lane.push(1, [run("next frame")]); + lane.push(2, [T::Wait(f, 10), run("held again")]); + look(&lane); + assert_eq!(*log.lock().unwrap(), ["draw", "held", "present", "next frame"]); + assert_eq!(FORCED_HERE.get(), 1); + // The second wait is met by a signal of the CPU. + crate::fence::set(f as This, 10); + look(&lane); + assert_eq!(log.lock().unwrap().last().unwrap(), "held again"); + assert_eq!(FORCED_HERE.get(), 1); + let state = lane.lock(); + assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0)); + } + + /// With the thread: a fence behind a submission is not reached before the + /// submission has been done, presents hold the title back a frame later, + /// and a drain comes back when everything was done. + #[test] + fn the_title_goes_on_and_is_told_in_order() { + let lane: &'static Lane = Box::leak(Box::new(Lane::new())); + std::thread::spawn(|| lane.serve()); + let log: Log = Default::default(); + let f = fence(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + lane.push(1, [T::Slow("slow", log.clone(), gate.clone())]); + lane.push_behind(1, false, T::Signal(f, 1, log.clone()), || panic!("behind the submission")); + lane.push(1, [T::Present("present 1", log.clone())]); + // One present may be in the line: this returns with it there. + lane.wait_presents(1); + assert_eq!(value(f), 0); + assert!(log.lock().unwrap().is_empty()); + // A fence behind a submission being done (no longer in the line). + while lane.lock().running.is_none() { + std::thread::yield_now(); + } + lane.push(1, [T::Run("second", log.clone())]); + lane.push(1, [T::Present("present 2", log.clone())]); + let opener = { + let gate = gate.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + }) + }; + lane.wait_presents(1); + assert!(value(f) == 1, "the first frame was done"); + lane.drain(); + assert_eq!(*log.lock().unwrap(), ["slow", "signal 1", "present 1", "second", "present 2"]); + opener.join().unwrap(); + // A wait the CPU meets without telling anybody; a drain does not + // stand at it. + lane.push(1, [T::Wait(f, 5), T::Run("after the wait", log.clone())]); + lane.drain(); + assert_eq!(log.lock().unwrap().len(), 5); + lane.wait_runs(0); + crate::fence::set(f as This, 5); + while log.lock().unwrap().len() < 6 { + std::thread::yield_now(); + } + } +}