From 3f6ba0116fd1bce95f78e66b5ad00558768a0501 Mon Sep 17 00:00:00 2001 From: Ahyildiz <87144467+Ahyildiz@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:59:25 +0300 Subject: [PATCH 01/22] Textures: a prelude upload checks again at submission that the host has not written the texture (confetti faces) With VICTORY_PRELUDE_UPLOADS=1, upload_from checks host_written when a list is recorded, and the upload itself is decided at submission (PreludeUpload::finish_refresh), which did not check again. With lists recorded on several threads (VICTORY_THIN), a list that samples a texture can be recorded just before the list whose copy writes it (the title's decoration bake copying a character's baked skin into a 1024x1024 BC3 texture) and be submitted after it. Its prelude then copied the title's memory, which the title never filled (the console's GPU copy did), over the host's contents, and nothing uploads a host-written texture again, so it stayed: the diner bartender's face as coloured specks, or blue with lines, for the whole scene in about half the runs. finish_refresh now leaves the upload out when the texture is host-written, with a warning (first eight, then powers of two) naming its size and format. VICTORY_PRELUDE_RECHECK=0 restores the old behaviour. Checked with VICTORY_CAPTURE_FRAMES every 100 frames through the diner (Series S, DLSS off, RTX 5080): broken in about 5 of 10 runs before; clean in 5 of 5 runs after, where the check fired ~10 times per run (including 1024x1024 format 78 textures). Frame rate unchanged (24-25 fps there). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/texture.rs | 41 ++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 17955a108..6cd46736f 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -869,7 +869,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { staging.expected.store(there, Relaxed); } let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None }; - list.defer_prelude_upload(PreludeUpload { staging, copy, on_demand }); + list.defer_prelude_upload(PreludeUpload { staging, copy, on_demand, resource: resource as usize }); return; } // The host texture has the staging buffer's contents: only the check @@ -982,6 +982,21 @@ pub(crate) struct PreludeUpload { staging: Arc, pub(crate) copy: Arc, on_demand: Option, + /// The title's texture, for the check at submission that the host has + /// not written it since the list was recorded ([`host_written`]). + resource: usize, +} + +/// Whether a host copy or resolve has written the title's texture `resource`. +fn is_host_written(resource: usize) -> bool { + HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|set| set.contains(&resource)) +} + +/// `VICTORY_PRELUDE_RECHECK=0`: a prelude upload is not checked again at +/// submission for a host write made after its list was recorded (as before). +fn prelude_recheck() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PRELUDE_RECHECK").is_none_or(|v| v != "0")) } impl PreludeUpload { @@ -997,6 +1012,30 @@ impl PreludeUpload { /// levels on demand given memory, what the host copy holds). pub(crate) fn finish_refresh(&self) -> Option { use std::sync::atomic::Ordering::Relaxed; + // The host wrote the texture (a bake's copy into it) after this list + // was recorded, on another recording thread: its title memory holds + // what it held before, often another texture's bytes, and copying it + // over the host's contents left them there for good (no later list + // uploads a host-written texture): a character's baked skin drawn as + // coloured specks or a blue face for a whole scene, in about half the + // runs (the diner's bartender). + if prelude_recheck() && is_host_written(self.resource) { + static SKIPPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + // SAFETY: a live texture. + let desc = unsafe { self.copy.texture.GetDesc() }; + tracing::warn!( + n, + resource = format_args!("{:#x}", self.resource), + width = desc.Width, + height = desc.Height, + format = desc.Format.0, + "prelude upload left out: the host wrote the texture after the list that samples it was recorded" + ); + } + return None; + } let Some(first_upload) = claim_upload(&self.staging.uploaded, &self.staging.dirty) else { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexSkipped, 1); From 847cc36537923eb76d4e9c63535a68829a2f1ee1 Mon Sep 17 00:00:00 2001 From: VI Personal Date: Fri, 27 Nov 2026 20:09:19 +0100 Subject: [PATCH 02/22] Launcher: texture catch-up, 64 ms passes, no room held for targets, 92 % of the card's budget without frame generation scripts/play-foxhound.ps1: VICTORY_TEXTURE_CATCHUP=1, VICTORY_TEXTURE_STAGE_MS=64 (16), VICTORY_EARLY_TEXTURES_MS=32 (12), VICTORY_CARD_ROOM_FOR_TARGETS_MB=0 (3,072), and VICTORY_TEXTURE_ROOM_PERCENT=92 where frame generation has not set its own 80 / 86. Measured outdoors on an RTX 5080 (16 GB), Series X profile, 1440p, DLSS Quality, no frame generation: reviewed captures with low mips 0 of 29 (7 of 18 before), the texture queue at most 990 slots due (4,272), frames over 150 ms in the world 16 (66). Not measured on smaller cards or with frame generation ready. --- scripts/play-foxhound.ps1 | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1 index 47dd030b8..39b2e8b1c 100644 --- a/scripts/play-foxhound.ps1 +++ b/scripts/play-foxhound.ps1 @@ -78,9 +78,13 @@ $settings = @{ VICTORY_WC_NO_BACK = '1'; VICTORY_WC_NO_BACK_MIN_KB = '1024' # The title's page-mapping copies kept without Windows views (no cutscene freezes at scene cuts) VICTORY_SOFT_VIEWS = 'copies' - # Textures: pool with no blocks made ahead, 16 ms a pass, no catch-up, levels not on demand (sharp) - VICTORY_TEXTURE_POOL = '1'; VICTORY_RIPE_BLOCKS = '0'; VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_TEXTURE_CATCHUP = '0' - VICTORY_TEXTURE_STAGE_MS = '16'; VICTORY_LEVELS_ON_DEMAND = '0' + # Textures: pool with no blocks made ahead, levels not on demand (sharp). Catch-up on a backlog, 64 ms a pass + # (32 ms for the pass made before a shader asks), no room held back for targets and, further down, 92 % of the + # card's budget where no frame generation holds room back. Outdoors on a 16 GB card: no capture with low mips + # (7 of 18 before), the queue at most 990 deep (4,272), 4x fewer frames over 150 ms. + VICTORY_TEXTURE_POOL = '1'; VICTORY_RIPE_BLOCKS = '0'; VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_TEXTURE_CATCHUP = '1' + VICTORY_TEXTURE_STAGE_MS = '64'; VICTORY_EARLY_TEXTURES_MS = '32'; VICTORY_LEVELS_ON_DEMAND = '0' + VICTORY_CARD_ROOM_FOR_TARGETS_MB = '0' VICTORY_PRELUDE_UPLOADS = '1'; VICTORY_SHOW_NEW_LATER = '1'; VICTORY_POOL_SMALL = '0'; VICTORY_TABLED_REREAD = '1' VICTORY_QUEUE_HOST_TEXTURES = '0' # Descriptor heaps' records @@ -131,6 +135,9 @@ if ($FgType -ne 'dlss' -and ($FrameGen -or -not $NoFrameGenReady)) { if (-not $settings.VICTORY_FRAMEGEN_X) { $settings.VICTORY_FRAMEGEN_X = if ($FrameGen) { [string]$timesWanted } else { '0' } } if (-not $settings.VICTORY_TEXTURE_ROOM_PERCENT) { $settings.VICTORY_TEXTURE_ROOM_PERCENT = if ($FrameGen) { '80' } else { '86' } } } +# Where no frame generation holds room back above (-NoFrameGenReady without -FrameGen, for one): textures up to +# 92 % of the card's budget, as in the runs the texture settings were measured in. +if (-not $settings.VICTORY_TEXTURE_ROOM_PERCENT) { $settings.VICTORY_TEXTURE_ROOM_PERCENT = '92' } if ($fpsWanted -gt 0) { $settings.VICTORY_FRAME_INTERVAL_US = [string][int][math]::Round(1000000 / $fpsWanted) } foreach ($k in $menu.Keys) { if ($k -like 'VICTORY_MENU_*') { continue } From 48ff43c458d0659698fcb62d51f1d5a7d7727bdc Mon Sep 17 00:00:00 2001 From: mikey Date: Fri, 27 Nov 2026 15:40:22 -0500 Subject: [PATCH 03/22] fix(gpu): check moved-texture bytes before keeping old slot view (VICTORY_KEEP_SHOWN=checked) --- crates/victory-gpu/src/descriptor/host.rs | 121 +++++++++++++++++++--- 1 file changed, 109 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f2aad9792..714fd0509 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2821,10 +2821,7 @@ impl HostHeap { // (As `mirror`.) let stale = self.note_buffer(index, Some(&view), true); let old = view_at(shown as u32, (shown >> 32) as u32); - let kept = old.is_some_and(|old| match kin(&old, &view) { - Kin::Same => true, - kin => kin.kept(keep_shown()), - }); + let kept = old.is_some_and(|old| kept_meanwhile(&old, &view)); if shown == 0 || !kept { #[cfg(feature = "diagnostics")] note_before(index, shown, "neutral"); @@ -3958,7 +3955,7 @@ impl HostHeap { // ([`keep_shown`]): black, then grey for a frame or two is // what popped. if is_texture_view(&old) { - let kept = kin.kept(keep_shown()); + let kept = kept_meanwhile(&old, &view); rewritten(kin, kept); if kept { drop(held); @@ -3986,10 +3983,7 @@ impl HostHeap { return Some(view); } let old = view_at(shown as u32, (shown >> 32) as u32); - let kept = old.is_some_and(|old| match kin(&old, &view) { - Kin::Same => true, - kin => kin.kept(keep_shown()), - }); + let kept = old.is_some_and(|old| kept_meanwhile(&old, &view)); if shown == 0 || !kept { #[cfg(feature = "diagnostics")] note_before(index, shown, "neutral, new texture"); @@ -5180,7 +5174,9 @@ fn kin(old: &View, new: &View) -> Kin { /// showing the one it shows until the new one is made and its upload has run /// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral /// texture; 1: one of the same kind in another place or size; 2: any of the -/// same dimension. +/// same dimension; `checked`: as 1, except that a texture of the same +/// description placed elsewhere ([`Kin::Moved`]) is kept only when both +/// memories begin and end with the same 4 KiB. fn keep_shown() -> u8 { #[cfg(feature = "diagnostics")] if let Some(on) = crate::ab::pick("VICTORY_KEEP_SHOWN") { @@ -5190,6 +5186,69 @@ fn keep_shown() -> u8 { *KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1)) } +/// `VICTORY_KEEP_SHOWN=checked`: as 1, except that a slot written with a +/// texture of the same description placed elsewhere ([`Kin::Moved`]) goes on +/// showing the old one only where both memories begin and end with the same +/// bytes, i.e. the title moved the texture. Otherwise it shows the neutral +/// texture until the new one's upload has run. +/// +/// Why: "the same kind elsewhere" also matches a streamer reusing a slot for +/// a different texture of the same size and format (e.g. an albedo where a +/// mask or another character's map was), which renders rainbow-noise texels on +/// the surface until the upload lands. +fn keep_checked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").is_ok_and(|v| v.trim() == "checked")) +} + +/// Since the start, under `VICTORY_KEEP_SHOWN=checked`: `[0]` moved slots +/// whose memories began and ended alike (kept), `[1]` moved slots whose +/// memories differed or were unreadable (shown neutral). +static CHECKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether `old` stays in a slot rewritten with `new` until `new`'s upload +/// runs ([`keep_shown`], [`keep_checked`]). +fn kept_meanwhile(old: &View, new: &View) -> bool { + match kin(old, new) { + Kin::Same => true, + Kin::Moved if keep_checked() => { + let same = moved_whole(old, new); + CHECKED[usize::from(!same)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + same + } + kin => kin.kept(keep_shown()), + } +} + +/// Whether the memories of two placed texture views of one description begin +/// and end with the same bytes (4 KiB each end; title memory read as the +/// texture pass reads it). False where either cannot be read. +fn moved_whole(old: &View, new: &View) -> bool { + let (View::Placed(false, resource, from), View::Placed(false, _, to)) = (old, new) else { + return false; + }; + let at = |d: &[u32]| u64::from(d[10]) | u64::from(d[11]) << 32; + let Some(bytes) = crate::resource::placed_bytes(resource) else { + return false; + }; + same_ends(at(from), at(to), bytes, |at, out| crate::host::read_into(at as *const u8, out)) +} + +/// Whether `[a, a + bytes)` and `[b, b + bytes)` hold the same first and last +/// 4 KiB (all of them under 8 KiB), read by `read` (false: unreadable). +fn same_ends(a: u64, b: u64, bytes: u64, read: impl Fn(u64, &mut [u8]) -> bool) -> bool { + const END: u64 = 4096; + if a == 0 || b == 0 || bytes == 0 { + return false; + } + let ends = if bytes <= 2 * END { vec![(0, bytes)] } else { vec![(0, END), (bytes - END, END)] }; + let (mut x, mut y) = (vec![0u8; END as usize * 2], vec![0u8; END as usize * 2]); + ends.into_iter().all(|(offset, len)| { + let len = len as usize; + read(a + offset, &mut x[..len]) && read(b + offset, &mut y[..len]) && x[..len] == y[..len] + }) +} + /// Slots that showed a texture and were written with a view of another, /// since the start, by [`Kin`] (moved, sized, other, none), and those of /// them that kept what they showed. @@ -5208,12 +5267,14 @@ fn rewritten(kin: Kin, kept: bool) { let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum(); if n.is_multiple_of(5000) { tracing::info!( - "slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)", + "slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN); moved ones checked: {} with the same bytes kept, {} with other bytes shown neutral (VICTORY_KEEP_SHOWN=checked)", REWRITTEN[0].load(Relaxed), REWRITTEN[1].load(Relaxed), REWRITTEN[2].load(Relaxed), REWRITTEN[3].load(Relaxed), - REWRITTEN[4].load(Relaxed) + REWRITTEN[4].load(Relaxed), + CHECKED[0].load(Relaxed), + CHECKED[1].load(Relaxed) ); } } @@ -7031,4 +7092,40 @@ mod bake_flip_tests { drop(cb2); assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry"); } + + /// `VICTORY_KEEP_SHOWN=checked`: a texture of the same description elsewhere stands for the + /// new one only where both memories begin and end alike (a move), not where a streamer + /// gave the slot another texture of that size and format, nor where a memory is unreadable. + #[test] + fn a_moved_texture_is_kept_only_with_the_same_ends() { + let memory: Vec = (0..64 * 1024u32).map(|i| (i * 31 + i / 4096) as u8).collect(); + let mut moved = memory.clone(); + let mut other = memory.clone(); + // (The middle of a move may still differ: only the ends are compared.) + moved[20_000] ^= 0xff; + other[64 * 1024 - 1] ^= 1; + let all = [memory.as_slice(), moved.as_slice(), other.as_slice()]; + let base = |i: usize| (i as u64 + 1) << 32; + let read = |at: u64, out: &mut [u8]| { + let Some(bytes) = all.get(((at >> 32) as usize).wrapping_sub(1)) else { + return false; + }; + let offset = (at & 0xffff_ffff) as usize; + match bytes.get(offset..offset + out.len()) { + Some(src) => { + out.copy_from_slice(src); + true + } + None => false, + } + }; + let len = memory.len() as u64; + assert!(super::same_ends(base(0), base(1), len, read)); + assert!(!super::same_ends(base(0), base(2), len, read)); + // Unreadable (no such memory) or no address: not kept. + assert!(!super::same_ends(base(0), base(7), len, read)); + assert!(!super::same_ends(0, base(1), len, read)); + // Under 8 KiB: compared whole. + assert!(super::same_ends(base(0), base(1), 6000, read)); + } } From 3a9f195b8f10820f336cb6ede29ecc9d4f75f49f Mon Sep 17 00:00:00 2001 From: "Manley.B" Date: Sat, 28 Nov 2026 14:52:44 +1100 Subject: [PATCH 04/22] Pipelines: the heads' blend-shape map is made when its pipeline is created The title dispatches the compute program that builds the heads' blend-shape map (61e54e90adccaf6a) once. When its pipeline was still being made at that dispatch, the dispatch was dropped and the faces were drawn without their skin: eyes and teeth floating, as #586 reports on an RTX 3070. On an RTX 4090 the pipeline was made 29.8 s after its first bind (TaynanGT/Vice-Tay#372). It joins the confirmed first-scene producers (scene_input): started when the title creates the pipeline, first in the workers' queue, and its dispatch waits with the screen passes' budget (VICTORY_SCREEN_WAIT_MS, 10 s), not the ordinary one. Started at creation, Vice-Tay found it ready 48 s before its first bind. The finding is TaynanGT's (Vice-Tay#372, after avatarmanz/VIctory-7900XTX#166), whose change reworks the pipeline queue for it; this tree's scene_input list already does what it needs. Test the_head_blend_shape_map_is_made_at_creation. --- crates/victory-gpu/src/pipeline/make.rs | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 226f47843..f85f7da86 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -132,6 +132,13 @@ fn left_out(shaders: &[Arc]) -> Option<&'static str> { /// Confirmed first-scene producers. Prepare these at creation even on a cold /// launch so cutscene lighting, tiling, and bakes never miss their first frame. +/// +/// `61e54e90adccaf6a` is the compute program that builds the heads' blend-shape +/// map, which the title dispatches once: a dispatch dropped while its pipeline +/// was still being made left the faces without their skin, eyes and teeth +/// floating (the pipeline was made 29.8 s after its first bind on an RTX 4090, +/// TaynanGT/Vice-Tay#372; avatarmanz/VIctory-7900XTX#166). Made at creation it +/// was ready 48 s before that bind there. fn scene_input(shaders: &[Arc]) -> bool { shaders.iter().any(|s| { matches!( @@ -142,10 +149,14 @@ fn scene_input(shaders: &[Arc]) -> bool { | "ebe4e53f031f5249" | "2cc4c197ee29e291" | "369cbe906ea72764" + | HEAD_BLEND_SHAPE_MAP ) || crate::draw::BAKE_PIXEL_SHADERS.contains(&s.hash.as_str()) }) } +/// The compute program that builds the heads' blend-shape map ([`scene_input`]). +const HEAD_BLEND_SHAPE_MAP: &str = "61e54e90adccaf6a"; + // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input // elements point into its own names) is only read after creation. unsafe impl Send for Pending {} @@ -705,6 +716,28 @@ mod tests { ); } + /// The heads' blend-shape map is a first-scene producer: started when the + /// title creates its pipeline, first in the workers' queue, and its dispatch + /// waits with the passes over the screen's budget, not the ordinary one. + #[test] + fn the_head_blend_shape_map_is_made_at_creation() { + let shader = |hash: &str| { + Arc::new(Shader { + stage: "compute", + hash: hash.to_owned(), + container: Vec::new(), + #[cfg(windows)] + ambient: None, + #[cfg(windows)] + translated: OnceLock::new(), + }) + }; + let head = Pending::new(vec![shader(HEAD_BLEND_SHAPE_MAP)], None); + assert!(head.scene_input && head.screen, "made at creation, with the screen passes' budget"); + let other = Pending::new(vec![shader("0123456789abcdef")], None); + assert!(!other.scene_input && !other.screen); + } + #[test] fn pending_pipeline_is_recorded_for_the_next_launch() { let mut p = Pending::new(Vec::new(), None); From 59db7fa34b1e526becf3e05194a5d50a0425ed86 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:12:04 -0300 Subject: [PATCH 05/22] perf(gpu): scale texture pass time cap with VRAM and catch-up backlog --- apps/victory/src/play.rs | 4 +-- crates/victory-gpu/src/draw.rs | 55 ++++++++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index 141e932d6..054371ab4 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -84,8 +84,8 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_TEXTURE_POOL", "1"), ("VICTORY_RIPE_BLOCKS", "0"), ("VICTORY_TEXTURE_NO_WAIT", "1"), - ("VICTORY_TEXTURE_CATCHUP", "0"), - ("VICTORY_TEXTURE_STAGE_MS", "16"), + ("VICTORY_TEXTURE_CATCHUP", "1"), + ("VICTORY_TEXTURE_STAGE_MS", "24"), ("VICTORY_LEVELS_ON_DEMAND", "0"), ("VICTORY_PRELUDE_UPLOADS", "1"), ("VICTORY_SHOW_NEW_LATER", "1"), diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e3a7be8bf..e3f88cdfe 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3183,7 +3183,9 @@ impl State { // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); - let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + let pressured = crate::residency::pressured(); + let catchup_active = catchup && on_time >= 1024 && room && !pressured; + let (per_frame, span) = if catchup_active { (per_frame * 3, span * 3) } else { (per_frame, span) }; // A run made early (`State::early_textures`) has a budget of its // own: its bytes on top of what the frame has spent so far. // (Not `most`: that is the longest wait between looks, used below.) @@ -3200,7 +3202,7 @@ impl State { } else { crate::residency::prefetch_limit( bytes_at_most, - crate::residency::pressured(), + pressured, crate::residency::critical_commit(), crate::residency::limited_host_ram(), crate::texture::live_staging_bytes(), @@ -3211,11 +3213,13 @@ impl State { // before a bake) within `VICTORY_TEXSPK_PASS_MS` together // ([`texspk_pass_ms`]). let frame_pass = !required && !baking && sync.is_none(); + let vram_budget = memory.map(|[budget, ..]| budget); let span = match texspk_pass_ms() { Some(cap) if frame_pass => { if PASS_FRAME.swap(frame, Ordering::Relaxed) != frame { PASS_FRAME_NANOS.store(0, Ordering::Relaxed); } + let cap = texspk_cap_ms(cap, vram_budget, room, pressured, catchup_active); pass_span_left(span, cap, PASS_FRAME_NANOS.load(Ordering::Relaxed)) } _ => span, @@ -5956,6 +5960,36 @@ fn pass_span_left(span: std::time::Duration, cap_ms: u64, spent_ns: u64) -> std: span.min(cap.saturating_sub(std::time::Duration::from_nanos(spent_ns))) } +/// Effective per-frame texture pass cap in milliseconds from the configured +/// `VICTORY_TEXSPK_PASS_MS` baseline. +/// +/// Cards with > 12 GiB VRAM and free room get twice the baseline cap (capped +/// at 1000 ms) so larger staging budgets can drain, and an active catch-up +/// burst (`on_time >= 1024`, `room`, not pressured) triples the baseline cap +/// instead of being clamped back down to the calm-frame cap. Cards at +/// `<= 12 GiB`, full cards (`!room`), or pressured host RAM keep the baseline +/// cap. +fn texspk_cap_ms( + base_cap_ms: u64, + vram_budget: Option, + room: bool, + pressured: bool, + catchup_active: bool, +) -> u64 { + const GIB: u64 = 1 << 30; + if !room || pressured { + return base_cap_ms; + } + let scaled = if catchup_active { + base_cap_ms.saturating_mul(3) + } else if vram_budget.is_some_and(|b| b > 12 * GIB) { + base_cap_ms.saturating_mul(2) + } else { + base_cap_ms + }; + scaled.min(1000) +} + /// Per-frame texture staging byte budget scaled from the adapter's local VRAM /// budget (`None` keeps the 192 MiB 12 GiB baseline). fn staging_budget_per_frame(vram_budget: Option) -> u64 { @@ -5987,6 +6021,23 @@ mod tests { assert_eq!(pass_span_left(ms(16), 8, 9_000_000), Duration::ZERO); } + #[test] + fn texspk_cap_scales_with_vram_and_catchup() { + use super::texspk_cap_ms; + const GIB: u64 = 1 << 30; + // 12 GiB baseline keeps 8 ms when calm and scales to 24 ms on catchup. + assert_eq!(texspk_cap_ms(8, Some(12 * GIB), true, false, false), 8); + assert_eq!(texspk_cap_ms(8, Some(12 * GIB), true, false, true), 24); + // >12 GiB (e.g. 16 GiB RTX 5080) with room doubles calm cap to 16 ms, 24 ms on catchup. + assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, false, false), 16); + assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, false, true), 24); + // Full card or host-RAM pressure never expands the cap. + assert_eq!(texspk_cap_ms(8, Some(16 * GIB), false, false, true), 8); + assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, true, true), 8); + // Clamped at 1000 ms. + assert_eq!(texspk_cap_ms(600, Some(16 * GIB), true, false, true), 1000); + } + #[test] fn staging_budget_scales_with_vram_budget() { const GIB: u64 = 1 << 30; From e8f7d0211a4760fca99226769dfd8036e9d61743 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:02:39 -0300 Subject: [PATCH 06/22] perf(gpu): pre-filter nothing_new refreshes before ask_ahead and wide_each --- crates/victory-gpu/src/host.rs | 130 ++++++++++++++++++++++++--------- 1 file changed, 95 insertions(+), 35 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 66710676f..10573aa06 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8958,35 +8958,29 @@ impl Batch { let _flush = crate::timeline::span("refreshes of copies"); let started = std::time::Instant::now(); let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)); - // Those known to copy nothing are said so here, unless they are very - // many: then beside the others. - const FEW: usize = 256; + // Filter out refreshes known to copy nothing before `ask_ahead` and + // `wide_each`, even when there are many (> FEW), so no-ops never + // trigger `ask_ahead` or worker scheduling overhead. let mut spans = spans; - let many = spans.len() > FEW; - if !many { - let all = spans.len(); - spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); - FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); - } + let dropped = Self::filter_nothing_new(&mut spans); + FLUSHES[2].fetch_add(dropped as u64, Ordering::Relaxed); let ahead = spans.len() > 1; if ahead { let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); crate::watch::ask_ahead(&ranges); } FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); - crate::shadow::wide_each(spans.len() + due.len(), move |i| { - // The textures first: they are the longer pieces. - let Some(i) = i.checked_sub(due.len()) else { - due[i].refresh(); - return; - }; - let (shadow, from, to) = &spans[i]; - if many && shadow.nothing_new(*from, *to - *from) { - FLUSHES[2].fetch_add(1, Ordering::Relaxed); - return; - } - Self::update(shadow, *from, *to); - }); + if !spans.is_empty() || !due.is_empty() { + crate::shadow::wide_each(spans.len() + due.len(), move |i| { + // The textures first: they are the longer pieces. + let Some(i) = i.checked_sub(due.len()) else { + due[i].refresh(); + return; + }; + let (shadow, from, to) = &spans[i]; + Self::update(shadow, *from, *to); + }); + } if ahead { crate::watch::ask_ahead_done(); } @@ -9098,19 +9092,54 @@ impl Batch { FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); } - fn flush_all(&mut self) { - // Most of a flush's copies are as they were: they are told so here, - // from what the submission's asking found, before anything is asked - // and any thread woken. (Thousands of them, the heap's buffer views - // once a frame: on the threads, below.) + /// Drops refreshes known to copy nothing (`Shadow::nothing_new`) before + /// `ask_ahead` and `wide_each`, returning how many were dropped. + fn filter_nothing_new(items: &mut Vec<(std::sync::Arc, usize, usize)>) -> usize { const FEW: usize = 256; + const CHUNK: usize = 64; + let all = items.len(); + if all <= FEW { + items.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + return all - items.len(); + } + let taken = std::sync::Arc::new(std::mem::take(items)); + let keep = std::sync::Arc::new( + (0..all) + .map(|_| std::sync::atomic::AtomicBool::new(false)) + .collect::>(), + ); + let (taken_ref, keep_ref) = (taken.clone(), keep.clone()); + crate::shadow::wide_each(all.div_ceil(CHUNK), move |chunk| { + let start = chunk * CHUNK; + let end = (start + CHUNK).min(taken_ref.len()); + for idx in start..end { + let (shadow, from, to) = &taken_ref[idx]; + if !shadow.nothing_new(*from, *to - *from) { + keep_ref[idx].store(true, Ordering::Relaxed); + } + } + }); + let taken = std::sync::Arc::try_unwrap(taken).unwrap_or_else(|_| unreachable!()); + *items = taken + .into_iter() + .zip(keep.iter()) + .filter_map(|(item, k)| k.load(Ordering::Relaxed).then_some(item)) + .collect(); + all - items.len() + } + + fn flush_all(&mut self) { + // Most of a flush's copies are as they were: filter them out here + // (in parallel chunks when > FEW) before `ask_ahead` or worker dispatch. let light = crate::watch::light(); - if light && self.refreshes.len() <= FEW { + if light { let started = std::time::Instant::now(); - let all = self.refreshes.len(); - self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + let dropped = Self::filter_nothing_new(&mut self.refreshes); PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); + FLUSHES[2].fetch_add(dropped as u64, Ordering::Relaxed); + } + if self.refreshes.is_empty() { + return; } // One write-watch asking for the copies that lie close together, // not one per copy. @@ -9138,10 +9167,6 @@ impl Batch { let refreshes = std::mem::take(&mut self.refreshes); crate::shadow::wide_each(refreshes.len(), move |i| { let (shadow, from, to) = &refreshes[i]; - if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { - FLUSHES[2].fetch_add(1, Ordering::Relaxed); - return; - } Self::update(shadow, *from, *to); }); } else { @@ -11867,6 +11892,41 @@ mod refresh_tests { } } + /// Even when a flush has more than `FEW` (256) refreshes, `filter_nothing_new` + /// drops the unchanged ones up front so `ask_ahead` and `wide_each` only see + /// the ranges that actually changed. + #[test] + fn many_unchanged_refreshes_are_filtered_before_dispatch() { + const COUNT: usize = 300; + let region = title(2 * PAGE, false); + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, 2 * PAGE) }; + let data = memory(2 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (2 * PAGE) as u64, false); + // Take the first page once so `nothing_new` is true for it. + copy.update(region, PAGE); + let mut items: Vec<(std::sync::Arc, usize, usize)> = (0..COUNT) + .map(|_| (copy.clone(), region, region + PAGE)) + .collect(); + // Add two ranges on the second page (never taken -> `nothing_new` is false). + items.push((copy.clone(), region + PAGE, region + 2 * PAGE)); + items.push((copy.clone(), region + PAGE + 64, region + PAGE + 128)); + // Retry `ask_once` in case another parallel test called `ask_once_end`. + let mut dropped = 0; + for _ in 0..100 { + crate::watch::ask_once(&[(region, region + 2 * PAGE)]); + let mut probe = items.clone(); + dropped = Batch::filter_nothing_new(&mut probe); + crate::watch::ask_once_end(); + if dropped == COUNT { + items = probe; + break; + } + } + assert_eq!(dropped, COUNT); + assert_eq!(items.len(), 2); + } + /// Of a copy in the card's memory only the dwords title memory changed go /// up, and none beside them, not even between two in 64 bytes; a page /// never taken goes up whole. From a6c917425bdb7739ad85a6277c57531ac4033301 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:05:39 -0300 Subject: [PATCH 07/22] perf(gpu): skip detiling zeroed mips and expose texture hash cadence switches --- crates/victory-gpu/src/texture.rs | 112 +++++++++++++++++++++++++++--- 1 file changed, 102 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 301b0455f..26ef7ac74 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -113,8 +113,30 @@ struct Last { } /// Frames a guarded texture is hashed at every check from its first check, -/// and after the hash found a change the guard did not see. -const HOT_FRAMES: u64 = 64; +/// and after the hash found a change the guard did not see +/// (`VICTORY_TEXTURE_HOT_FRAMES`, default 64). +fn hot_frames() -> u64 { + static FRAMES: std::sync::OnceLock = std::sync::OnceLock::new(); + *FRAMES.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_HOT_FRAMES") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(64) + }) +} + +/// How often (in frames) a guarded texture is re-hashed even when the guard +/// saw no write (`VICTORY_TEXTURE_HASH_EVERY`, default 8; 0 disables blind +/// periodic re-hashing). +fn hash_every() -> u64 { + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_HASH_EVERY") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(8) + }) +} /// Whether a guarded texture whose memory the hash found changed although /// the guard saw no write is hashed at every check for a while @@ -1481,19 +1503,21 @@ impl Staging { && *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) { - const HASH_EVERY: u64 = 8; + let every = hash_every(); let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); last.asked = now; let frame = crate::frame::current(); - let turn = frame - .wrapping_add((start >> 16) as u64) - .is_multiple_of(HASH_EVERY); + let turn = every != 0 + && frame + .wrapping_add((start >> 16) as u64) + .is_multiple_of(every); // A texture starts hot: one written that way from its first // frames on changes before the hash has ever caught it. + let hot_len = hot_frames(); if last.hot_until == 0 { - last.hot_until = frame + HOT_FRAMES; + last.hot_until = frame + hot_len; } - let hot = hot_textures() && frame < last.hot_until; + let hot = hot_len != 0 && hot_textures() && frame < last.hot_until; if !exact && unwritten && !turn && !hot { return 0; } @@ -1501,8 +1525,9 @@ impl Staging { } // A change the guard did not see: hashed at every check for a while. let found_blind = |last: &mut Last| { - if blind && hot_textures() { - last.hot_until = crate::frame::current() + HOT_FRAMES; + let hot_len = hot_frames(); + if blind && hot_len != 0 && hot_textures() { + last.hot_until = crate::frame::current() + hot_len; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHot, 1); } @@ -1752,6 +1777,15 @@ impl Staging { linear.fill(0); continue; } + if let Some((from, to)) = mip_tiled_range(&self.layout, mip, slice) + && to <= tiled.len() + && is_all_zero(&tiled[from..to]) + { + // Unmapped or zeroed mip (e.g. streamed texture with mip 0 not + // resident yet): detiling zeros always yields zeros. + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) @@ -1763,6 +1797,38 @@ impl Staging { } } +/// Byte range in `tiled` for `(mip, slice)` when it is a contiguous individual +/// mip (non-3D and before `first_tail_mip`). +fn mip_tiled_range(layout: &victory_formats::texture::Layout, mip: u32, slice: u32) -> Option<(usize, usize)> { + if layout.desc.dimension == victory_formats::texture::Dimension::Tex3d + || mip >= layout.first_tail_mip + || slice >= layout.slices + { + return None; + } + let m = layout.mips.get(mip as usize)?; + let end = if mip == 0 { + layout.slice_size + } else { + layout.mips.get(mip as usize - 1)?.offset + }; + if m.offset >= end { + return None; + } + let base = slice as u64 * layout.slice_size; + let from = usize::try_from(base.checked_add(m.offset)?).ok()?; + let to = usize::try_from(base.checked_add(end)?).ok()?; + Some((from, to)) +} + +fn is_all_zero(bytes: &[u8]) -> bool { + // SAFETY: `align_to::` is safe for `u8` slices; `u128` has no invalid bit patterns. + let (head, body, tail) = unsafe { bytes.align_to::() }; + head.iter().all(|&b| b == 0) + && body.iter().all(|&w| w == 0) + && tail.iter().all(|&b| b == 0) +} + /// Lets go of a title texture's staging buffer (lists that recorded an /// upload from it hold it until they have run); the next upload makes one /// anew. @@ -2362,6 +2428,32 @@ mod title_memory_tests { } } } + + #[test] + fn zero_mip_range_is_detected_for_non_tail_mips() { + use victory_formats::texture::{Desc, Dimension, Layout, Swizzle}; + let desc = Desc { + dimension: Dimension::Tex2d, + width: 512, + height: 512, + depth: 1, + mips: 10, + samples: 1, + element_bytes: 16, + block: 4, + swizzle: Swizzle::LINEAR, + }; + let layout = Layout::new(&desc).expect("valid layout"); + let mut tiled = vec![0u8; layout.size as usize]; + let (from0, to0) = super::mip_tiled_range(&layout, 0, 0).expect("mip 0 range"); + assert!(super::is_all_zero(&tiled[from0..to0])); + tiled[from0 + 7] = 1; + assert!(!super::is_all_zero(&tiled[from0..to0])); + assert!(super::is_all_zero(&[0u8; 31])); + assert!(!super::is_all_zero(&[0, 0, 0, 1, 0, 0])); + assert_eq!(super::hash_every(), 8); + assert_eq!(super::hot_frames(), 64); + } } /// [`claim_upload`] (ported from Belobug/VIctory-Belobug-AMD 5d6bd84). From f6421868c8f480032ca88833f7b9a8b501a02f4f Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:08:10 -0300 Subject: [PATCH 08/22] perf(gpu): cache heap.handle per slot in draw pass and add VICTORY_DUE_FRESH_FIRST --- crates/victory-gpu/src/descriptor/host.rs | 59 ++++++++++++++++++----- crates/victory-gpu/src/draw.rs | 31 ++++++------ 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index d331dd46e..f324678c4 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1340,23 +1340,44 @@ impl Due { /// [`Due::order`], and beside it what [`TextureQueue::checked`] said of /// each when they were taken. fn ordered(self, max: usize) -> (Vec<(u32, u64)>, Vec>) { + static FRESH_FIRST: std::sync::OnceLock = std::sync::OnceLock::new(); + let fresh_first = *FRESH_FIRST.get_or_init(|| std::env::var_os("VICTORY_DUE_FRESH_FIRST").is_some_and(|v| v == "1")); + self.ordered_with(max, fresh_first) + } + + fn ordered_with(self, max: usize, fresh_first: bool) -> (Vec<(u32, u64)>, Vec>) { let Due { mut again, mut fresh } = self; // By the number of the write, counted over the run. again.sort_unstable_by_key(|e| std::cmp::Reverse(e.2)); fresh.sort_unstable_by_key(|e| std::cmp::Reverse(e.2)); - let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write, _)| (index, write)).collect(); - let mut known: Vec> = again.iter().map(|a| a.3).collect(); - let (mut new, mut old) = (0, fresh.len()); - while new < old && order.len() < max { - order.push((fresh[new].1, fresh[new].2)); - new += 1; - if new < old && order.len() < max { - old -= 1; - order.push((fresh[old].1, fresh[old].2)); + let mut order: Vec<(u32, u64)> = Vec::with_capacity(max.min(again.len() + fresh.len())); + let mut known: Vec> = Vec::with_capacity(max.min(again.len() + fresh.len())); + let push_fresh = |order: &mut Vec<(u32, u64)>, known: &mut Vec>| { + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push((fresh[new].1, fresh[new].2)); + known.push(None); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push((fresh[old].1, fresh[old].2)); + known.push(None); + } } + }; + let push_again = |order: &mut Vec<(u32, u64)>, known: &mut Vec>| { + for &(_, index, write, checked) in again.iter().take(max.saturating_sub(order.len())) { + order.push((index, write)); + known.push(checked); + } + }; + if fresh_first { + push_fresh(&mut order, &mut known); + push_again(&mut order, &mut known); + } else { + push_again(&mut order, &mut known); + push_fresh(&mut order, &mut known); } - order.truncate(max); - known.resize(order.len(), None); (order, known) } } @@ -6305,6 +6326,22 @@ mod tests { } } + #[test] + fn due_fresh_first_prevents_again_starvation() { + let mut due = Due::default(); + due.again.push((1, 100, 10, None)); + due.again.push((2, 101, 11, None)); + due.fresh.push((3, 200, 12)); + let (again_first, _) = Due { + again: due.again.clone(), + fresh: due.fresh.clone(), + } + .ordered_with(2, false); + assert_eq!(again_first, [(101, 11), (100, 10)]); + let (fresh_first, _) = due.ordered_with(2, true); + assert_eq!(fresh_first, [(200, 12), (101, 11)]); + } + /// Slots held back for lack of room on the card are not handed out /// until their frame, keep their place, are not counted as waiting /// for their memory, and all come back at once when the card has room; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e3f88cdfe..41fb16c43 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3317,8 +3317,9 @@ impl State { } let mut partly = None; let mut there = None; - // The view the slot holds now, read once for the looks below. - let held = rest(1, || heap.handle(index).and_then(crate::descriptor::view)); + // The view the slot holds now, read once for the whole slot turn. + let handle = rest(1, || heap.handle(index)); + let held = handle.and_then(crate::descriptor::view); if let Some(View::Placed(false, resource, desc)) = &held { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let first = crate::resource::first_mip(desc); @@ -3375,7 +3376,7 @@ impl State { // before. if !room { let has_its_texture = reupload_when_full() - && rest(1, || heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle))); + && handle.is_some_and(|handle| host.texture_slot_made_from(index, handle)); if !has_its_texture { refused += 1; outcome(slot_outcome::HELD); @@ -3415,17 +3416,17 @@ impl State { let shows_other = !baking && !sync_bake && crate::resource::held_only() - && rest(1, || heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle))); + && handle.is_some_and(|handle| host.texture_slot_shows_other(index, handle)); // A slot that shows nothing of it yet, or something else, shows it // when the upload has run too. let late = !shows_other && !baking && !sync_bake && crate::descriptor::host::show_after() - && rest(1, || heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle))); + && handle.is_some_and(|handle| !host.texture_slot_made_from(index, handle)); let (view, bake_key) = timed(6, || { if sync_bake { - match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) { + match handle.and_then(|handle| host.prepare_bake_slot(index, handle)) { Some((view, key)) => (Some(view), Some(key)), None => (None, None), } @@ -3434,12 +3435,12 @@ impl State { // again, the views' table was asked twice a slot). (held.clone(), None) } else { - (heap.handle(index).and_then(|handle| host.mirror(index, handle, true)), None) + (handle.and_then(|handle| host.mirror(index, handle, true)), None) } }); // (`nothing`: the slot has nothing to bring up to date.) let at_once = |nothing: bool| { - if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) { + if (late || bake_key.is_some()) && let Some(handle) = handle { HEAP_TEXTURE_NOTHING[3].fetch_add(u64::from(nothing), Ordering::Relaxed); shown(0, || { let _ = host.mirror(index, handle, true); @@ -3488,20 +3489,20 @@ impl State { if same { HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::SAME); - if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, handle) { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); } sync.publish.push((index, handle, key)); } else { - if shows_other && let Some(handle) = heap.handle(index) { + if shows_other && let Some(handle) = handle { shown(2, || { let _ = host.mirror(index, handle, true); }); } // Its bytes are in, or on the way there in a list before. if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { - if let Some(handle) = heap.handle(index) { + if let Some(handle) = handle { shown(1, || host.texture_slot_show_after(list, index, handle)); } } else { @@ -3532,7 +3533,7 @@ impl State { use crate::texture::ahead::Taken; let (Taken::New(job) | Taken::Known(job)) = ahead; rest(3, || { - if let Some(handle) = heap.handle(index) { + if let Some(handle) = handle { host.texture_slot_show_ahead(job, index, handle); } if let Taken::New(job) = ahead { @@ -3564,16 +3565,16 @@ impl State { served = false; break; } - if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, handle) { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); } sync.publish.push((index, handle, key)); } - if shows_other && let Some(handle) = heap.handle(index) { + if shows_other && let Some(handle) = handle { shown(2, || host.texture_slot_flip(list, index, handle)); } - if late && let Some(handle) = heap.handle(index) { + if late && let Some(handle) = handle { shown(1, || host.texture_slot_show_after(list, index, handle)); } #[cfg(feature = "diagnostics")] From 8653fc35c8522b858201c9e382130d5e35a08d1e Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:10:06 -0300 Subject: [PATCH 09/22] perf(gpu): combine copy_spans and refresh_front step walks --- crates/victory-gpu/src/host.rs | 99 ++++++++++++++++++---------------- 1 file changed, 53 insertions(+), 46 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 10573aa06..6ee9af474 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -6142,7 +6142,7 @@ impl Host { // One write-watch asking for everything the submission refreshes // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. if crate::watch::once() { - batch.copy_spans(runs); + batch.copy_spans(runs, refresh_front().then_some(&parts[..])); let Batch { spans, ranges, .. } = &mut batch; ranges.clear(); ranges.extend(spans.iter().filter(|s| s.0.asked_ahead()).map(|s| (s.1, s.2))); @@ -8539,6 +8539,8 @@ struct Batch { /// `ahead` holds everything the submission refreshes /// ([`Batch::refresh_front`]). front: bool, + /// `touches` and `due` were already gathered during [`Batch::copy_spans`]. + front_gathered: bool, /// Per copy the submission refreshes, the span of all its refreshes, in /// the order the copies first come ([`Batch::copy_spans`]); where each /// copy (by address) is in it. @@ -8794,6 +8796,7 @@ impl Batch { self.fills.clear(); self.ahead.clear(); self.front = false; + self.front_gathered = false; self.spans.clear(); self.spans_at.clear(); self.ranges.clear(); @@ -8805,35 +8808,59 @@ impl Batch { /// [`Batch::spans`]: the submission's one asking asks about those /// ([`crate::watch::ask_once`]), and behind flights those of copies /// shaders may be writing are looked at ([`Batch::stale_under_flights`]). - /// One walk over the steps for both, where there were two, each with a - /// table of its own. - fn copy_spans(&mut self, runs: &[&HostList]) { + /// When `parts` is `Some`, also gathers `touches` and `due` for + /// [`Batch::refresh_front`] in the same single walk. + fn copy_spans(&mut self, runs: &[&HostList], parts: Option<&[usize]>) { self.spans.clear(); self.spans_at.clear(); + if parts.is_some() { + self.touches.clear(); + self.due.clear(); + self.front_gathered = true; + } + let textures = parts.is_some() && wide_textures(); // (Most come several times on end.) let mut last = (0, 0); - for list in runs { + for (n, list) in runs.iter().enumerate() { + if let Some(parts) = parts + && parts.contains(&n) + { + self.touches.push(Touch::Part); + } for step in &list.deferred().copies { - let Step::Refresh(shadow, address, len) = step else { - continue; - }; - let (from, to) = (*address, *address + *len); - let key = std::sync::Arc::as_ptr(shadow) as usize; - let at = if last.0 == key && key != 0 { - last.1 - } else { - match self.spans_at.entry(key) { - std::collections::hash_map::Entry::Occupied(at) => *at.get(), - std::collections::hash_map::Entry::Vacant(place) => { - place.insert(self.spans.len()); - self.spans.push((shadow.clone(), from, to)); - self.spans.len() - 1 + match step { + Step::Refresh(shadow, address, len) => { + let (from, to) = (*address, *address + *len); + let key = std::sync::Arc::as_ptr(shadow) as usize; + if parts.is_some() { + self.touches.push(Touch::Refresh(key, from, to)); } + let at = if last.0 == key && key != 0 { + last.1 + } else { + match self.spans_at.entry(key) { + std::collections::hash_map::Entry::Occupied(at) => *at.get(), + std::collections::hash_map::Entry::Vacant(place) => { + place.insert(self.spans.len()); + self.spans.push((shadow.clone(), from, to)); + self.spans.len() - 1 + } + } + }; + last = (key, at); + let span = &mut self.spans[at]; + (span.1, span.2) = (span.1.min(from), span.2.max(to)); } - }; - last = (key, at); - let span = &mut self.spans[at]; - (span.1, span.2) = (span.1.min(from), span.2.max(to)); + Step::GpuWrite(shadow, ..) if parts.is_some() => { + self.touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)); + } + Step::Texture(staging) if textures => { + if self.texture_due(staging) { + self.due.push(staging.clone()); + } + } + _ => {} + } } } } @@ -8920,30 +8947,10 @@ impl Batch { fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) { // The copies refreshed, by address: as the submission's one asking // found them, or found here. - if self.spans.is_empty() { - self.copy_spans(runs); - } - let mut due = Vec::new(); - self.touches.clear(); - for (n, list) in runs.iter().enumerate() { - if parts.contains(&n) { - self.touches.push(Touch::Part); - } - for step in &list.deferred().copies { - match step { - Step::Refresh(shadow, at, len) => { - self.touches.push(Touch::Refresh(std::sync::Arc::as_ptr(shadow) as usize, *at, *at + *len)); - } - Step::GpuWrite(shadow, ..) => self.touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)), - Step::Texture(staging) if wide_textures() => { - if self.texture_due(staging) { - due.push(staging.clone()); - } - } - _ => {} - } - } + if !self.front_gathered { + self.copy_spans(runs, Some(parts)); } + let due = std::mem::take(&mut self.due); let found = front_spans(self.touches.drain(..)); let spans: Vec<_> = found .into_iter() From 90f051df93b15acfca228459eb2fead16078a376 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:44:10 -0300 Subject: [PATCH 10/22] fix(gpu): verify descriptor record key before host descriptor writes --- crates/victory-gpu/src/descriptor.rs | 8 +++++- crates/victory-gpu/src/descriptor/host.rs | 32 ++++++++++----------- crates/victory-gpu/src/draw.rs | 35 +++++++++++++++-------- 3 files changed, 45 insertions(+), 30 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 2176cbf60..8016c934b 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1704,6 +1704,11 @@ pub(crate) fn record_at(handle: u64) -> Option<[u32; 3]> { /// The view recorded at `handle`, if one is (and its resource is alive). pub(crate) fn view(handle: u64) -> Option { + view_with_key(handle).map(|(_, view)| view) +} + +/// The `(key, view)` recorded at `handle`, if one is (and its resource is alive). +pub(crate) fn view_with_key(handle: u64) -> Option<(u64, View)> { if handle == 0 { return None; } @@ -1712,7 +1717,8 @@ pub(crate) fn view(handle: u64) -> Option { if tag != VIEW_TAG { return None; } - view_at(i, generation) + let key = u64::from(generation) << 32 | u64::from(i); + view_at(i, generation).map(|view| (key, view)) } /// A description of `N` words, if the title passes one. diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f324678c4..c7d2fa826 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -576,7 +576,7 @@ pub(crate) fn flip_now() { pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// The key of the record at `handle`, a view's descriptor slot; 0: none. -fn record_key(handle: u64) -> u64 { +pub(crate) fn record_key(handle: u64) -> u64 { // SAFETY: the handle is a descriptor slot in title memory. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; if tag == VIEW_TAG { u64::from(generation) << 32 | u64::from(i) } else { 0 } @@ -2831,34 +2831,32 @@ impl HostHeap { /// until then it shows what it showed. (Made at once, the frames on the /// card read the new view before its levels were filled.) pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) { - self.flip(list, index, handle, None); + self.flip(list, index, handle, record_key(handle), None); } /// The same of a slot that shows nothing of the texture the record at /// `handle` views, or something else: until then it shows the neutral /// texture ([`show_after`]). pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { - if self.show_later(index, handle) { - self.flip(list, index, handle, Some(crate::frame::current())); + if let Some(key) = self.show_later(index, handle) { + self.flip(list, index, handle, key, Some(crate::frame::current())); } } /// What slot `index` shows until the texture the record at `handle` views - /// is shown. False: it shows it, or there is none. - fn show_later(&self, index: u32, handle: u64) -> bool { + /// is shown. `None`: it shows it, or there is none. + fn show_later(&self, index: u32, handle: u64) -> Option { use std::sync::atomic::Ordering::Relaxed; let key = record_key(handle); let view = view_at(key as u32, (key >> 32) as u32); let (true, Some(view)) = (key != 0, view) else { - return false; + return None; }; let stale = { let _made = self.made.lock(index); - let Some(shown) = self.made.get(index) else { - return false; - }; + let shown = self.made.get(index)?; if shown == key { - return false; + return None; } // (As `mirror`.) let stale = self.note_buffer(index, Some(&view), true); @@ -2881,16 +2879,16 @@ impl HostHeap { stale }; self.unmake_stale(index, stale); - true + Some(key) } /// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job` /// makes: shown when that has run. pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) { - if !self.show_later(index, handle) { + let Some(key) = self.show_later(index, handle) else { return; - } - let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + }; + let heap = std::ptr::from_ref(self) as usize; let late = Some(crate::frame::current()); job.then(move || { let flip = Flip { after: 0, heap, index, handle, key, late }; @@ -2917,9 +2915,9 @@ impl HostHeap { self.mirror(index, handle, true); } - fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option) { + fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, key: u64, late: Option) { use std::sync::atomic::Ordering::{Relaxed, Release}; - let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + let heap = std::ptr::from_ref(self) as usize; let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed); let origin = (std::ptr::from_ref(list) as usize, list.epoch()); { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 41fb16c43..01fcaa3e3 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3317,9 +3317,20 @@ impl State { } let mut partly = None; let mut there = None; - // The view the slot holds now, read once for the whole slot turn. + // The view the slot holds now, read once for the looks below. let handle = rest(1, || heap.handle(index)); - let held = handle.and_then(crate::descriptor::view); + let (held_key, held) = match handle.and_then(crate::descriptor::view_with_key) { + Some((key, view)) => (Some(key), Some(view)), + None => (None, None), + }; + // Re-read the handle and verify the slot still holds the same + // view record before any step that writes host descriptors, so a + // concurrent slot rewrite by the title cannot expose a new view + // using the previous view's upload. + let fresh_handle = || { + heap.handle(index) + .filter(|&h| held_key.is_none_or(|k| crate::descriptor::host::record_key(h) == k)) + }; if let Some(View::Placed(false, resource, desc)) = &held { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let first = crate::resource::first_mip(desc); @@ -3426,7 +3437,7 @@ impl State { && handle.is_some_and(|handle| !host.texture_slot_made_from(index, handle)); let (view, bake_key) = timed(6, || { if sync_bake { - match handle.and_then(|handle| host.prepare_bake_slot(index, handle)) { + match fresh_handle().and_then(|handle| host.prepare_bake_slot(index, handle)) { Some((view, key)) => (Some(view), Some(key)), None => (None, None), } @@ -3435,12 +3446,12 @@ impl State { // again, the views' table was asked twice a slot). (held.clone(), None) } else { - (handle.and_then(|handle| host.mirror(index, handle, true)), None) + (fresh_handle().and_then(|handle| host.mirror(index, handle, true)), None) } }); // (`nothing`: the slot has nothing to bring up to date.) let at_once = |nothing: bool| { - if (late || bake_key.is_some()) && let Some(handle) = handle { + if (late || bake_key.is_some()) && let Some(handle) = fresh_handle() { HEAP_TEXTURE_NOTHING[3].fetch_add(u64::from(nothing), Ordering::Relaxed); shown(0, || { let _ = host.mirror(index, handle, true); @@ -3489,20 +3500,20 @@ impl State { if same { HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::SAME); - if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, handle) { + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, fresh_handle()) { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); } sync.publish.push((index, handle, key)); } else { - if shows_other && let Some(handle) = handle { + if shows_other && let Some(handle) = fresh_handle() { shown(2, || { let _ = host.mirror(index, handle, true); }); } // Its bytes are in, or on the way there in a list before. if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { - if let Some(handle) = handle { + if let Some(handle) = fresh_handle() { shown(1, || host.texture_slot_show_after(list, index, handle)); } } else { @@ -3533,7 +3544,7 @@ impl State { use crate::texture::ahead::Taken; let (Taken::New(job) | Taken::Known(job)) = ahead; rest(3, || { - if let Some(handle) = handle { + if let Some(handle) = fresh_handle() { host.texture_slot_show_ahead(job, index, handle); } if let Taken::New(job) = ahead { @@ -3565,16 +3576,16 @@ impl State { served = false; break; } - if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, handle) { + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, fresh_handle()) { if let Some(copy) = crate::resource::host_copy(resource) { sync.keep.push(copy); } sync.publish.push((index, handle, key)); } - if shows_other && let Some(handle) = handle { + if shows_other && let Some(handle) = fresh_handle() { shown(2, || host.texture_slot_flip(list, index, handle)); } - if late && let Some(handle) = handle { + if late && let Some(handle) = fresh_handle() { shown(1, || host.texture_slot_show_after(list, index, handle)); } #[cfg(feature = "diagnostics")] From 5b463d75dc805a490c1248a554ca4a77504a1667 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:46:58 -0300 Subject: [PATCH 11/22] perf(gpu): prioritize fresh textures over rechecks and parallelize ahead staging refresh --- crates/victory-gpu/src/descriptor/host.rs | 21 +++++++++++++++------ crates/victory-gpu/src/draw.rs | 12 ++++++++---- crates/victory-gpu/src/texture/ahead.rs | 13 ++++++++++--- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index c7d2fa826..66caf5517 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1365,18 +1365,27 @@ impl Due { } } }; - let push_again = |order: &mut Vec<(u32, u64)>, known: &mut Vec>| { - for &(_, index, write, checked) in again.iter().take(max.saturating_sub(order.len())) { - order.push((index, write)); - known.push(checked); + let push_again = |order: &mut Vec<(u32, u64)>, known: &mut Vec>, recheck: Option| { + for &(_, index, write, checked) in &again { + if order.len() >= max { + break; + } + if recheck.is_none_or(|want| checked.is_some() == want) { + order.push((index, write)); + known.push(checked); + } } }; if fresh_first { push_fresh(&mut order, &mut known); - push_again(&mut order, &mut known); + push_again(&mut order, &mut known, None); } else { - push_again(&mut order, &mut known); + // Unuploaded retries (`later`/`partly`) first, then `fresh` + // never-uploaded slots, then already-uploaded `recheck` slots so + // thousands of `recheck` slots cannot starve `fresh` textures. + push_again(&mut order, &mut known, Some(false)); push_fresh(&mut order, &mut known); + push_again(&mut order, &mut known, Some(true)); } (order, known) } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 01fcaa3e3..9b954493e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3184,7 +3184,7 @@ impl State { static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); let pressured = crate::residency::pressured(); - let catchup_active = catchup && on_time >= 1024 && room && !pressured; + let catchup_active = catchup && on_time >= 256 && room && !pressured; let (per_frame, span) = if catchup_active { (per_frame * 3, span * 3) } else { (per_frame, span) }; // A run made early (`State::early_textures`) has a budget of its // own: its bytes on top of what the frame has spent so far. @@ -5993,7 +5993,11 @@ fn texspk_cap_ms( return base_cap_ms; } let scaled = if catchup_active { - base_cap_ms.saturating_mul(3) + if vram_budget.is_some_and(|b| b > 12 * GIB) { + base_cap_ms.saturating_mul(4) + } else { + base_cap_ms.saturating_mul(3) + } } else if vram_budget.is_some_and(|b| b > 12 * GIB) { base_cap_ms.saturating_mul(2) } else { @@ -6040,9 +6044,9 @@ mod tests { // 12 GiB baseline keeps 8 ms when calm and scales to 24 ms on catchup. assert_eq!(texspk_cap_ms(8, Some(12 * GIB), true, false, false), 8); assert_eq!(texspk_cap_ms(8, Some(12 * GIB), true, false, true), 24); - // >12 GiB (e.g. 16 GiB RTX 5080) with room doubles calm cap to 16 ms, 24 ms on catchup. + // >12 GiB (e.g. 16 GiB RTX 5080) with room doubles calm cap to 16 ms, 32 ms on catchup. assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, false, false), 16); - assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, false, true), 24); + assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, false, true), 32); // Full card or host-RAM pressure never expands the cap. assert_eq!(texspk_cap_ms(8, Some(16 * GIB), false, false, true), 8); assert_eq!(texspk_cap_ms(8, Some(16 * GIB), true, true, true), 8); diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 5f36ebb68..ff2fcc9a1 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -104,7 +104,7 @@ fn claim(resource: This, first: u32, there: u64) -> Option { let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); } - let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; + let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST * 2 }; if !crate::residency::allow_staging_growth(false) || BYTES.load(Relaxed) >= most || copy.flags() & 0x7 != 0 @@ -261,8 +261,15 @@ impl Worker { } fn copy(&self, jobs: &[Arc], value: u64) -> windows::core::Result<()> { - for job in jobs { - job.staging.refresh(); + if jobs.len() >= 2 { + let stagings: Vec<_> = jobs.iter().map(|job| job.staging.clone()).collect(); + crate::shadow::wide_each(stagings.len(), move |i| { + stagings[i].refresh(); + }); + } else { + for job in jobs { + job.staging.refresh(); + } } // SAFETY: this worker's allocator and list, whose last submission has // run; the jobs hold what the list names until after the wait. From bcb4e1f1944b4c01d40c07d9949a6646c79f0dd1 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:16:18 -0300 Subject: [PATCH 12/22] perf(gpu): hold only asked pages during submission write-watch askings Adapted from #697 by @0xkn0wh3r3. --- crates/victory-gpu/src/host.rs | 111 ++++++++++++++++++++- crates/victory-gpu/src/watch.rs | 168 +++++++++++++++++++++++++++++--- 2 files changed, 263 insertions(+), 16 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6ee9af474..c7f889cf6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -11485,12 +11485,22 @@ mod refresh_tests { } } + /// One submission's asking at a time in this test process, as in the + /// layer (one thread prepares them): taken by [`submission`] and by the + /// tests that ask as a submission does themselves. (Without it, one + /// test's asking ended another's while a third thread of that one was + /// refreshing: 4 of 40 runs of these tests with `watch::`'s left a copy + /// behind, with every hold of pages, 1 of 40 holding all memory; none + /// in 60 of the test alone.) + fn one_submission() -> std::sync::MutexGuard<'static, ()> { + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + ONE.lock().unwrap_or_else(|e| e.into_inner()) + } + /// Prepares as a submission does: one asking for all the ranges, the /// refreshes in several flushes, the asking's end. fn submission(ranges: &[(Arc, usize, usize)], flushes: usize) { - // One at a time, as submissions are. - static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); - let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let _one = one_submission(); let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect(); crate::watch::ask_once(&asked); let mut batch = Batch::default(); @@ -11567,6 +11577,100 @@ mod refresh_tests { } } + /// A submission's asking beside other threads' askings, as the heaps' + /// thread and the helpers' texture refreshes ask while one is prepared: + /// copies of the same title memory refreshed by a submission on one + /// thread and one range at a time on another, while a third asks about + /// other memory without end. Whatever was written before a round, every + /// copy holds what title memory holds after it (an asking that forgot + /// pages another had not yet noted would leave one of them behind). + #[test] + fn askings_of_other_threads_beside_a_submission() { + const LEN: usize = 32 * PAGE; + let mut random = Random(0x2468_1357_ACE0_BDF9); + let regions = [title(LEN, false), title(LEN, true)]; + let elsewhere = title(LEN, false); + // SAFETY: the test's own memory. + unsafe { + for r in regions.into_iter().chain([elsewhere]) { + std::ptr::write_bytes(r as *mut u8, 1, LEN); + } + } + // The submission's copies, and the other thread's over the same + // memory, cut elsewhere. + let cut = |spans: &[(usize, usize)]| -> Vec<(Arc, *mut u8, usize, usize)> { + regions + .iter() + .flat_map(|®ion| { + spans.iter().map(move |&(from, to)| { + let data = memory(to - from); + (Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data, region + from, to - from) + }) + }) + .collect() + }; + let ours = cut(&(0..8).map(|i| (i * 4 * PAGE, (i + 1) * 4 * PAGE)).collect::>()); + let theirs = cut(&[(100, 6 * PAGE + 9), (6 * PAGE + 9, 19 * PAGE), (19 * PAGE, LEN - 3), (3 * PAGE, 4 * PAGE + 1)]); + let ranges: Vec<(Arc, usize, usize)> = ours.iter().map(|c| (c.0.clone(), c.2, c.3)).collect(); + let same = |c: &(Arc, *mut u8, usize, usize)| unsafe { + std::slice::from_raw_parts(c.2 as *const u8, c.3) == std::slice::from_raw_parts(c.1, c.3) + }; + let stop = std::sync::atomic::AtomicBool::new(false); + // Told to stop however the rounds end (a failed one too: the scope + // would wait for it without end). + struct Stop<'a>(&'a std::sync::atomic::AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::Relaxed); + } + } + const ROUNDS: usize = 300; + // (Raw pointers are the test's own memory, used by one thread at a time.) + struct Sent(T); + unsafe impl Send for Sent {} + unsafe impl Sync for Sent {} + let theirs = Sent(theirs); + std::thread::scope(|s| { + // Without end, about memory no copy here holds. + s.spawn(|| { + let mut n = 0usize; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + let at = elsewhere + (n * 7 % 31) * PAGE; + // SAFETY: the test's own memory. + unsafe { (at as *mut u8).write_volatile(n as u8) }; + let _ = crate::watch::writes(at, at + PAGE, false); + n += 1; + } + }); + let _stop = Stop(&stop); + for round in 0..ROUNDS { + for _ in 0..1 + random.below(8) { + let at = regions[random.below(2)] + random.below(LEN - 64); + for i in 0..1 + random.below(60) { + // SAFETY: the test's own memory. + unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) }; + } + } + // One range at a time on another thread, beside the submission. + std::thread::scope(|s| { + let theirs = &theirs; + s.spawn(move || { + for c in &theirs.0 { + c.0.update(c.2, c.3); + } + }); + submission(&ranges, 1 + random.below(3)); + }); + for c in &ours { + assert!(same(c), "round {round}: a copy the submission refreshed at {:#x}+{:#x} differs", c.2, c.3); + } + for c in &theirs.0 { + assert!(same(c), "round {round}: a copy refreshed beside it at {:#x}+{:#x} differs", c.2, c.3); + } + } + }); + } + /// A copy in the card's memory, with the card's side and the sends to it /// played by the test. struct Carded { @@ -11867,6 +11971,7 @@ mod refresh_tests { // Ends in the middle of pages. let (at, len) = (region + 500, 5 * PAGE); let look = |expected: bool, what: &str| { + let _one = one_submission(); // The submission's one asking, which takes two ranges. (Again // if a submission of another test ended it.) let mut known = false; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 1e63f3431..3e52023e7 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -250,6 +250,87 @@ impl Drop for Asking { } } +/// Whether a submission's askings ([`ask_ahead`], [`ask_rest`]) hold only +/// the pages they ask about ([`Askings`]). On by default; +/// `VICTORY_ASK_HOLD_ALL=1`: they hold all memory, as before. +/// +/// Holding all memory, each waited for every other asking to end and made +/// every other wait for it: the descriptor heaps' thread, which holds a +/// heap's pages through its asking and through guarding them again, began +/// its round just before the submission's asking (the log of 2026-11-28: +/// 5.1-6.4 ms of its asking a frame, in some 16 rounds), and texture +/// refreshes on the helpers ask too. Neither asks about the submission's +/// pages more often than before: only about others, at the same time. +fn hold_pages() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_HOLD_ALL").is_none_or(|v| v != "1")) +} + +/// Page ranges held in [`ASKING`] together until dropped: all of them or +/// none, so that two threads that each hold several never wait for each +/// other in a circle. +struct Askings(Vec<(usize, usize)>); + +impl Askings { + /// `ranges`: page ranges in order, none touching another ([`merged`]). + fn hold(ranges: Vec<(usize, usize)>) -> Askings { + let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); + if held.iter().any(|&(a, b)| overlaps(&ranges, a, b)) { + held = waited(0, || { + let mut held = held; + while held.iter().any(|&(a, b)| overlaps(&ranges, a, b)) { + held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner()); + } + held + }); + } + held.extend_from_slice(&ranges); + Askings(ranges) + } + + /// Those of `ranges` (in order, none touching another) if + /// [`hold_pages`], else all memory. + fn hold_or_all(ranges: Vec<(usize, usize)>) -> Result { + if hold_pages() { Ok(Askings::hold(ranges)) } else { Err(Asking::hold_all()) } + } +} + +impl Drop for Askings { + fn drop(&mut self) { + let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner()); + for range in &self.0 { + if let Some(i) = held.iter().position(|r| r == range) { + held.swap_remove(i); + } + } + drop(held); + ASKING.1.notify_all(); + } +} + +/// Whether `[a, b)` overlaps one of `ranges` (in order, none touching +/// another). +fn overlaps(ranges: &[(usize, usize)], a: usize, b: usize) -> bool { + // The first that ends after `a`: it overlaps if it begins before `b`. + let i = ranges.partition_point(|&(_, end)| end <= a); + ranges.get(i).is_some_and(|&(start, _)| start < b) +} + +/// `ranges` in order, those that overlap or touch made one, empty ones +/// left out. +fn merged(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.retain(|r| r.0 < r.1); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for (a, b) in ranges { + match out.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + out +} + thread_local! { /// Room for the kernel's answer. static FOUND: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; @@ -342,8 +423,9 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { if journal().kept { return; } - let _all = Asking::hold_all(); - let (mut asked, mut written) = (Vec::new(), Vec::new()); + // The runs asked about: pieces close together, with the pages between + // them, which the kernel's asking walks and resets too. + let mut runs = Vec::new(); let mut i = 0; while i < pieces.len() { let first = pieces[i].0; @@ -356,9 +438,15 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { last = last.max(pieces[k].1); k += 1; } - ask_run(&pieces[i..k], &mut asked, &mut written); + runs.push((i, k, first, last)); i = k; } + // Those pages held ([`hold_pages`]) until the answers are in the journal. + let _held = Askings::hold_or_all(merged(runs.iter().map(|&(.., first, last)| (first, last)).collect())); + let (mut asked, mut written) = (Vec::new(), Vec::new()); + for &(i, k, ..) in &runs { + ask_run(&pieces[i..k], &mut asked, &mut written); + } note_hot(&written); let mut j = journal_mut(); j.ahead_asked = next_asking(); @@ -552,22 +640,28 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { /// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the /// asking stands. fn ask_rest(ranges: &[(usize, usize)]) { - let _all = Asking::hold_all(); - let mut ahead = { - let mut j = journal_mut(); - std::mem::take(&mut j.ahead) - }; + // (Read, not taken: holding only its own pages ([`hold_pages`]), this + // asking lets other threads ask meanwhile, and the journal goes on + // answering them for what `ask_ahead` asked.) + let mut ahead = journal().ahead.clone(); + // The ranges it asks about: those `ask_ahead` left, held until the + // answers are in the journal. + let alone: Vec<(usize, usize)> = ranges + .iter() + .filter(|&&(start, end)| start < end && !published(start, end)) + .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) + .filter(|&(first, last)| !ahead.iter().any(|&(a, b)| a <= first && last <= b)) + .collect(); + let _held = Askings::hold_or_all(merged(alone.clone())); // `ask_ahead` leaves a range that lies alone to `writes`, which asks // once per flush: with one asking for the submission that was every // such range asked again at each of its 70 flushes (run 76: 2,300 // askings a frame with the switch on, as without it). They are asked // here, once; what is not write-watched stays with `writes`. + // (Those held, and no others: a range's bits found since are no reason + // to ask about a range not held.) let mut written = Vec::new(); - for &(start, end) in ranges { - if start >= end || published(start, end) { - continue; - } - let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + for (first, last) in alone { if !ahead.iter().any(|&(a, b)| a <= first && last <= b) && let Some(pages) = kernel_written(first, last) { @@ -5282,3 +5376,51 @@ mod many_askers_tests { assert!(!BITS.swap_on(70) && BITS.swap_on(70) && BITS.all(70, 71)); } } + +#[cfg(test)] +mod ask_holds { + use super::{Askings, merged, overlaps}; + use std::sync::atomic::{AtomicBool, Ordering::SeqCst}; + use std::time::Duration; + + #[test] + fn ranges_are_merged_in_order_and_told_apart() { + assert_eq!(merged(vec![(9, 12), (1, 3), (3, 5), (4, 4), (11, 20), (30, 31)]), [(1, 5), (9, 20), (30, 31)]); + assert!(merged(vec![(5, 5)]).is_empty()); + let held = [(1, 5), (9, 20), (30, 31)]; + assert!(overlaps(&held, 0, 2)); + assert!(overlaps(&held, 4, 9)); + assert!(!overlaps(&held, 5, 9), "touching is not overlapping"); + assert!(!overlaps(&held, 20, 30)); + assert!(overlaps(&held, 19, 21)); + assert!(overlaps(&held, 0, usize::MAX)); + assert!(!overlaps(&held, 31, usize::MAX)); + assert!(!overlaps(&[], 0, usize::MAX)); + } + + /// Pages held by one asking hold up an asking of any of them, and of no + /// other page; several are taken all at once. + #[test] + fn an_asking_waits_only_for_the_pages_it_asks_about() { + // Far above any page the other tests' memory has. + const AT: usize = usize::MAX / 2; + let held = Askings::hold(vec![(AT, AT + 4), (AT + 10, AT + 12)]); + // Other pages: at once. + drop(Askings::hold(vec![(AT + 4, AT + 10), (AT + 12, AT + 20)])); + drop(super::Asking::hold(AT + 5, AT + 6)); + // One page in common: not before the first lets go. + let done = AtomicBool::new(false); + std::thread::scope(|s| { + s.spawn(|| { + let _second = Askings::hold(vec![(AT + 6, AT + 8), (AT + 11, AT + 13)]); + done.store(true, SeqCst); + }); + std::thread::sleep(Duration::from_millis(100)); + assert!(!done.load(SeqCst), "an asking of a held page went ahead"); + drop(held); + }); + assert!(done.load(SeqCst)); + // And all of them are let go. + drop(Askings::hold(vec![(AT, AT + 20)])); + } +} From 74223a586e2e06de658fa91d70efdd13731aa289 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:19:56 -0300 Subject: [PATCH 13/22] perf(gpu): split VIEW_SHAPES lock, O(1) FxHashMap, and forget() read-check Adapted from #666 by @Capt-Speed. --- crates/victory-gpu/src/descriptor.rs | 166 +++++++++++++++++++++------ 1 file changed, 132 insertions(+), 34 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8016c934b..59bb17670 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1019,7 +1019,7 @@ const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV"); /// A shader view or sampler as the title described it (descriptions in the /// host's layout, kept as words), for the host to build its own from. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) enum View { /// Constant buffer: GPU address and size. Constant(u64, u32), @@ -1076,16 +1076,53 @@ impl View { /// without the address: as many as the title has kinds of textures and /// buffers, however often it moves them). /// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before. +/// Fast non-cryptographic 64-bit hasher for internal view/shape lookup maps +/// (keeps lock hold times O(1) without extra crate dependencies). +#[derive(Default)] +struct FxHasher(u64); + +impl std::hash::Hasher for FxHasher { + #[inline] + fn finish(&self) -> u64 { + self.0 + } + #[inline] + fn write(&mut self, bytes: &[u8]) { + const K: u64 = 0x517c_c1b7_2722_0a95; + let mut h = self.0; + let mut chunks = bytes.chunks_exact(8); + for c in &mut chunks { + let v = u64::from_ne_bytes(c.try_into().expect("8-byte chunk")); + h = (h.rotate_left(5) ^ v).wrapping_mul(K); + } + for &b in chunks.remainder() { + h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(K); + } + self.0 = h; + } + #[inline] + fn write_u32(&mut self, i: u32) { + self.0 = (self.0.rotate_left(5) ^ u64::from(i)).wrapping_mul(0x517c_c1b7_2722_0a95); + } + #[inline] + fn write_u64(&mut self, i: u64) { + self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517c_c1b7_2722_0a95); + } + #[inline] + fn write_usize(&mut self, i: usize) { + self.write_u64(i as u64); + } +} + +type FastMap = std::collections::HashMap>; + struct Views { /// Each entry's view and generation. list: Vec<(View, u32)>, - index: std::collections::BTreeMap, + index: FastMap, /// Entries naming each resource. - by_resource: std::collections::BTreeMap>, + by_resource: FastMap>, free: Vec, - /// The shapes of views of placed memory, and where each is. - shapes: Vec, - shape_index: std::collections::BTreeMap, /// Entries of views that no resource releases (constant buffer views /// and views of placed memory that did not fit a record), oldest first, /// with the generation each was made at: past [`ownerless_cap`] the @@ -1093,19 +1130,45 @@ struct Views { ownerless: std::collections::VecDeque<(u32, u32)>, } +/// Append-only table of placed-view shapes, kept under its own `RwLock` so +/// frequent `PLACED` lookups across recording threads never stall behind +/// `VIEWS` resource-creation or `forget` writes. +struct ViewShapes { + /// The shapes of views of placed memory, and where each is. + shapes: Vec, + shape_index: FastMap, +} + /// Read far more often than written: every slot a draw reads through a /// table is looked up here, on several recording threads at once in the -/// world. Readers share it; only a view not seen before (a new table entry -/// or shape) and a released resource take it alone. -static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { - list: Vec::new(), - index: std::collections::BTreeMap::new(), - by_resource: std::collections::BTreeMap::new(), - free: Vec::new(), - shapes: Vec::new(), - shape_index: std::collections::BTreeMap::new(), - ownerless: std::collections::VecDeque::new(), -}); +/// world. Readers share it; only a view not seen before (a new table entry) +/// and a released resource take it alone. +static VIEWS: std::sync::OnceLock> = std::sync::OnceLock::new(); + +static VIEW_SHAPES: std::sync::OnceLock> = std::sync::OnceLock::new(); + +#[inline] +fn views_lock() -> &'static std::sync::RwLock { + VIEWS.get_or_init(|| { + std::sync::RwLock::new(Views { + list: Vec::new(), + index: FastMap::default(), + by_resource: FastMap::default(), + free: Vec::new(), + ownerless: std::collections::VecDeque::new(), + }) + }) +} + +#[inline] +fn shapes_lock() -> &'static std::sync::RwLock { + VIEW_SHAPES.get_or_init(|| { + std::sync::RwLock::new(ViewShapes { + shapes: Vec::new(), + shape_index: FastMap::default(), + }) + }) +} /// How many table entries of views without a resource are kept /// ([`Views::ownerless`]). Once the shapes of placed views are full (the @@ -1249,7 +1312,7 @@ fn placed_words(shape: u32, address: u64) -> [u32; 2] { kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) } -impl Views { +impl ViewShapes { /// The number of `shape`, a new one if it is not there yet; `None` when /// the shapes are full (the view is then a table entry). fn shape(&mut self, shape: Shape) -> Option { @@ -1278,6 +1341,9 @@ impl Views { desc[12..].copy_from_slice(&rest[10..]); Some(View::Placed(unordered, resource, desc)) } +} + +impl Views { /// The record words of `view` as a table entry, if it has one. fn entry_of(&self, view: &View) -> Option<[u32; 2]> { @@ -1362,8 +1428,8 @@ fn words_for(view: View) -> [u32; 2] { let (shape, address) = shape_of(*unordered, resource, desc); if address >> PLACED_ADDRESS_BITS == 0 { // Nearly every placed view has a shape seen before. - let known = views_read().shape_index.get(&shape).copied(); - let shape = known.or_else(|| views_write().shape(shape)); + let known = shapes_read().shape_index.get(&shape).copied(); + let shape = known.or_else(|| shapes_write().shape(shape)); if let Some(shape) = shape { NAMED_WHOLE[1].fetch_add(1, Relaxed); return placed_words(shape, address); @@ -1381,12 +1447,13 @@ fn words_for(view: View) -> [u32; 2] { } fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { - match VIEWS.try_read() { + let lock = views_lock(); + match lock.try_read() { Ok(views) => views, Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), Err(std::sync::TryLockError::WouldBlock) => { let started = std::time::Instant::now(); - let views = VIEWS.read().unwrap_or_else(|e| e.into_inner()); + let views = lock.read().unwrap_or_else(|e| e.into_inner()); waited(1, started); views } @@ -1394,18 +1461,47 @@ fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { } fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { - match VIEWS.try_write() { + let lock = views_lock(); + match lock.try_write() { Ok(views) => views, Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), Err(std::sync::TryLockError::WouldBlock) => { let started = std::time::Instant::now(); - let views = VIEWS.write().unwrap_or_else(|e| e.into_inner()); + let views = lock.write().unwrap_or_else(|e| e.into_inner()); waited(1, started); views } } } +fn shapes_read() -> std::sync::RwLockReadGuard<'static, ViewShapes> { + let lock = shapes_lock(); + match lock.try_read() { + Ok(shapes) => shapes, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + let started = std::time::Instant::now(); + let shapes = lock.read().unwrap_or_else(|e| e.into_inner()); + waited(1, started); + shapes + } + } +} + +fn shapes_write() -> std::sync::RwLockWriteGuard<'static, ViewShapes> { + let lock = shapes_lock(); + match lock.try_write() { + Ok(shapes) => shapes, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + let started = std::time::Instant::now(); + let shapes = lock.write().unwrap_or_else(|e| e.into_inner()); + waited(1, started); + shapes + } + } +} + /// For the memory line: the distinct views kept ([`Views`]), those of them /// free for reuse, and the bytes the table and its index hold for them (an /// estimate: an entry of the table, and one of the index with its share of @@ -1418,6 +1514,7 @@ fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { pub(crate) fn views_kept() -> [u64; 8] { use std::sync::atomic::Ordering::Relaxed; let views = views_read(); + let shapes = shapes_read(); let each = size_of::<(View, u32)>() as u64; let shape = size_of::() as u64; let (mut constants, mut placed) = (0, 0); @@ -1433,11 +1530,11 @@ pub(crate) fn views_kept() -> [u64; 8] { views.free.len() as u64, views.list.capacity() as u64 * each + views.index.len() as u64 * each * 3 / 2 - + views.shapes.capacity() as u64 * shape - + views.shape_index.len() as u64 * shape * 3 / 2, + + shapes.shapes.capacity() as u64 * shape + + shapes.shape_index.len() as u64 * shape * 3 / 2, constants, placed, - views.shapes.len() as u64, + shapes.shapes.len() as u64, NAMED_WHOLE[0].load(Relaxed), NAMED_WHOLE[1].load(Relaxed), ] @@ -1657,6 +1754,9 @@ pub(crate) fn forget(resource: usize) { .lock() .unwrap_or_else(|e| e.into_inner()) .remove(&resource); + if !views_read().by_resource.contains_key(&resource) { + return; + } let mut views = views_write(); let Some(entries) = views.by_resource.remove(&resource) else { return; @@ -1687,7 +1787,7 @@ fn view_at(i: u32, generation: u32) -> Option { (*current == generation).then(|| view.clone()) } CONSTANT => Some(constant_of(i, generation)), - PLACED => views_read().placed_of(i, generation), + PLACED => shapes_read().placed_of(i, generation), _ => None, } } @@ -2330,11 +2430,9 @@ mod tests { fn ownerless_entries_are_capped() { let mut views = Views { list: Vec::new(), - index: std::collections::BTreeMap::new(), - by_resource: std::collections::BTreeMap::new(), + index: FastMap::default(), + by_resource: FastMap::default(), free: Vec::new(), - shapes: Vec::new(), - shape_index: std::collections::BTreeMap::new(), ownerless: std::collections::VecDeque::new(), }; let placed = |n: u32| View::Placed(false, [n; 14], [n; 16]); @@ -2428,8 +2526,8 @@ mod tests { View::Placed(_, r, _) => *r == kept, _ => false, }; - let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); - let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == kept).count(); + let entries = || views_read().list.iter().filter(|(v, _)| mine(v)).count(); + let shapes = || shapes_read().shapes.iter().filter(|s| s.1 == kept).count(); for n in 0..20_000u64 { let address = 0x6_0000_0000 + n * 0x100; create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); From 9ace3a4e37609758c9d268235a6535520e8103ba Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:23:26 -0300 Subject: [PATCH 14/22] perf(gpu): make texture and staging pool blocks with the pool lock released Adapted from #661 by @0xkn0wh3r3. --- crates/victory-gpu/src/pool.rs | 308 +++++++++++++++++++++++++++++---- 1 file changed, 271 insertions(+), 37 deletions(-) diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index f94df0483..21904473d 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -205,21 +205,28 @@ struct Pool { spare: usize, most: usize, retry_growth_at: u64, + /// Blocks being made ahead by a thread outside the lock ([`take_from`]), + /// counted as empty ones so that no two threads make the same one. + making_ahead: usize, } impl Pool { const fn new(most: usize) -> Pool { - Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 } + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0, making_ahead: 0 } } /// A piece of `len` bytes and the memory it lies in, and whether that /// part was ever used before; `make` makes a block when none has room. + /// (`make` runs with the pool borrowed; the pools of the process are + /// taken from with [`take_from`], which makes blocks with their lock let go.) + #[cfg(test)] fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnMut() -> Option) -> Option<(Piece, B, bool)> { self.take_ripe(len, align, now, Ripe::ALL, make) } /// The same from a block that is ripe, if one has room; `make` makes one /// ahead too, when few are empty. + #[cfg(test)] fn take_ripe( &mut self, len: u64, @@ -228,6 +235,33 @@ impl Pool { ripe: Ripe, mut make: impl FnMut() -> Option, ) -> Option<(Piece, B, bool)> { + let (i, start) = match self.cut(len, align, now, ripe)? { + Some(found) => found, + None => { + if !self.may_grow(now) { + return None; + } + let Some(memory) = make() else { + self.failed_growth(now); + return None; + }; + self.add_and_cut(memory, ripe.started, len, align)? + } + }; + if self.short_ahead(now, ripe) { + match make() { + Some(memory) => { + self.add(memory, ripe.started); + } + None => self.failed_growth(now), + } + } + self.taken(i, start, len, ripe) + } + + /// Where a piece of `len` bytes was cut from a block there is: `None` + /// if it is never pooled, `Some(None)` if no block has room. + fn cut(&mut self, len: u64, align: u64, now: u64, ripe: Ripe) -> Option> { // With blocks made ahead, what would be an allocation of its own (and // new when the card first reads it) lies in one of those too. if len == 0 || len > if ripe.ahead > 0 { BLOCK } else { BLOCK / 2 } { @@ -251,47 +285,49 @@ impl Pool { unripe.sort_unstable(); found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?))); } - // A failed 64 MiB block must not trigger another driver call for each - // small texture. Existing free ranges remain usable during backoff. - let (i, start) = match found { - Some(found) => found, - None => { - let memory = self.grow(now, &mut make)?; - let i = self.add(memory, ripe.started); - (i, self.blocks[i].as_mut()?.free.take(len, align)?) - } - }; - if ripe.ahead > 0 { - if !ripe.is(self.blocks[i].as_ref()?) { - let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - tracing::info!("textures cut from blocks made while lists ran that still run: {n}"); - } - } - let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count(); - if empty < ripe.ahead - && let Some(memory) = self.grow(now, &mut make) - { - self.add(memory, ripe.started); + Some(found) + } + + /// Whether a block may be made now: a failed 64 MiB block must not + /// trigger another driver call for each small texture. Existing free + /// ranges remain usable during backoff. + fn may_grow(&self, now: u64) -> bool { + now >= self.retry_growth_at + } + + fn failed_growth(&mut self, now: u64) { + self.retry_growth_at = now.saturating_add(500); + } + + /// Adds a block just made and cuts the piece from it. + fn add_and_cut(&mut self, memory: B, made: u64, len: u64, align: u64) -> Option<(usize, u64)> { + let i = self.add(memory, made); + Some((i, self.blocks[i].as_mut()?.free.take(len, align)?)) + } + + /// Whether a block is to be made ahead: fewer are empty (or being made) + /// than are wanted. + fn short_ahead(&self, now: u64, ripe: Ripe) -> bool { + ripe.ahead > 0 + && self.may_grow(now) + && self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count() + self.making_ahead < ripe.ahead + } + + /// The piece cut at `start` of block `i`, its memory, and whether it was + /// used before. + fn taken(&mut self, i: usize, start: u64, len: u64, ripe: Ripe) -> Option<(Piece, B, bool)> { + let block = self.blocks[i].as_mut()?; + if ripe.ahead > 0 && !ripe.is(block) { + let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!("textures cut from blocks made while lists ran that still run: {n}"); } } - let block = self.blocks[i].as_mut()?; let again = start < block.used_to; block.used_to = block.used_to.max(start + len); Some((Piece { block: i, start, len }, block.memory.clone(), again)) } - fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option) -> Option { - if now < self.retry_growth_at { - return None; - } - let block = make(); - if block.is_none() { - self.retry_growth_at = now.saturating_add(500); - } - block - } - fn add(&mut self, memory: B, made: u64) -> usize { let i = match self.blocks.iter().position(Option::is_none) { Some(i) => i, @@ -398,6 +434,78 @@ fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } +/// [`Pool::take_ripe`] of a pool behind a lock, with blocks made while the +/// lock is let go. Making one is a 64 MiB heap or upload buffer, made +/// resident and waited for until it is mapped (`crate::host::resident`, +/// `crate::host::mapped`): a tenth of a millisecond to some, but over a +/// second near the card's budget (`MakeResident` waits for the system to +/// evict first). Under the lock every thread that took a texture, or gave +/// one back, waited for that. +/// +/// `ripe` is asked again once a block is made: a block is ripe once the +/// submissions begun before it was made have finished, so its mark is +/// taken after the making (a mark taken before would be too low). +/// +/// Two threads that both find no room may each make a block; the second +/// is a block made ahead, or a spare that [`Pool::reclaim`] lets go. +fn take_from( + pool: &'static Mutex>, + len: u64, + align: u64, + ripe: impl Fn() -> Ripe, + mut make: impl FnMut() -> Option, +) -> Option<(Piece, B, bool)> { + let first = ripe(); + let mut p = lock(pool); + let (i, start) = match p.cut(len, align, now(), first)? { + Some(found) => found, + None => { + if !p.may_grow(now()) { + return None; + } + drop(p); + let made = make(); + let mark = ripe().started; + p = lock(pool); + let Some(memory) = made else { + p.failed_growth(now()); + return None; + }; + p.add_and_cut(memory, mark, len, align)? + } + }; + let ahead = p.short_ahead(now(), first); + if ahead { + p.making_ahead += 1; + } + let taken = p.taken(i, start, len, first); + drop(p); + if ahead { + /// Counts the block as made (or not) even if `make` unwinds. + struct Making(&'static Mutex>); + impl Drop for Making { + fn drop(&mut self) { + let mut p = lock(self.0); + p.making_ahead = p.making_ahead.saturating_sub(1); + } + } + let making = Making(pool); + let made = make(); + let mark = ripe().started; + let mut p = lock(pool); + // Counted off under the same lock the block is added under. + std::mem::forget(making); + p.making_ahead = p.making_ahead.saturating_sub(1); + match made { + Some(memory) => { + p.add(memory, mark); + } + None => p.failed_growth(now()), + } + } + taken +} + /// Bytes of the pieces textures hold now. static HELD: AtomicU64 = AtomicU64::new(0); @@ -527,7 +635,7 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi } // Copies from a buffer begin at multiples of 512. let bytes = bytes.next_multiple_of(512); - let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { + let (piece, memory, again) = take_from(&STAGING, bytes, 512, || Ripe::ALL, || { // Only gate speculative bindless prefetch on staging-pool growth // headroom; table-bound textures and decoration bakes are sampled // immediately and would otherwise read uninitialized/reused VRAM. @@ -823,7 +931,7 @@ pub(crate) unsafe fn texture( 0 }; #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] - let (piece, heap, again) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { + let (piece, heap, again) = take_from(&TEXTURES, info.SizeInBytes, info.Alignment.max(1), Ripe::now, || { let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -1003,6 +1111,132 @@ mod tests { assert!(none.take(65536, 65536, 0, || None).is_none()); } + /// What a thread that only cuts pieces from a block with room waits for + /// while another thread makes new blocks of the card's memory, each a + /// heap of 64 MiB made resident and waited for until it is mapped, as + /// [`texture`] makes them: with the blocks made inside the pool's lock + /// ([`Pool::take_ripe`], the way it was) and with the lock let go + /// ([`take_from`]). Run with `--ignored --nocapture`. + #[test] + #[ignore] + fn waits_for_a_piece_while_blocks_are_made() { + use std::sync::atomic::AtomicBool; + use std::time::{Duration, Instant}; + const BLOCKS: usize = 12; + let Some(host) = crate::host::host() else { return }; + if let Some((_, name, _)) = victory_shader::emit::host::hardware_adapter() { + println!("adapter: {name}"); + } + let make_block = |device: &ID3D12Device| -> Option { + let desc = D3D12_HEAP_DESC { + SizeInBytes: BLOCK, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(), + }; + let mut heap: Option = None; + // SAFETY: plain creation. + unsafe { device.CreateHeap(&desc, &mut heap) }.ok()?; + let heap = heap?; + crate::host::resident(device, &heap).and_then(|()| crate::host::mapped(device)).ok()?; + Some(heap) + }; + let ms = |d: Duration| d.as_secs_f64() * 1e3; + for inside in [true, false] { + let pool: &'static Mutex> = Box::leak(Box::new(Mutex::new(Pool::new(SPARE_KEPT)))); + // The block the other thread cuts from: room for all its pieces. + assert!(take_from(pool, 256, 256, || Ripe::ALL, || make_block(&host.device)).is_some()); + let done = AtomicBool::new(false); + let (makes, waits) = std::thread::scope(|s| { + let maker = s.spawn(|| { + // A whole block each time, made ahead too: a new block for + // every piece. + let ripe = || Ripe { started: 0, finished: 0, ahead: 1 }; + let make = || make_block(&host.device); + let mut makes = Vec::new(); + for _ in 0..BLOCKS { + let began = Instant::now(); + let taken = if inside { + lock(pool).take_ripe(BLOCK, 65536, now(), ripe(), make) + } else { + take_from(pool, BLOCK, 65536, ripe, make) + }; + assert!(taken.is_some(), "a block of the card's memory"); + makes.push(began.elapsed()); + } + done.store(true, Ordering::Release); + makes + }); + let mut waits = Vec::new(); + while !done.load(Ordering::Acquire) { + let began = Instant::now(); + let taken = take_from(pool, 256, 256, || Ripe::ALL, || panic!("the first block has room")); + waits.push(began.elapsed()); + assert!(taken.is_some()); + std::thread::yield_now(); + } + (maker.join().unwrap(), waits) + }); + let mut sorted = waits.clone(); + sorted.sort_unstable(); + let at = |q: f64| sorted[((sorted.len() - 1) as f64 * q) as usize]; + println!( + "blocks made {}: {BLOCKS} pieces that each made blocks, {:.2} ms each on average; {} pieces cut from a block with \ + room meanwhile: median {:.4} ms, 99th percentile {:.3} ms, longest {:.3} ms, {:.1} ms in all", + if inside { "inside the lock (before)" } else { "with the lock let go (after)" }, + ms(makes.iter().sum::()) / BLOCKS as f64, + sorted.len(), + ms(at(0.5)), + ms(at(0.99)), + ms(*sorted.last().unwrap()), + ms(waits.iter().sum()), + ); + // The card's memory back. + let mut p = lock(pool); + p.blocks.clear(); + p.resting.clear(); + } + } + + /// A block is made with the pool's lock let go (making one waits for + /// residency, up to a second near the card's budget), it is marked with + /// the submissions begun after its making, and a block made ahead is + /// counted off again whether it was made or not. + #[test] + fn blocks_are_made_with_the_pool_let_go() { + static POOL: Mutex> = Mutex::new(Pool::new(SPARE_KEPT)); + let made = std::cell::Cell::new(0u64); + let make = || { + assert!(POOL.try_lock().is_ok(), "a block was made with the pool's lock held"); + made.set(made.get() + 1); + Some(made.get()) + }; + // Ten more submissions begun for every block made: a mark taken + // before a making would be ten lower. + let ripe = || Ripe { started: made.get() * 10, finished: 0, ahead: 2 }; + let (piece, memory, again) = take_from(&POOL, BLOCK / 2, 65536, ripe, make).unwrap(); + assert_eq!((piece.start, memory, again), (0, 1, false)); + assert_eq!(made.get(), 2, "one more made ahead"); + { + let p = lock(&POOL); + let marks: Vec = p.blocks.iter().flatten().map(|b| b.made).collect(); + assert_eq!(marks, [10, 20]); + assert_eq!(p.making_ahead, 0); + } + // Block 2 is empty, so one more is made ahead; then that one fails. + assert_eq!(take_from(&POOL, BLOCK / 2, 65536, ripe, make).unwrap().1, 1); + assert_eq!(made.get(), 3); + let refuse = || { + assert!(POOL.try_lock().is_ok(), "a block was made with the pool's lock held"); + None + }; + let full = || Ripe { started: 100, finished: 100, ahead: 4 }; + assert!(take_from(&POOL, BLOCK / 2, 65536, full, refuse).is_some(), "cut from a block there is"); + let p = lock(&POOL); + assert_eq!(p.making_ahead, 0, "a block not made is counted off"); + assert!(!p.may_grow(now()), "and blocks are not asked for again at once"); + } + #[test] fn pieces_come_from_blocks_older_than_the_lists_that_run() { let mut pool: Pool = Pool::new(SPARE_KEPT); From 9f3d8692d393fd65ce7dee36d361d84783fab591 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:26:40 -0300 Subject: [PATCH 15/22] perf(gpu): add VICTORY_WAIT_RESIDENT=textures to wait for texture residency only Adapted from #654 by @bakdakonusuruz. --- crates/victory-gpu/src/host.rs | 44 ++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c7f889cf6..482e837a1 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -232,11 +232,35 @@ fn wait_resident() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_RESIDENT").is_none_or(|v| v != "0")) } +/// Whether plain buffers are waited for as well ([`wait_resident`]). +/// `VICTORY_WAIT_RESIDENT=textures` waits for texture blocks and textures +/// only: the device losses above lay in texture blocks, and the waits for +/// buffers are most of them (an RTX 4090 run: 59,000 waits, 18.1 s, the +/// longest 1.2 s; on an RTX 3080, 212,000 waits, 60.8 s, Belobug issue #346). +fn wait_resident_buffers() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_RESIDENT").is_none_or(|v| v != "0" && v != "textures")) +} + /// The flag memory is made with that [`resident`] waits for. pub(crate) fn not_resident() -> D3D12_HEAP_FLAGS { if wait_resident() { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE } } +/// [`not_resident`], [`resident`] and [`mapped`] for a plain buffer +/// ([`wait_resident_buffers`]). +fn buffer_not_resident() -> D3D12_HEAP_FLAGS { + if wait_resident_buffers() { not_resident() } else { D3D12_HEAP_FLAG_NONE } +} + +fn buffer_resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> { + if wait_resident_buffers() { resident(device, object) } else { Ok(()) } +} + +fn buffer_mapped(device: &ID3D12Device) -> windows::core::Result<()> { + if wait_resident_buffers() { mapped(device) } else { Ok(()) } +} + /// A queue of its own that new memory is waited for with ([`mapped`]). struct Aside { queue: ID3D12CommandQueue, @@ -9608,7 +9632,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - not_resident(), + buffer_not_resident(), &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, @@ -9616,7 +9640,7 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; + buffer_resident(&self.device, b)?; b.Map(0, None, Some(&mut data)) }) }; @@ -10912,7 +10936,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - not_resident(), + buffer_not_resident(), &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -10920,8 +10944,8 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - mapped(&self.device)?; + buffer_resident(&self.device, b)?; + buffer_mapped(&self.device)?; b.Map(0, None, Some(&mut data)) }) }; @@ -11001,7 +11025,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - not_resident(), + buffer_not_resident(), &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -11009,8 +11033,8 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - mapped(&self.device)?; + buffer_resident(&self.device, b)?; + buffer_mapped(&self.device)?; b.Map(0, None, Some(&mut data)) }) }; @@ -11051,7 +11075,7 @@ impl Host { let made = unsafe { self.device.CreateCommittedResource( &heap, - not_resident(), + buffer_not_resident(), &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -11062,7 +11086,7 @@ impl Host { if let Some(b) = &buffer { crate::book::made(b, || "an unordered access buffer".into()); } - let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device)); + let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| buffer_resident(&self.device, b))).and_then(|()| buffer_mapped(&self.device)); match made { Ok(()) => buffer, Err(e) => { From 87694c92615a624a40d3efd9e34398932c24f771 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:38:49 -0300 Subject: [PATCH 16/22] perf(gpu): compact AtomicU64 bitmask and in-place retain in filter_nothing_new --- crates/victory-gpu/src/host.rs | 58 +++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 482e837a1..92918dbcc 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9127,35 +9127,63 @@ impl Batch { /// `ask_ahead` and `wide_each`, returning how many were dropped. fn filter_nothing_new(items: &mut Vec<(std::sync::Arc, usize, usize)>) -> usize { const FEW: usize = 256; - const CHUNK: usize = 64; + const CHUNK: usize = 128; let all = items.len(); if all <= FEW { items.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); return all - items.len(); } - let taken = std::sync::Arc::new(std::mem::take(items)); + let words = all.div_ceil(64); let keep = std::sync::Arc::new( - (0..all) - .map(|_| std::sync::atomic::AtomicBool::new(false)) + (0..words) + .map(|_| std::sync::atomic::AtomicU64::new(0)) .collect::>(), ); - let (taken_ref, keep_ref) = (taken.clone(), keep.clone()); + // SAFETY: `wide_each` joins all workers before returning, so `items` + // outlives every worker closure; each worker only reads `&items[idx]`. + struct ItemsPtr(*const (std::sync::Arc, usize, usize), usize); + impl ItemsPtr { + fn len(&self) -> usize { + self.1 + } + unsafe fn slice(&self, start: usize, end: usize) -> &[(std::sync::Arc, usize, usize)] { + unsafe { std::slice::from_raw_parts(self.0.add(start), end - start) } + } + } + unsafe impl Send for ItemsPtr {} + unsafe impl Sync for ItemsPtr {} + let ptr = ItemsPtr(items.as_ptr(), all); + let keep_ref = keep.clone(); crate::shadow::wide_each(all.div_ceil(CHUNK), move |chunk| { let start = chunk * CHUNK; - let end = (start + CHUNK).min(taken_ref.len()); - for idx in start..end { - let (shadow, from, to) = &taken_ref[idx]; + let end = (start + CHUNK).min(ptr.len()); + // SAFETY: `start..end` is within `0..all` and `items` is immutable for this scope. + let slice = unsafe { ptr.slice(start, end) }; + let mut mask0 = 0u64; + let mut mask1 = 0u64; + for (offset, (shadow, from, to)) in slice.iter().enumerate() { if !shadow.nothing_new(*from, *to - *from) { - keep_ref[idx].store(true, Ordering::Relaxed); + if offset < 64 { + mask0 |= 1u64 << offset; + } else { + mask1 |= 1u64 << (offset - 64); + } } } + let word = chunk * 2; + if mask0 != 0 { + keep_ref[word].store(mask0, Ordering::Relaxed); + } + if mask1 != 0 { + keep_ref[word + 1].store(mask1, Ordering::Relaxed); + } + }); + let mut idx = 0usize; + items.retain(|_| { + let keep_item = (keep[idx >> 6].load(Ordering::Relaxed) & (1u64 << (idx & 63))) != 0; + idx += 1; + keep_item }); - let taken = std::sync::Arc::try_unwrap(taken).unwrap_or_else(|_| unreachable!()); - *items = taken - .into_iter() - .zip(keep.iter()) - .filter_map(|(item, k)| k.load(Ordering::Relaxed).then_some(item)) - .collect(); all - items.len() } From 9af806847c1972f28f775d6096c4a239421a62de Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:44:11 -0300 Subject: [PATCH 17/22] perf(play): enable texture residency wait, fresh-first due, and guard-driven hashing --- apps/victory/src/play.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index 054371ab4..597c1ff5a 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -92,6 +92,10 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_POOL_SMALL", "0"), ("VICTORY_TABLED_REREAD", "1"), ("VICTORY_QUEUE_HOST_TEXTURES", "0"), + ("VICTORY_WAIT_RESIDENT", "textures"), + ("VICTORY_DUE_FRESH_FIRST", "1"), + ("VICTORY_TEXTURE_HASH_EVERY", "0"), + ("VICTORY_TEXTURE_HOT_FRAMES", "0"), // Descriptor heaps' records ("VICTORY_HEAP_SYNC_FIRST", "1"), ("VICTORY_SYNC_IN_PLACE", "1"), From f88e7d52089b69d39218112971e464647c94144b Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:30:27 -0300 Subject: [PATCH 18/22] fix(gpu): use is_multiple_of in descriptor.rs --- crates/victory-gpu/src/descriptor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 59bb17670..a93504456 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1294,7 +1294,7 @@ fn shape_census(shape: &Shape, count: usize) { set.insert(w); } } - if count == 1000 || (count > 0 && count % 50_000 == 0) { + if count == 1000 || (count > 0 && count.is_multiple_of(50_000)) { let distinct: Vec = seen.iter().map(|s| s.len().to_string()).collect(); let last: Vec = words.iter().map(|w| format!("{w:x}")).collect(); tracing::info!( From 2f1dc9c85dad0083b3bdb65273b91ab7851b2f99 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:33:16 -0300 Subject: [PATCH 19/22] perf(gpu): make one empty texture block ahead when none is left Adapted from trustno1-coder/VIctory-NVIDIA#684 by @0xkn0wh3r3. --- crates/victory-gpu/src/pool.rs | 133 +++++++++++++++++++++++++++------ 1 file changed, 112 insertions(+), 21 deletions(-) diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 21904473d..f84e69101 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -449,11 +449,22 @@ fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { /// Two threads that both find no room may each make a block; the second /// is a block made ahead, or a spare that [`Pool::reclaim`] lets go. fn take_from( + pool: &'static Mutex>, + len: u64, + align: u64, + ripe: impl Fn() -> Ripe, + make: impl FnMut() -> Option, +) -> Option<(Piece, B, bool)> { + take_from_with(pool, len, align, ripe, make, None) +} + +fn take_from_with( pool: &'static Mutex>, len: u64, align: u64, ripe: impl Fn() -> Ripe, mut make: impl FnMut() -> Option, + on_none_empty: Option, ) -> Option<(Piece, B, bool)> { let first = ripe(); let mut p = lock(pool); @@ -479,6 +490,8 @@ fn take_from( p.making_ahead += 1; } let taken = p.taken(i, start, len, first); + let none_empty = + on_none_empty.is_some() && first.ahead == 0 && !p.blocks.iter().flatten().any(|b| b.free.whole(BLOCK)); drop(p); if ahead { /// Counts the block as made (or not) even if `make` unwinds. @@ -502,6 +515,8 @@ fn take_from( } None => p.failed_growth(now()), } + } else if none_empty && let Some(f) = on_none_empty { + f(); } taken } @@ -890,6 +905,63 @@ fn give_back_with(texture: &ID3D12Resource, piece: Piece, small: u64) { } } +/// A new block of texture memory, resident and mapped (waited for). +fn make_texture_block(device: &ID3D12Device) -> Option { + let desc = D3D12_HEAP_DESC { + SizeInBytes: BLOCK, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(), + }; + let mut heap: Option = None; + // SAFETY: plain creation. + if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } { + crate::residency::allocation_error(&e); + tracing::warn!(error = %e, "no block of texture memory"); + } + if let Some(h) = &heap + && let Err(e) = crate::host::resident(device, h).and_then(|()| crate::host::mapped(device)) + { + tracing::warn!(error = %e, "a block of texture memory is not resident"); + return None; + } + heap +} + +/// Whether one empty block of textures is kept made by a thread of ours, +/// for the next texture no block has room for (`VICTORY_BLOCK_AHEAD=0`: +/// none, the thread that needs it makes it, as before). +fn block_ahead() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BLOCK_AHEAD").is_none_or(|v| v != "0")) +} + +static MAKING_AHEAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static MADE_AHEAD: AtomicU64 = AtomicU64::new(0); + +/// Makes one empty block of textures on a thread of ours ([`block_ahead`]), +/// unless one is being made. +fn make_one_ahead() { + if !block_ahead() || !crate::resource::room_lately() || MAKING_AHEAD.swap(true, Ordering::AcqRel) { + return; + } + let made = std::thread::Builder::new().name("victory-block-ahead".into()).spawn(|| { + if let Some(host) = crate::host::host() + && let Some(heap) = make_texture_block(&host.device) + { + let mut pool = lock(&TEXTURES); + if !pool.blocks.iter().flatten().any(|b| b.free.whole(BLOCK)) { + pool.add(heap, crate::host::submissions().0); + MADE_AHEAD.fetch_add(1, Ordering::Relaxed); + } + } + MAKING_AHEAD.store(false, Ordering::Release); + }); + if made.is_err() { + MAKING_AHEAD.store(false, Ordering::Release); + } +} + /// A texture of `desc` (no target, depth or unordered access) in a block; /// `None`: not pooled, or the host refused. /// @@ -931,27 +1003,7 @@ pub(crate) unsafe fn texture( 0 }; #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] - let (piece, heap, again) = take_from(&TEXTURES, info.SizeInBytes, info.Alignment.max(1), Ripe::now, || { - let desc = D3D12_HEAP_DESC { - SizeInBytes: BLOCK, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - Alignment: 0, - Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(), - }; - let mut heap: Option = None; - // SAFETY: plain creation. - if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } { - crate::residency::allocation_error(&e); - tracing::warn!(error = %e, "no block of texture memory"); - } - if let Some(h) = &heap - && let Err(e) = crate::host::resident(device, h).and_then(|()| crate::host::mapped(device)) - { - tracing::warn!(error = %e, "a block of texture memory is not resident"); - return None; - } - heap - })?; + let (piece, heap, again) = take_from_with(&TEXTURES, info.SizeInBytes, info.Alignment.max(1), Ripe::now, || make_texture_block(device), Some(make_one_ahead))?; let mut made: Option = None; // SAFETY: the piece is no one else's; the heap lives while a piece of // it is taken. @@ -1308,4 +1360,43 @@ mod tests { assert!(host.device.GetDeviceRemovedReason().is_ok()); } } + + #[test] + fn an_empty_block_is_made_ahead_once_none_is_left() { + let Some(host) = crate::host::host() else { return }; + if !block_ahead() || ahead() != 0 || !crate::resource::room_lately() { + return; + } + let made_before = MADE_AHEAD.load(Ordering::Relaxed); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2048, + Height: 2048, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let empty = || lock(&TEXTURES).blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count(); + let mut held = Vec::new(); + for _ in 0..64 { + // SAFETY: a valid description. + held.extend(unsafe { texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }); + if empty() == 0 { + break; + } + } + let began = std::time::Instant::now(); + while empty() == 0 && began.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(empty() >= 1, "no block was made ahead"); + while MAKING_AHEAD.load(Ordering::Acquire) && began.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!MAKING_AHEAD.load(Ordering::Acquire), "the thread that makes it ahead did not end"); + assert!(MADE_AHEAD.load(Ordering::Relaxed) > made_before, "the empty block is not one made ahead"); + drop(held); + } } From d80e7c7eee55c63d227746504d35d4287450cdb1 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:36:48 -0300 Subject: [PATCH 20/22] perf(gpu): reduce TextureQueue lock hold time, TELL fallbacks, and zero-work locks Adapted from trustno1-coder/VIctory-NVIDIA#797 by @Capt-Speed. --- crates/victory-gpu/src/descriptor.rs | 144 ++- crates/victory-gpu/src/descriptor/host.rs | 1102 ++++++++++++++++++--- crates/victory-gpu/src/draw.rs | 14 +- 3 files changed, 1103 insertions(+), 157 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index a93504456..334ebe445 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -149,9 +149,12 @@ impl Heap { self.host .get_or_init(|| { let step = u64::from(increment(self.desc.kind)?); - let h = host::HostHeap::new(self.samplers(), self.desc.count)?; - for i in pending.drain(..) { - h.mirror(i, self.start + u64::from(i) * step, false); + let mut h = host::HostHeap::new(self.samplers(), self.desc.count)?; + { + let mut batch = host::QueueFlusher::new_unpublished(&mut h); + for i in pending.drain(..) { + batch.mirror(i, self.start + u64::from(i) * step, false); + } } Some(h) }) @@ -204,6 +207,12 @@ fn mirror(handle: u64) { let Some(index) = heap.index(handle) else { return; }; + if let Some(host) = heap.host.get() { + if let Some(host) = host { + host.mirror(index, handle, false); + } + return; + } let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner()); match heap.host.get() { None => pending.push(index), @@ -216,6 +225,85 @@ fn mirror(handle: u64) { } } +/// Mirrors `count` consecutive descriptors of stride `step` starting at `dst`, +/// hoisting the `SHADER_HEAPS` lookup when +/// `count > 1` and the range lies inside a single shader-visible heap. +#[cfg(windows)] +fn mirror_range(dst: u64, count: u32, step: u64) { + if count == 0 { + return; + } + if count == 1 { + mirror(dst); + return; + } + let Some(len) = u64::from(count).checked_mul(step) else { + return; + }; + let Some(range_end) = dst.checked_add(len) else { + return; + }; + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + let mut overlaps = heaps.iter().filter(|&&(start, end, _)| dst < end && start < range_end); + let Some(&(start, end, at)) = overlaps.next() else { + return; + }; + if dst < start || range_end > end || overlaps.next().is_some() { + drop(heaps); + for i in 0..u64::from(count) { + mirror(dst + i * step); + } + return; + }; + // SAFETY: registered heaps stay alive until `Heap::drop`, which takes + // the `SHADER_HEAPS` lock we hold here. + let heap = unsafe { &*(at as *const Heap) }; + let Some(first) = heap.index(dst) else { + return; + }; + let Some(heap_step) = increment(heap.desc.kind).map(u64::from) else { + return; + }; + if heap_step != step || dst - start != u64::from(first) * step { + drop(heaps); + for i in 0..u64::from(count) { + mirror(dst + i * step); + } + return; + } + if let Some(host) = heap.host.get() { + if let Some(host) = host { + for i in 0..count { + let index = first + i; + if index >= heap.desc.count { + break; + } + host.mirror(index, dst + u64::from(i) * step, false); + } + } + return; + } + let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner()); + match heap.host.get() { + None => { + let avail = heap.desc.count.saturating_sub(first).min(count); + pending.extend(first..first + avail); + } + Some(host) => { + drop(pending); + if let Some(host) = host { + for i in 0..count { + let index = first + i; + if index >= heap.desc.count { + break; + } + host.mirror(index, dst + u64::from(i) * step, false); + } + } + } + } +} + /// Whether [`sync_heaps`] is done (`VICTORY_HEAP_SYNC=0`: not). #[cfg(windows)] fn sync_on() -> bool { @@ -2007,9 +2095,7 @@ pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u6 std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; #[cfg(windows)] - for i in 0..u64::from(count) { - mirror(dst + i * step); - } + mirror_range(dst, count, step); } } @@ -2613,3 +2699,49 @@ mod tests { assert_ne!(slot:: u64>(h, 0x48)(h), address); } } + +#[cfg(all(test, windows))] +mod audit_regressions { + use super::*; + #[test] + fn audit_range_matches_individual_with_aliases() { + let memory = [0u64; 16]; + let start = memory.as_ptr() as u64; + let register = |start, count| { + let h = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc: HeapDesc { + kind: 0, + count, + flags: SHADER_VISIBLE, + nodes: 0, + }, + start, + memory: None, + host: Default::default(), + pending: Default::default(), + written: None, + }); + SHADER_HEAPS.write().unwrap().push(( + start, + start + u64::from(count) * 32, + &*h as *const Heap as usize, + )); + h + }; + let earlier = register(start + 32, 1); + let later = register(start, 3); + for i in 0..3 { + mirror(start + i * 32); + } + let take = || { + ( + std::mem::take(&mut *earlier.pending.lock().unwrap()), + std::mem::take(&mut *later.pending.lock().unwrap()), + ) + }; + let expected = take(); + mirror_range(start, 3, 32); + assert_eq!(take(), expected); + } +} diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 66caf5517..fdb3a7b87 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -212,6 +212,10 @@ pub(crate) struct HostHeap { textures: Mutex, /// What `textures` holds, read without its lock ([`QueueMarks`]). marks: std::sync::Arc, + /// Capacity hints for [`Due`] (`again`, `fresh`, `checked`), pre-allocated + /// before taking `textures`'s lock so steady-state passes avoid reallocs + /// inside the critical section. + due_hints: [std::sync::atomic::AtomicUsize; 3], /// Per title slot, the frame (plus one; 0: never) in which a draw last /// read it through a table, or made a table it lies in (with /// [`TABLED_READ`] set if the draw read it). The draw that @@ -1060,9 +1064,22 @@ pub(crate) fn tabled_reread() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_REREAD").is_some_and(|v| v == "1")) } -/// What the queue of textures picked by index knows of a title slot. +type FastMap = std::collections::HashMap>; + +/// Entry flag: the slot was uploaded whole and has a fingerprint in +/// [`TextureQueue::checked`] (`checked.2 != 0`). +const FLAG_CHECKED: u8 = 1 << 0; +/// Entry flag: the slot was uploaded in part and has a mapped-bytes count +/// (`>= 1`) in [`TextureQueue::mapped`]. +const FLAG_MAPPED: u8 = 1 << 1; +/// Sentinel index in [`Due::again`] meaning the slot has no [`Checked`] entry. +const NO_CHECKED: u32 = u32::MAX; + +/// Hot per-slot record in [`TextureQueue::entries`]: packed to 32 bytes so +/// scanning the queue for due slots touches half as many cache lines, with +/// cold recheck/partial-mapped fields split into side maps. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Waiting { +struct Entry { /// The frame from which the slot is due. due: u64, /// The frame it was written in. @@ -1070,28 +1087,27 @@ struct Waiting { /// Which write of the queue put it here: the pass hands it back with /// what it did, so a slot written again meanwhile stays as written. write: u64, + /// The title descriptor slot index. + index: u32, /// Looks in a row that found nothing to upload (its memory not mapped, /// or no more of it than at the last upload). looks: u8, - /// Bytes of its memory that were mapped when it was last uploaded - /// without all of it there; 0: not uploaded yet. - mapped: u64, - /// For a slot uploaded whole and looked at again - /// ([`TextureQueue::recheck`]): where its memory is (address, bytes), - /// the fingerprint it had at the upload, how many looks found it - /// unchanged, and the frame of the upload. A fingerprint of 0: none. - checked: (u64, u64, u64, u8, u64), + /// Bitmask of [`FLAG_CHECKED`] and [`FLAG_MAPPED`]. + flags: u8, } +const _: () = assert!(std::mem::size_of::() == 32); + /// Which title slots the queue of textures picked by index holds, readable -/// without its lock: for each slot the write number of its entry (0: none). -/// Changed only by the queue itself, under its lock; read without it by the -/// places that would change nothing if they took it: a slot's record noted -/// that takes out a slot the queue does not hold, or keeps one it holds -/// (`seen`); a table read or a stale view that takes out a slot it does not -/// hold. Whoever reads a mark while the queue changes it sees the slot as -/// it was just before or just after: as if it had taken the lock a moment -/// earlier or later, which it may always have done. +/// without its lock: for each slot the write number of its entry (0: none), +/// plus the queue's monotonic write counter and whether any slots are held +/// back for lack of card room. Changed only by the queue itself, under its +/// lock; read without it by the places that would change nothing if they took +/// it: a slot's record noted that takes out a slot the queue does not hold, +/// or keeps one it holds (`seen`); a table read or a stale view that takes +/// out a slot it does not hold. Whoever reads a mark while the queue changes +/// it sees the slot as it was just before or just after: as if it had taken +/// the lock a moment earlier or later, which it may always have done. /// /// The recording threads, the heaps' records thread and the draws note /// every slot record they make here: the line split by place (18ff932) says @@ -1100,17 +1116,25 @@ struct Waiting { /// 3.8-5.2 s of the pass: coolfox-20261126-232343, -233017). /// `VICTORY_QUEUE_MARKS=0`: the lock is taken every time, as before. #[derive(Default)] -pub(crate) struct QueueMarks(Box<[std::sync::atomic::AtomicU64]>); +pub(crate) struct QueueMarks { + slots: Box<[std::sync::atomic::AtomicU64]>, + writes: std::sync::atomic::AtomicU64, + has_held: std::sync::atomic::AtomicBool, +} impl QueueMarks { fn new(count: usize) -> Self { - QueueMarks((0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect()) + QueueMarks { + slots: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), + writes: std::sync::atomic::AtomicU64::new(0), + has_held: std::sync::atomic::AtomicBool::new(false), + } } /// Under the queue's lock: slot `index` holds the entry of write /// `write` (0: none). fn set(&self, index: u32, write: u64) { - if let Some(mark) = self.0.get(index as usize) { + if let Some(mark) = self.slots.get(index as usize) { mark.store(write, std::sync::atomic::Ordering::Release); } } @@ -1118,7 +1142,27 @@ impl QueueMarks { /// The write of slot `index`'s entry (0: none); `None`: not known here /// (past the marks), the queue knows. fn get(&self, index: u32) -> Option { - Some(self.0.get(index as usize)?.load(std::sync::atomic::Ordering::Acquire)) + Some(self.slots.get(index as usize)?.load(std::sync::atomic::Ordering::Acquire)) + } + + /// Under the queue's lock: records the latest write counter. + fn note_write(&self, write: u64) { + self.writes.store(write, std::sync::atomic::Ordering::Release); + } + + /// The queue's write counter, read without its lock. + fn writes(&self) -> u64 { + self.writes.load(std::sync::atomic::Ordering::Acquire) + } + + /// Under the queue's lock: records whether any slots are held back. + fn set_held(&self, held: bool) { + self.has_held.store(held, std::sync::atomic::Ordering::Release); + } + + /// Whether any slots are currently held back for lack of card room. + fn has_held(&self) -> bool { + self.has_held.load(std::sync::atomic::Ordering::Acquire) } } @@ -1196,15 +1240,28 @@ fn host_texture_left_out() { /// The queue of title slots whose texture view waits to be brought up to /// date for shaders that pick textures by index: which are due, and in /// which order (no host heap needed, so it is tested without one). +/// +/// Dense `entries` + `by_slot` index keeps full-queue scans contiguous in +/// cache and slot updates O(1); cold recheck and partial-mapped metadata live +/// in side maps keyed by slot and guarded by entry flags. #[derive(Default)] pub(crate) struct TextureQueue { - slots: std::collections::BTreeMap, - writes: u64, + /// Dense 32-byte hot entries; `by_slot[index] == pos` iff + /// `entries[pos].index == index`. + entries: Vec, + by_slot: FastMap, + /// Cold metadata for slots uploaded whole and waiting for a look again; + /// contains `index` iff the entry's [`FLAG_CHECKED`] bit is set (`c.2 != 0`). + checked: FastMap, + /// Cold metadata for slots uploaded in part (`>= 1` mapped bytes); + /// contains `index` iff the entry's [`FLAG_MAPPED`] bit is set. + mapped: FastMap, /// Slots held back because the card had no room for the host copy /// they need ([`TextureQueue::hold`]), each with the write it was /// held as. - held: std::collections::BTreeMap, - /// What `slots` holds, for reading without the lock (the host heap + held: FastMap, + writes: u64, + /// What the queue holds, for reading without the lock (the host heap /// keeps the same; none in tests made without a heap). marks: std::sync::Arc, } @@ -1215,19 +1272,51 @@ impl TextureQueue { TextureQueue { marks, ..Default::default() } } - /// Slot `index` holds `waiting` now. - fn put(&mut self, index: u32, waiting: Waiting) { - self.marks.set(index, waiting.write); - self.slots.insert(index, waiting); + fn entry(&self, index: u32) -> Option<&Entry> { + let &pos = self.by_slot.get(&index)?; + Some(&self.entries[pos as usize]) + } + + /// Slot `index` holds fresh `entry` (`flags == 0`) now. + fn put(&mut self, index: u32, entry: Entry) { + debug_assert_eq!(entry.index, index); + debug_assert_eq!(entry.flags, 0); + self.marks.set(index, entry.write); + if let Some(&pos) = self.by_slot.get(&index) { + let slot = &mut self.entries[pos as usize]; + let old_flags = slot.flags; + *slot = entry; + if old_flags & FLAG_CHECKED != 0 { + self.checked.remove(&index); + } + if old_flags & FLAG_MAPPED != 0 { + self.mapped.remove(&index); + } + } else { + let pos = self.entries.len() as u32; + self.entries.push(entry); + self.by_slot.insert(index, pos); + } } /// Slot `index` leaves the queue; whether it was there. fn take_out(&mut self, index: u32) -> bool { - let was = self.slots.remove(&index).is_some(); - if was { - self.marks.set(index, 0); + let Some(pos) = self.by_slot.remove(&index) else { + return false; + }; + let removed = self.entries.swap_remove(pos as usize); + debug_assert_eq!(removed.index, index); + if let Some(moved) = self.entries.get(pos as usize) { + self.by_slot.insert(moved.index, pos); + } + if removed.flags & FLAG_CHECKED != 0 { + self.checked.remove(&index); + } + if removed.flags & FLAG_MAPPED != 0 { + self.mapped.remove(&index); } - was + self.marks.set(index, 0); + true } /// A texture view was written into slot `index` in `frame`, due from @@ -1235,12 +1324,13 @@ impl TextureQueue { /// the host slot from a view the queue may hold already, which then /// stays as it is. fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) { - if seen && self.slots.contains_key(&index) { + if seen && self.by_slot.contains_key(&index) { return; } self.writes += 1; let write = self.writes; - self.put(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + self.marks.note_write(write); + self.put(index, Entry { due, written: frame, write, index, looks: 0, flags: 0 }); } fn remove(&mut self, index: u32) { @@ -1266,38 +1356,88 @@ impl TextureQueue { /// [`TextureQueue::due`]'s slots, not in order yet, and /// [`TextureQueue::census`], in one look at every slot: what the queue's /// lock is held for. The order is made after it is let go - /// ([`Due::order`]). Ordered under the lock, the queue of some 40,000 + /// ([`Due::ordered`]). Ordered under the lock, the queue of some 40,000 /// slots in the first gameplay area kept it 1-5 ms a pass, and the /// title's recording threads, whose every descriptor copy notes its slot /// here, waited that long behind it (run timeline, 2026-11-26). - fn due_and_census(&self, frame: u64) -> (Due, [u64; 6]) { - let mut due = Due::default(); - let mut c = [self.slots.len() as u64, 0, 0, 0, 0, 0]; - for (&index, w) in &self.slots { - let again = w.checked.2 != 0; - if w.mapped > 0 { + fn collect_due_and_census(&self, frame: u64, due: &mut Due) -> [u64; 6] { + let mut c = [self.entries.len() as u64, 0, 0, 0, 0, 0]; + for e in &self.entries { + let mapped = e.flags & FLAG_MAPPED != 0; + let again = e.flags & FLAG_CHECKED != 0; + if mapped { c[3] += 1; } else if again { c[5] += 1; - } else if w.looks > 0 { + } else if e.looks > 0 { c[2] += 1; } - if w.due <= frame { + if e.due <= frame { c[1] += 1; if !again { - c[4] = c[4].max(frame.saturating_sub(w.written)); + c[4] = c[4].max(frame.saturating_sub(e.written)); } - if w.looks > 0 || w.mapped > 0 { + if e.looks > 0 || mapped { // (Only these can wait for a look again: `recheck` // leaves a look, `partly` some bytes mapped.) - due.again.push((w.written, index, w.write, Some(w.checked).filter(|c| c.2 != 0))); + let checked_pos = if again { + if let Some(&checked) = self.checked.get(&e.index) { + let pos = due.checked.len() as u32; + due.checked.push(checked); + pos + } else { + NO_CHECKED + } + } else { + NO_CHECKED + }; + due.again.push((e.index, e.write, checked_pos)); } else { - due.fresh.push((w.written, index, w.write)); + due.fresh.push((e.index, e.write)); } } } + c + } + + #[cfg(test)] + fn due_and_census(&self, frame: u64) -> (Due, [u64; 6]) { + let mut due = Due::default(); + let c = self.collect_due_and_census(frame, &mut due); (due, c) } + + /// Every queued slot due at `frame`, and whether it was already uploaded + /// (in part, or whole and waiting for another look). + fn all_due(&self, frame: u64) -> Vec<(u32, bool)> { + self.entries + .iter() + .filter(|e| e.due <= frame) + .map(|e| (e.index, e.flags & (FLAG_MAPPED | FLAG_CHECKED) != 0)) + .collect() + } + + /// Whether slot `index` was already uploaded before (out of the queue, or + /// queued after an upload in part or whole). + fn was_uploaded(&self, index: u32) -> bool { + self.entry(index).is_none_or(|e| e.flags & (FLAG_MAPPED | FLAG_CHECKED) != 0) + } + + /// Diagnostic description of slot `index` at `frame`. + #[cfg(feature = "diagnostics")] + fn slot_state(&self, index: u32, frame: u64) -> String { + match self.entry(index) { + None => "not queued".into(), + Some(e) => format!( + "queued due={} written@{} looks={} part_mapped={} recheck={}", + if e.due <= frame { "now".to_string() } else { format!("@{}", e.due) }, + e.written, + e.looks, + self.mapped(index), + e.flags & FLAG_CHECKED != 0 + ), + } + } } /// What [`TextureQueue::recheck`] noted of a slot uploaded whole: where its @@ -1321,16 +1461,28 @@ pub(crate) enum Told { Held(u64), } -/// The slots due, taken from the queue ([`TextureQueue::due_and_census`]): -/// (frame written, slot, write number) of those looked at before, with what -/// [`TextureQueue::checked`] says of them, and of the others. +/// The slots due, taken from the queue ([`TextureQueue::collect_due_and_census`]): +/// `(slot, write, checked_pos_or_NO_CHECKED)` of those looked at before, +/// `(slot, write)` of the others, and the side table of [`Checked`] records. #[derive(Default)] struct Due { - again: Vec<(u64, u32, u64, Option)>, - fresh: Vec<(u64, u32, u64)>, + again: Vec<(u32, u64, u32)>, + fresh: Vec<(u32, u64)>, + checked: Vec, } +const _: () = assert!(std::mem::size_of::<(u32, u64, u32)>() == 16); +const _: () = assert!(std::mem::size_of::<(u32, u64)>() == 16); + impl Due { + fn with_capacity(again: usize, fresh: usize, checked: usize) -> Self { + Due { + again: Vec::with_capacity(again), + fresh: Vec::with_capacity(fresh), + checked: Vec::with_capacity(checked), + } + } + /// Up to `max` of them, in the order [`TextureQueue::due`] serves them. #[cfg(test)] fn order(self, max: usize) -> Vec<(u32, u64)> { @@ -1346,60 +1498,105 @@ impl Due { } fn ordered_with(self, max: usize, fresh_first: bool) -> (Vec<(u32, u64)>, Vec>) { - let Due { mut again, mut fresh } = self; - // By the number of the write, counted over the run. - again.sort_unstable_by_key(|e| std::cmp::Reverse(e.2)); - fresh.sort_unstable_by_key(|e| std::cmp::Reverse(e.2)); - let mut order: Vec<(u32, u64)> = Vec::with_capacity(max.min(again.len() + fresh.len())); - let mut known: Vec> = Vec::with_capacity(max.min(again.len() + fresh.len())); - let push_fresh = |order: &mut Vec<(u32, u64)>, known: &mut Vec>| { - let (mut new, mut old) = (0, fresh.len()); - while new < old && order.len() < max { - order.push((fresh[new].1, fresh[new].2)); - known.push(None); - new += 1; - if new < old && order.len() < max { - old -= 1; - order.push((fresh[old].1, fresh[old].2)); - known.push(None); + if max == 0 { + return (Vec::new(), Vec::new()); + } + let Due { mut again, mut fresh, checked } = self; + let cap = (again.len() + fresh.len()).min(max); + let mut order: Vec<(u32, u64)> = Vec::with_capacity(cap); + let mut known: Vec> = Vec::with_capacity(cap); + let push_fresh = |fresh: &mut Vec<(u32, u64)>, order: &mut Vec<(u32, u64)>, known: &mut Vec>| { + let need = max.saturating_sub(order.len()); + if need == 0 || fresh.is_empty() { + return; + } + if fresh.len() > need { + // Only select the `top_n` newest and `bot_n` oldest entries + // instead of sorting the entire fresh backlog. + let top_n = need.div_ceil(2); + let bot_n = need / 2; + fresh.select_nth_unstable_by_key(top_n, |e| std::cmp::Reverse(e.1)); + let (top, rest) = fresh.split_at_mut(top_n); + top.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + if bot_n > 0 { + rest.select_nth_unstable_by_key(bot_n, |e| e.1); + let bot = &mut rest[..bot_n]; + bot.sort_unstable_by_key(|e| e.1); + for i in 0..bot_n { + order.push(top[i]); + order.push(bot[i]); + } + } + if top_n > bot_n { + order.push(top[bot_n]); + } + } else { + fresh.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push(fresh[new]); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push(fresh[old]); + } } } + known.resize(order.len(), None); }; - let push_again = |order: &mut Vec<(u32, u64)>, known: &mut Vec>, recheck: Option| { - for &(_, index, write, checked) in &again { + let push_again = |again: &[(u32, u64, u32)], + order: &mut Vec<(u32, u64)>, + known: &mut Vec>, + recheck: Option| { + for &(index, write, checked_pos) in again { if order.len() >= max { break; } - if recheck.is_none_or(|want| checked.is_some() == want) { + let is_recheck = checked_pos != NO_CHECKED; + if recheck.is_none_or(|want| is_recheck == want) { order.push((index, write)); - known.push(checked); + known.push(is_recheck.then(|| checked[checked_pos as usize])); } } }; if fresh_first { - push_fresh(&mut order, &mut known); - push_again(&mut order, &mut known, None); + push_fresh(&mut fresh, &mut order, &mut known); + let need = max.saturating_sub(order.len()); + if need > 0 && !again.is_empty() { + if again.len() > need { + again.select_nth_unstable_by_key(need, |e| std::cmp::Reverse(e.1)); + again.truncate(need); + } + again.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + push_again(&again, &mut order, &mut known, None); + } } else { - // Unuploaded retries (`later`/`partly`) first, then `fresh` - // never-uploaded slots, then already-uploaded `recheck` slots so - // thousands of `recheck` slots cannot starve `fresh` textures. - push_again(&mut order, &mut known, Some(false)); - push_fresh(&mut order, &mut known); - push_again(&mut order, &mut known, Some(true)); + again.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + push_again(&again, &mut order, &mut known, Some(false)); + push_fresh(&mut fresh, &mut order, &mut known); + push_again(&again, &mut order, &mut known, Some(true)); } (order, known) } } impl TextureQueue { + /// Position of `index` in `self.entries` if it is still the write the pass + /// was handed. + fn same_pos(&self, index: u32, write: u64) -> Option { + let &pos = self.by_slot.get(&index)?; + (self.entries[pos as usize].write == write).then_some(pos as usize) + } + /// The entry of `index` if it is still the write the pass was handed. - fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> { - self.slots.get_mut(&index).filter(|w| w.write == write) + fn same(&mut self, index: u32, write: u64) -> Option<&mut Entry> { + let pos = self.same_pos(index, write)?; + Some(&mut self.entries[pos]) } /// Slot `index` is up to date: out of the queue until written again. fn done(&mut self, index: u32, write: u64) { - if self.same(index, write).is_some() { + if self.same_pos(index, write).is_some() { self.take_out(index); } } @@ -1407,9 +1604,9 @@ impl TextureQueue { /// Nothing to upload at slot `index` now: looked at again after 1, 2, /// 4, ... frames, at most `most`. fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) { - if let Some(w) = self.same(index, write) { - w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1)); - w.looks = w.looks.saturating_add(1); + if let Some(e) = self.same(index, write) { + e.due = frame + (1u64 << e.looks.min(16)).min(most.max(1)); + e.looks = e.looks.saturating_add(1); } } @@ -1424,20 +1621,26 @@ impl TextureQueue { /// to date, and the ones whose memory went, which is what lets host /// copies go and makes room.) fn hold(&mut self, index: u32, write: u64, due: u64) { - if let Some(w) = self.same(index, write) { - w.due = w.due.max(due); + if let Some(pos) = self.same_pos(index, write) { + let e = &mut self.entries[pos]; + e.due = e.due.max(due); self.held.insert(index, write); + self.marks.set_held(true); } } /// The card has room again at `frame`: the slots held back for lack of /// it are due now, as if they had never been held. Returns how many. fn room(&mut self, frame: u64) -> usize { + if self.held.is_empty() { + return 0; + } let held = std::mem::take(&mut self.held); + self.marks.set_held(false); let mut back = 0; for (index, write) in held { - if let Some(w) = self.same(index, write) { - w.due = w.due.min(frame); + if let Some(e) = self.same(index, write) { + e.due = e.due.min(frame); back += 1; } } @@ -1447,8 +1650,12 @@ impl TextureQueue { /// Slot `index` was uploaded with `mapped` bytes of its memory there, /// not all of it: looked at again from frame `due`. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { - if let Some(w) = self.same(index, write) { - (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1)); + if let Some(pos) = self.same_pos(index, write) { + let e = &mut self.entries[pos]; + e.due = due; + e.looks = 0; + e.flags |= FLAG_MAPPED; + self.mapped.insert(index, mapped.max(1)); } } @@ -1458,16 +1665,28 @@ impl TextureQueue { /// `looks`-th such look; `uploaded` is the upload's frame). #[allow(clippy::too_many_arguments)] fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { - if let Some(w) = self.same(index, write) { - (w.due, w.looks, w.mapped) = (due, 1, 0); - w.checked = (at.0, at.1, print, looks, uploaded); + if let Some(pos) = self.same_pos(index, write) { + let e = &mut self.entries[pos]; + e.due = due; + e.looks = 1; + if e.flags & FLAG_MAPPED != 0 { + e.flags &= !FLAG_MAPPED; + self.mapped.remove(&index); + } + if print != 0 { + e.flags |= FLAG_CHECKED; + self.checked.insert(index, (at.0, at.1, print, looks, uploaded)); + } else if e.flags & FLAG_CHECKED != 0 { + e.flags &= !FLAG_CHECKED; + self.checked.remove(&index); + } } } /// What [`TextureQueue::recheck`] noted of slot `index`, if it is /// waiting for such a look. fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { - self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) + self.checked.get(&index).copied() } /// The memory slot `index`'s texture lies in was mapped, unmapped or @@ -1477,18 +1696,19 @@ impl TextureQueue { fn changed(&mut self, index: u32, frame: u64, due: u64) { self.writes += 1; let write = self.writes; - let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); - self.put(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + self.marks.note_write(write); + let due = self.entry(index).map_or(due, |e| e.due.min(due)); + self.put(index, Entry { due, written: frame, write, index, looks: 0, flags: 0 }); } /// Bytes of slot `index`'s memory that were mapped at its last upload /// (0: not uploaded, or all of it was). fn mapped(&self, index: u32) -> u64 { - self.slots.get(&index).map_or(0, |w| w.mapped) + self.mapped.get(&index).copied().unwrap_or(0) } /// For the frame line (made with the slots due, by - /// [`TextureQueue::due_and_census`]): slots in the queue; of them due at `frame`; + /// [`TextureQueue::collect_due_and_census`]): slots in the queue; of them due at `frame`; /// waiting for their memory (looked at, never uploaded); uploaded in /// part; the frames the oldest due one not uploaded yet has waited /// since its write; and the slots uploaded whole that wait for a look @@ -1497,22 +1717,22 @@ impl TextureQueue { /// cutscene's 19,277 "waiting for their memory" were such slots, /// coolfox-20261126-223059 17:02:04, where 1,700 looks in all had found /// memory not there.) - #[cfg(test)] fn census(&self, frame: u64) -> [u64; 6] { - let mut c = [self.slots.len() as u64, 0, 0, 0, 0, 0]; - for w in self.slots.values() { - let again = w.checked.2 != 0; - if w.mapped > 0 { + let mut c = [self.entries.len() as u64, 0, 0, 0, 0, 0]; + for e in &self.entries { + let mapped = e.flags & FLAG_MAPPED != 0; + let again = e.flags & FLAG_CHECKED != 0; + if mapped { c[3] += 1; } else if again { c[5] += 1; - } else if w.looks > 0 { + } else if e.looks > 0 { c[2] += 1; } - if w.due <= frame { + if e.due <= frame { c[1] += 1; if !again { - c[4] = c[4].max(frame.saturating_sub(w.written)); + c[4] = c[4].max(frame.saturating_sub(e.written)); } } } @@ -1526,16 +1746,16 @@ impl TextureQueue { /// memory not there, by the frames since its write. fn note_served(&self, index: u32, write: u64, frame: u64) { use std::sync::atomic::Ordering::Relaxed; - let Some(w) = self.slots.get(&index).filter(|w| w.write == write) else { + let Some(e) = self.entry(index).filter(|e| e.write == write) else { return; }; - if w.mapped > 0 || w.checked.2 != 0 { + if e.flags & (FLAG_MAPPED | FLAG_CHECKED) != 0 { return; } - let (which, frames) = if w.looks == 0 { - (0, frame.saturating_sub(w.due.max(w.written))) + let (which, frames) = if e.looks == 0 { + (0, frame.saturating_sub(e.due.max(e.written))) } else { - (3, frame.saturating_sub(w.written)) + (3, frame.saturating_sub(e.written)) }; SERVED[which].fetch_add(1, Relaxed); SERVED[which + 1].fetch_add(frames, Relaxed); @@ -1543,6 +1763,97 @@ impl TextureQueue { } } +/// Deferred [`TextureQueue`] update buffered by [`QueueBatch`] to amortize +/// `WRITE` lock acquisitions across bulk descriptor mirroring loops. +#[derive(Clone, Copy, Debug)] +enum QueueOp { + Write { index: u32, frame: u64, due: u64, seen: bool }, + /// Conditional removal guarded by the `write` number observed under the + /// slot's [`Made`] lock so a concurrent newer write is never clobbered. + RemoveIf { index: u32, write: u64 }, +} + +impl QueueOp { + fn index(self) -> u32 { + match self { + QueueOp::Write { index, .. } | QueueOp::RemoveIf { index, .. } => index, + } + } +} + +/// Per-loop buffer of [`TextureQueue`] `WRITE` operations flushed under a +/// single lock acquisition once [`QueueBatch::LIMIT`] ops accumulate or when +/// flushed explicitly (prefer [`QueueFlusher`] so early returns always flush). +#[derive(Default)] +pub(crate) struct QueueBatch { + ops: Vec, + /// 64-bit bloom filter of `1u64 << (index & 63)` for buffered ops: zero + /// false positives for sequential ranges up to [`Self::LIMIT`]. + seen_bits: u64, +} + +impl QueueBatch { + const LIMIT: usize = 64; + + fn has_slot(&self, index: u32) -> bool { + let bit = 1u64 << (index & 63); + self.seen_bits & bit != 0 && self.ops.iter().any(|op| op.index() == index) + } + + fn push(&mut self, host: &HostHeap, op: QueueOp) { + self.seen_bits |= 1u64 << (op.index() & 63); + self.ops.push(op); + if self.ops.len() >= Self::LIMIT { + self.flush(host); + } + } + + fn apply(&mut self, textures: &mut TextureQueue) { + self.seen_bits = 0; + for op in self.ops.drain(..) { + match op { + QueueOp::Write { index, frame, due, seen } => { + textures.written(index, frame, due, seen); + } + QueueOp::RemoveIf { index, write } => { + textures.done(index, write); + } + } + } + } + + pub(crate) fn flush(&mut self, host: &HostHeap) { + if self.ops.is_empty() { + return; + } + let mut textures = host.queue(super::queue_site::WRITE); + self.apply(&mut textures); + } +} + +/// Scoped guard pairing a [`QueueBatch`] with its [`HostHeap`], flushing any +/// buffered queue ops automatically on drop. +pub(crate) struct QueueFlusher<'a> { + host: &'a HostHeap, + batch: QueueBatch, +} + +impl<'a> QueueFlusher<'a> { + pub(crate) fn new_unpublished(host: &'a mut HostHeap) -> Self { + QueueFlusher { host, batch: QueueBatch::default() } + } + + pub(crate) fn mirror(&mut self, index: u32, handle: u64, for_draw: bool) -> Option { + self.host.mirror_batched(index, handle, for_draw, &mut self.batch) + } +} + +impl Drop for QueueFlusher<'_> { + fn drop(&mut self) { + self.batch.flush(self.host); + } +} + /// Slots of textures picked by index the pass served for the first time, /// since the last 5-second line: at their first look, with the frames they /// had been due before the pass took them (in all, and the most); after @@ -2127,6 +2438,7 @@ impl HostHeap { changed: Slots::new(count as usize), textures: Mutex::new(TextureQueue::with_marks(marks.clone())), marks, + due_hints: [const { std::sync::atomic::AtomicUsize::new(0) }; 3], tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), @@ -2368,8 +2680,8 @@ impl HostHeap { /// ([`TextureQueue::census`]). #[cfg(test)] pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 6]) { - let (due, census) = self.queue(super::queue_site::DUE).due_and_census(frame); - (if max == 0 { Vec::new() } else { due.order(max) }, census) + let (order, _, census) = self.texture_slots_due_known(frame, max); + (order, census) } /// Up to `max` title slots whose texture view is due at `frame`, each @@ -2379,8 +2691,21 @@ impl HostHeap { /// the lock (the pass asked it slot by slot, under the lock each time); /// and the queue's counts ([`TextureQueue::census`]). pub(crate) fn texture_slots_due_known(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, Vec>, [u64; 6]) { - let (due, census) = self.queue(super::queue_site::DUE).due_and_census(frame); - let (order, known) = if max == 0 { (Vec::new(), Vec::new()) } else { due.ordered(max) }; + if max == 0 { + let census = self.queue(super::queue_site::DUE).census(frame); + return (Vec::new(), Vec::new(), census); + } + let hints = self.due_hints.each_ref().map(|h| h.load(Ordering::Relaxed)); + let mut due = Due::with_capacity(hints[0], hints[1], hints[2]); + let census = { + let textures = self.queue(super::queue_site::DUE); + textures.collect_due_and_census(frame, &mut due) + }; + let next_hint = |n: usize| if n == 0 { 0 } else { n.saturating_add((n >> 3).max(16)) }; + self.due_hints[0].store(next_hint(due.again.len()), Ordering::Relaxed); + self.due_hints[1].store(next_hint(due.fresh.len()), Ordering::Relaxed); + self.due_hints[2].store(next_hint(due.checked.len()), Ordering::Relaxed); + let (order, known) = due.ordered(max); (order, known, census) } @@ -2424,7 +2749,11 @@ impl HostHeap { /// A number that changes when a slot is written or made due anew, and /// whether memory was noted since a pass last took the notes. pub(crate) fn texture_news(&self) -> (u64, bool) { - let writes = self.queue(super::queue_site::OTHER).writes; + let writes = if queue_marks() { + self.marks.writes() + } else { + self.queue(super::queue_site::OTHER).writes + }; let noted = |ranges: &Mutex>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN)) } @@ -2434,13 +2763,9 @@ impl HostHeap { /// look): for the card accounting line /// (`crate::resource::card_accounting`). pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { - let textures = self.queue(super::queue_site::OTHER); - textures - .slots - .iter() - .filter(|(_, w)| w.due <= frame) - .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0)) - .collect() + let mut out = self.queue(super::queue_site::OTHER).all_due(frame); + out.sort_unstable_by_key(|&(index, _)| index); + out } /// The texture view of title slot `index` (as handed out with `write`) @@ -2493,6 +2818,9 @@ impl HostHeap { /// See [`TextureQueue::room`]. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { + if queue_marks() && !self.marks.has_held() { + return 0; + } self.queue(super::queue_site::MADE_DUE).room(frame) } @@ -2527,6 +2855,9 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); + if slots.is_empty() { + return 0; + } let mut textures = self.queue(super::queue_site::MADE_DUE); for &slot in &slots { textures.changed(slot, frame, frame + 1); @@ -2552,6 +2883,9 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); + if slots.is_empty() { + return 0; + } let mut textures = self.queue(super::queue_site::MADE_DUE); for &slot in &slots { textures.changed(slot, frame, frame + 1); @@ -2612,8 +2946,11 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); + if slots.is_empty() { + return 0; + } let mut textures = self.queue(super::queue_site::MADE_DUE); - slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + slots.retain(|&slot| textures.was_uploaded(slot)); for &slot in &slots { textures.changed(slot, frame, frame); } @@ -2633,10 +2970,13 @@ impl HostHeap { slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); let held = slots.len(); + if held == 0 { + return [0, 0, 0]; + } let mut textures = self.queue(super::queue_site::MADE_DUE); // Uploaded before: out of the queue, or in it after an upload (in // part, or whole and being looked at again). - slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + slots.retain(|&slot| textures.was_uploaded(slot)); PAGE_WRITES[2].fetch_add(held as u64, Relaxed); PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed); if !due { @@ -2723,6 +3063,9 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); + if slots.is_empty() { + return 0; + } let mut textures = self.queue(super::queue_site::MADE_DUE); for &slot in &slots { textures.changed(slot, frame, frame + 1); @@ -3330,7 +3673,26 @@ impl HostHeap { /// The queue's part of a write of title slot `index` in `frame`: /// `texture`, whether it now holds a view of a texture the title may /// fill; `seen` as for [`HostHeap::note_buffer`]. + #[cfg(test)] fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { + self.queue_texture_inner(index, texture, seen, frame, None); + } + + fn queue_texture_inner( + &self, + index: u32, + texture: bool, + seen: bool, + frame: u64, + mut batch: Option<&mut QueueBatch>, + ) { + // If `batch` already buffers an earlier op for `index`, flush first so + // `self.marks` and `self.queued` reflect that prior op before we decide. + if let Some(batch) = batch.as_deref_mut() + && batch.has_slot(index) + { + batch.flush(self); + } let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; let now = (frame as u32).wrapping_add(1) & !TABLED_READ; // A table's slot lately: the draw that reads it uploads its @@ -3353,6 +3715,31 @@ impl HostHeap { not_taken(super::queue_site::WRITE); return; } + if let Some(batch) = batch { + if keeps { + let due = if lately && !seen { + TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + frame + TABLED_GRACE + } else { + 0 + }; + batch.push(self, QueueOp::Write { index, frame, due, seen }); + return; + } + // Capture the write number under the slot's `Made` lock so a + // deferred removal can never clobber a newer concurrent write. + match self.texture_slot_write(index) { + Some(0) => { + not_taken(super::queue_site::WRITE); + return; + } + Some(write) => { + batch.push(self, QueueOp::RemoveIf { index, write }); + return; + } + None => {} + } + } let mut textures = self.queue(super::queue_site::WRITE); if keeps { let due = if lately && !seen { @@ -3401,6 +3788,16 @@ impl HostHeap { /// caller's to make null when it has let go of its own slot's lock /// ([`HostHeap::unmake_stale`]). fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<(u32, u64)> { + self.note_buffer_inner(index, view, seen, None) + } + + fn note_buffer_inner( + &self, + index: u32, + view: Option<&View>, + seen: bool, + mut batch: Option<&mut QueueBatch>, + ) -> Vec<(u32, u64)> { if self.sampler { return Vec::new(); } @@ -3424,7 +3821,7 @@ impl HostHeap { } _ => false, }; - self.queue_texture(index, texture, seen, crate::frame::current()); + self.queue_texture_inner(index, texture, seen, crate::frame::current(), batch.as_deref_mut()); // The memory a placed texture view describes. Not for a slot // tables read (thousands of writes a frame, each read by its // draw): no pass looks at it, and the same texture's view in a @@ -3478,6 +3875,12 @@ impl HostHeap { } }; if !stale.is_empty() { + // Flush any buffered writes from this batch before checking marks + // and removing stale slots, so an earlier write in the same batch + // cannot resurrect a stale slot after this removal. + if let Some(batch) = batch { + batch.flush(self); + } STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); // Only the ones the queue may hold. let queued: Vec = stale.iter().map(|&(slot, _)| slot).filter(|&slot| self.queued(slot) != Some(false)).collect(); @@ -3976,6 +4379,28 @@ impl HostHeap { /// views are made only for draws (`for_draw`), which also copy their /// data: a host copy of a buffer is made on first use. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { + self.mirror_inner(index, handle, for_draw, None) + } + + /// As [`HostHeap::mirror`], buffering [`TextureQueue`] `WRITE` updates into + /// `batch` to reduce lock contention across bulk descriptor loops. + pub(crate) fn mirror_batched( + &self, + index: u32, + handle: u64, + for_draw: bool, + batch: &mut QueueBatch, + ) -> Option { + self.mirror_inner(index, handle, for_draw, Some(batch)) + } + + fn mirror_inner( + &self, + index: u32, + handle: u64, + for_draw: bool, + batch: Option<&mut QueueBatch>, + ) -> Option { if index >= self.count { // Diagnostic (NVIDIA heap cap): the highest title slot past the // host heap seen so far. @@ -4015,10 +4440,10 @@ impl HostHeap { self.quick_is(index, 0); self.made.set(index, 0); self.make_null(index); - let _ = self.note_buffer(index, None, false); + let _ = self.note_buffer_inner(index, None, false, batch); } else if for_draw { // Left for later and stale since: out of the sets and the stride table. - let _ = self.note_buffer(index, None, false); + let _ = self.note_buffer_inner(index, None, false, batch); } return None; }; @@ -4027,7 +4452,7 @@ impl HostHeap { // are stale: their host slots read nothing from here on, and // let go of the host copies they held. // (When this slot's lock is let go: a lock at a time.) - let stale = self.note_buffer(index, Some(&view), for_draw); + let stale = self.note_buffer_inner(index, Some(&view), for_draw, batch); // A view of a texture object that has no host copy yet waits // for it, as buffer views wait for a draw: the slot is made // when the texture is first used (`super::make_waiting`), or @@ -4168,18 +4593,7 @@ impl HostHeap { /// `index` at `frame`, in a few words (diagnostics). #[cfg(feature = "diagnostics")] pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { - let textures = self.queue(super::queue_site::OTHER); - match textures.slots.get(&index) { - None => "not queued".into(), - Some(w) => format!( - "queued due={} written@{} looks={} part_mapped={} recheck={}", - if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, - w.written, - w.looks, - w.mapped, - w.checked.2 != 0 - ), - } + self.queue(super::queue_site::OTHER).slot_state(index, frame) } /// The view host slot `index` was made from, in a few words, with the @@ -6336,12 +6750,13 @@ mod tests { #[test] fn due_fresh_first_prevents_again_starvation() { let mut due = Due::default(); - due.again.push((1, 100, 10, None)); - due.again.push((2, 101, 11, None)); - due.fresh.push((3, 200, 12)); + due.again.push((100, 10, NO_CHECKED)); + due.again.push((101, 11, NO_CHECKED)); + due.fresh.push((200, 12)); let (again_first, _) = Due { again: due.again.clone(), fresh: due.fresh.clone(), + checked: due.checked.clone(), } .ordered_with(2, false); assert_eq!(again_first, [(101, 11), (100, 10)]); @@ -6855,6 +7270,304 @@ mod tests { assert!(plain.take_out(40)); } + /// Dense swap-remove, in-place overwrite, cold `checked` (both `print != 0` + /// and `print == 0`) and `mapped` side maps, and lock-free `QueueMarks` + /// shadows (`writes`, `has_held`) all stay strictly consistent. + #[test] + fn dense_texture_queue_invariants_and_cold_maps() { + let marks = std::sync::Arc::new(QueueMarks::new(64)); + let mut q = TextureQueue::with_marks(marks.clone()); + let check_invariants = |q: &TextureQueue| { + assert_eq!(q.entries.len(), q.by_slot.len()); + assert_eq!(q.marks.writes(), q.writes); + assert_eq!(q.marks.has_held(), !q.held.is_empty()); + let mut checked_count = 0usize; + let mut mapped_count = 0usize; + for (pos, e) in q.entries.iter().enumerate() { + assert_eq!(q.by_slot.get(&e.index), Some(&(pos as u32))); + assert_eq!(q.marks.get(e.index), Some(e.write)); + if e.flags & FLAG_CHECKED != 0 { + checked_count += 1; + let c = q.checked.get(&e.index).expect("FLAG_CHECKED must be in checked map"); + assert_ne!(c.2, 0); + } else { + assert!(!q.checked.contains_key(&e.index)); + } + if e.flags & FLAG_MAPPED != 0 { + mapped_count += 1; + let &m = q.mapped.get(&e.index).expect("FLAG_MAPPED must be in mapped map"); + assert!(m >= 1); + } else { + assert!(!q.mapped.contains_key(&e.index)); + } + } + assert_eq!(q.checked.len(), checked_count); + assert_eq!(q.mapped.len(), mapped_count); + for at in [0, 5, 10, 25, u64::MAX] { + assert_eq!(q.due_and_census(at).1, q.census(at)); + } + }; + + for slot in [10u32, 20, 30, 40, 50] { + q.written(slot, 1, 0, false); + } + check_invariants(&q); + assert!(!marks.has_held()); + + // `partly` sets FLAG_MAPPED; `recheck(print != 0)` clears FLAG_MAPPED and sets FLAG_CHECKED. + let w10 = q.entry(10).unwrap().write; + q.partly(10, w10, 6, 4096); + assert_eq!(q.mapped(10), 4096); + assert_eq!(q.checked(10), None); + assert!(q.was_uploaded(10)); + check_invariants(&q); + + q.recheck(10, w10, 8, (0x1000, 4096), 0xabc, 1, 5); + assert_eq!(q.mapped(10), 0); + assert_eq!(q.checked(10), Some((0x1000, 4096, 0xabc, 1, 5))); + check_invariants(&q); + + // `partly` after `recheck` keeps `checked` untouched (exact parity). + q.partly(10, w10, 9, 8192); + assert_eq!(q.mapped(10), 8192); + assert_eq!(q.checked(10), Some((0x1000, 4096, 0xabc, 1, 5))); + check_invariants(&q); + + // In-place overwrite reuses slot position and clears both cold maps. + let pos10 = q.by_slot[&10]; + q.written(10, 10, 10, false); + assert_eq!(q.by_slot[&10], pos10); + assert_eq!(q.mapped(10), 0); + assert_eq!(q.checked(10), None); + assert!(!q.was_uploaded(10)); + check_invariants(&q); + + // `recheck` with `print == 0` clears FLAG_CHECKED and removes from cold `checked` map. + let w20 = q.entry(20).unwrap().write; + q.recheck(20, w20, 12, (0x2000, 1024), 99, 0, 5); + assert!(q.checked(20).is_some()); + check_invariants(&q); + q.recheck(20, w20, 14, (0x2000, 1024), 0, 1, 5); + assert_eq!(q.checked(20), None); + assert_eq!(q.entry(20).unwrap().flags & FLAG_CHECKED, 0); + check_invariants(&q); + + // `hold` / `room` toggle `marks.has_held()`. + let w30 = q.entry(30).unwrap().write; + q.hold(30, w30, 100); + assert!(marks.has_held()); + check_invariants(&q); + assert_eq!(q.room(10), 1); + assert!(!marks.has_held()); + check_invariants(&q); + + // `changed` overwrites in place, clears cold maps, and preserves min `due`. + let w40 = q.entry(40).unwrap().write; + q.partly(40, w40, 3, 2048); + let pos40 = q.by_slot[&40]; + q.changed(40, 11, 20); + assert_eq!(q.by_slot[&40], pos40); + assert_eq!(q.entry(40).unwrap().due, 3); + assert_eq!(q.mapped(40), 0); + check_invariants(&q); + + // Swap-remove from front (moves last element into pos 0), middle, and back. + let w50 = q.entry(50).unwrap().write; + q.recheck(50, w50, 5, (0x5000, 512), 55, 0, 2); + check_invariants(&q); + assert!(q.take_out(10)); // front + assert_eq!(marks.get(10), Some(0)); + check_invariants(&q); + assert!(q.take_out(30)); // middle + assert_eq!(marks.get(30), Some(0)); + check_invariants(&q); + assert!(q.take_out(50)); // moved element with checked metadata + assert_eq!(marks.get(50), Some(0)); + assert_eq!(q.checked(50), None); + check_invariants(&q); + assert!(q.take_out(40)); + assert!(q.take_out(20)); + assert!(!q.take_out(20)); + assert!(q.entries.is_empty()); + check_invariants(&q); + } + + /// `Due::ordered` truncation matches a naive full-sort reference across + /// `again.len() > max`, `fresh.len() > max`, mixed queues, and edge `max`. + #[test] + fn due_ordered_truncation_matches_full_sort() { + let reference = |q: &TextureQueue, frame: u64, max: usize| -> (Vec<(u32, u64)>, Vec>) { + let mut again: Vec<(u32, u64, Option)> = Vec::new(); + let mut fresh: Vec<(u32, u64)> = Vec::new(); + for e in &q.entries { + if e.due <= frame { + let mapped = e.flags & FLAG_MAPPED != 0; + if e.looks > 0 || mapped { + again.push((e.index, e.write, q.checked(e.index))); + } else { + fresh.push((e.index, e.write)); + } + } + } + again.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + fresh.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + let mut order: Vec<(u32, u64)> = Vec::new(); + let mut known: Vec> = Vec::new(); + for &(i, w, c) in again.iter().filter(|a| a.2.is_none()) { + order.push((i, w)); + known.push(c); + } + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push(fresh[new]); + known.push(None); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push(fresh[old]); + known.push(None); + } + } + for &(i, w, c) in again.iter().filter(|a| a.2.is_some()) { + order.push((i, w)); + known.push(c); + } + order.truncate(max); + known.truncate(max); + (order, known) + }; + + // Mixed queue: 11 `again` (recheck, partly, later) + 17 `fresh`, scrambled write order. + let mut mixed = TextureQueue::default(); + for i in 0..28u32 { + mixed.written(100 + i, 1, 0, false); + } + // Rewrite a subset to scramble entry order vs write order. + for i in [3u32, 19, 7, 25, 11, 0, 14] { + mixed.written(100 + i, 2, 0, false); + } + for (k, i) in [0u32, 2, 5, 7, 9, 11, 13, 15, 17, 19, 21].into_iter().enumerate() { + let slot = 100 + i; + let w = mixed.entry(slot).unwrap().write; + match k % 3 { + 0 => mixed.recheck(slot, w, 5, (0x1000 * (u64::from(i) + 1), 4096), u64::from(i) + 1, k as u8, 2), + 1 => mixed.partly(slot, w, 5, 1024 * (u64::from(i) + 1)), + _ => mixed.later(slot, w, 3, 2), + } + } + for max in 0..=32 { + let got = mixed.due_and_census(20).0.ordered(max); + let want = reference(&mixed, 20, max); + assert_eq!(got, want, "mixed mismatch at max={max}"); + } + + // Pure fresh queue (`fresh.len() > max` for odd/even `max`, `max == 1`, etc.). + let mut fresh_only = TextureQueue::default(); + for i in 0..23u32 { + fresh_only.written(200 + ((i * 7) % 23), 1, 0, false); + } + for max in 0..=25 { + let got = fresh_only.due_and_census(10).0.ordered(max); + let want = reference(&fresh_only, 10, max); + assert_eq!(got, want, "fresh-only mismatch at max={max}"); + } + + // Pure again queue (`again.len() > max`). + let mut again_only = TextureQueue::default(); + for i in 0..15u32 { + again_only.written(300 + i, 1, 0, false); + let w = again_only.entry(300 + i).unwrap().write; + again_only.recheck(300 + i, w, 4, (0x8000, 4096), u64::from(i) + 1, 0, 1); + } + for max in 0..=17 { + let got = again_only.due_and_census(10).0.ordered(max); + let want = reference(&again_only, 10, max); + assert_eq!(got, want, "again-only mismatch at max={max}"); + } + } + + /// `QueueBatch` safety: a deferred `RemoveIf` with a stale write number + /// never removes a newer concurrent write, and batched `Write`/`RemoveIf` + /// sequences match unbatched updates identically. + #[test] + fn queue_batch_remove_if_never_clobbers_newer_write_and_matches_unbatched() { + let marks = std::sync::Arc::new(QueueMarks::new(32)); + let mut q = TextureQueue::with_marks(marks.clone()); + for slot in 1..=5u32 { + q.written(slot, 10, 0, false); + } + let w2_old = marks.get(2).unwrap(); + let w3_cur = marks.get(3).unwrap(); + let w4_cur = marks.get(4).unwrap(); + + // Concurrent newer write on slot 2 before the batch flushes. + q.written(2, 11, 0, false); + let w2_new = marks.get(2).unwrap(); + assert_ne!(w2_new, w2_old); + + let mut batch = QueueBatch::default(); + for op in [ + QueueOp::RemoveIf { index: 2, write: w2_old }, + QueueOp::RemoveIf { index: 3, write: w3_cur }, + QueueOp::Write { index: 4, frame: 12, due: 0, seen: true }, + QueueOp::Write { index: 6, frame: 12, due: 15, seen: false }, + ] { + batch.seen_bits |= 1u64 << (op.index() & 63); + batch.ops.push(op); + } + assert!(batch.has_slot(2) && batch.has_slot(6) && !batch.has_slot(7)); + batch.apply(&mut q); + assert!(batch.ops.is_empty() && batch.seen_bits == 0); + + // Slot 2 survived because `w2_old != w2_new`; slot 3 was removed; + // slot 4 kept its original write (`seen = true`); slot 6 was inserted. + assert_eq!(marks.get(2), Some(w2_new)); + assert_eq!(marks.get(3), Some(0)); + assert_eq!(q.entry(3), None); + assert_eq!(marks.get(4), Some(w4_cur)); + assert_eq!(q.entry(6).map(|e| e.due), Some(15)); + + // Full batched vs unbatched parity through `HostHeap::queue_texture_inner` + // across > `QueueBatch::LIMIT` ops including same-slot transitions. + let (Some(a), Some(b)) = (HostHeap::new(false, 128), HostHeap::new(false, 128)) else { + return; // no host GPU + }; + let mut heap_batch = QueueBatch::default(); + for i in 0..100u32 { + let slot = i % 80; + let texture = i % 5 != 0; + let seen = i % 7 == 0; + let frame = 50 + u64::from(i / 20); + a.queue_texture_inner(slot, texture, seen, frame, Some(&mut heap_batch)); + b.queue_texture_inner(slot, texture, seen, frame, None); + } + // Same-slot Write -> Remove -> Write within a single un-flushed batch. + for &(slot, texture, seen) in &[ + (5u32, true, false), + (5, false, false), + (6, true, false), + (6, true, true), + (6, false, false), + (6, true, false), + ] { + a.queue_texture_inner(slot, texture, seen, 60, Some(&mut heap_batch)); + b.queue_texture_inner(slot, texture, seen, 60, None); + } + heap_batch.flush(&a); + + for at in [50, 60, 100, u64::MAX] { + let (oa, ka, ca) = a.texture_slots_due_known(at, 200); + let (ob, kb, cb) = b.texture_slots_due_known(at, 200); + assert_eq!(oa, ob, "order mismatch at frame {at}"); + assert_eq!(ka, kb, "known mismatch at frame {at}"); + assert_eq!(ca, cb, "census mismatch at frame {at}"); + } + assert_eq!(a.texture_news().0, b.texture_news().0); + for slot in 0..80u32 { + assert_eq!(a.texture_slot_write(slot), b.texture_slot_write(slot)); + } + } + #[test] fn dynamic_slots_are_held_until_released() { let Some(heap) = HostHeap::new(false, 4) else { @@ -7149,3 +7862,96 @@ mod bake_flip_tests { assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry"); } } + +#[cfg(all(test, windows))] +mod audit_regressions { + use super::*; + #[test] + fn audit_shared_copy_table() { + audit_shared_copy(false); + } + + #[test] + fn audit_shared_copy_stale() { + audit_shared_copy(true); + } + + fn audit_shared_copy(stale: bool) { + use crate::descriptor::{ + FUNCTIONS, Heap, HeapDesc, SHADER_HEAPS, SHADER_VISIBLE, VIEW_TAG, mirror_range, + words_for, + }; + use crate::object::Object; + let bytes = vec![0u8; 65536]; + let address = bytes.as_ptr() as u64; + let view = |width| { + let mut desc = [0; 16]; + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed( + false, + [3, 0, 0, 0, width, 0, 64, 0x10001, 98, 1, 0, 0x105, 0, 0], + desc, + ) + }; + let words = words_for(view(64)); + let mut records = [0u32; 64]; + records[..3].copy_from_slice(&[VIEW_TAG, words[0], words[1]]); + let start = records.as_ptr() as u64; + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc: HeapDesc { + kind: 0, + count: 8, + flags: SHADER_VISIBLE, + nodes: 0, + }, + start, + memory: None, + host: Default::default(), + pending: Default::default(), + written: None, + }); + let Some(host_heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + heap.host.set(Some(host_heap)).ok().unwrap(); + SHADER_HEAPS + .write() + .unwrap() + .push((start, start + 256, &*heap as *const Heap as usize)); + let h = heap.host.get().unwrap().as_ref().unwrap(); + std::thread::scope(|s| { + // Pause the copy at slot 1 so the observer runs after slot 0 was mirrored. + let second = h.made.lock(1); + let a = s.spawn(move || mirror_range(start, 2, 32)); + let limit = std::time::Instant::now() + std::time::Duration::from_secs(8); + let mut reached = false; + while std::time::Instant::now() < limit { + if !h.spanned.all(|i| i == 0).is_empty() { + reached = true; + break; + } + std::thread::yield_now(); + } + if reached { + // Wait until the producer has released the first slot. + drop(h.made.lock(0)); + if stale { + let victims = h.note_buffer(2, Some(&view(128)), false); + assert!(victims.iter().any(|&(slot, _)| slot == 0)); + h.unmake_stale(2, victims); + } else { + h.texture_slot_tabled(0, true); + } + } + drop(second); + a.join().unwrap(); + assert!(reached); + }); + let order = h.texture_slots_due(u64::MAX, 16).0; + assert!( + !order.iter().any(|&(i, _)| i == 0), + "shared bulk mirror left slot 0 queued: {order:?}" + ); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9b954493e..ba0902188 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -996,7 +996,7 @@ impl Tells<'_> { /// Few slots' work (some microseconds each), so that a pass that takes /// the slots due meanwhile on another thread finds few of these told /// late. - const BATCH: usize = 16; + const BATCH: usize = 64; fn tell(&mut self, index: u32, write: u64, what: crate::descriptor::host::Told) { use crate::descriptor::host::Told; @@ -3246,6 +3246,13 @@ impl State { served = false; break; } + let mark = if queue_batch() { host.texture_slot_write(index) } else { None }; + if !baking && sync.is_none() && mark == Some(0) { + // Already left the queue (finished by a concurrent pass, read + // through a table, made stale, or overwritten with a non-texture): + // nothing to tell back (`TextureQueue::same` would drop it). + continue; + } outcome(slot_outcome::TAKEN); // A placed texture whose memory is not mapped (not streamed in // yet, or streamed out again: the heap keeps tens of thousands @@ -3275,8 +3282,9 @@ impl State { // What the queue knew of it when the slots due were taken, while // its marks say it holds the write handed out still; else (or with // `VICTORY_QUEUE_BATCH=0`) asked now. - let checked = match knew { - knew if queue_batch() && host.texture_slot_write(index) == Some(write) => knew, + let checked = match mark { + Some(cur) if cur == write => knew, + Some(0) => None, _ => rest(0, || host.texture_slot_checked(index)), }; if let Some((at, len, print, looks, uploaded)) = checked { From 3f6ca47b8b71fe77378477287c0e28e982aa5883 Mon Sep 17 00:00:00 2001 From: henriazz10 <100179000+henriazz10@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:48:08 -0300 Subject: [PATCH 21/22] perf(gpu): lock-free no-op refreshes, thin-worker refresh coalescing, and AVX2 copy diff Adapted from trustno1-coder/VIctory-NVIDIA#614 by @wike1701. --- crates/victory-gpu/src/host.rs | 75 +++++++++--- crates/victory-gpu/src/shadow.rs | 196 ++++++++++++++++++++++++------- crates/victory-gpu/src/watch.rs | 100 +++++++++++++--- 3 files changed, 298 insertions(+), 73 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 92918dbcc..66134a28c 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2727,6 +2727,11 @@ struct Deferred { /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Per-shadow coalesced span `(copies_index, from, to)` in the current + /// uninterrupted segment (cleared on title writes and per-shadow on GPU + /// writes): lets `VICTORY_THIN` workers merge overlapping/adjacent + /// refreshes before the submitting thread ever walks `copies`. + refreshed_span: std::collections::HashMap>, /// Ranges declared written by shaders since the list last wrote title /// memory (host copy, address, bytes): declaring them again would /// change nothing. @@ -2773,6 +2778,7 @@ impl Deferred { /// date before them is not any more. fn title_written(&mut self) { self.refreshed.clear(); + self.refreshed_span.clear(); self.gpu_written.clear(); self.filled.clear(); } @@ -6903,6 +6909,7 @@ impl HostList { deferred .copies .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); + deferred.refreshed_span.clear(); } /// A new host list for one of the title's lists (`crate::list::detach`), @@ -7677,11 +7684,33 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + let deferred = &mut *deferred; + let ptr = std::sync::Arc::as_ptr(shadow) as usize; + let end = address.saturating_add(len); + if let Some(&mut (idx, ref mut from, ref mut to)) = deferred.refreshed_span.get_mut(&ptr) + && address <= *to + && end >= *from + { + if *from <= address && end <= *to { + return; + } + let new_from = (*from).min(address); + let new_to = (*to).max(end); + if let Some(Step::Refresh(_, a, l)) = deferred.copies.get_mut(idx) { + *a = new_from; + *l = new_to - new_from; + *from = new_from; + *to = new_to; + return; + } + } + let key = (ptr, address, len); if deferred.refreshed.insert(key) { + let idx = deferred.copies.len(); deferred .copies .push(Step::Refresh(shadow.clone(), address, len)); + deferred.refreshed_span.insert(ptr, (idx, address, end)); } } @@ -7697,7 +7726,9 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + let ptr = std::sync::Arc::as_ptr(shadow) as usize; + deferred.refreshed_span.remove(&ptr); + let key = (ptr, address, len); if deferred.gpu_written.insert(key) || !declare_once() { deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); } @@ -8995,7 +9026,7 @@ impl Batch { let mut spans = spans; let dropped = Self::filter_nothing_new(&mut spans); FLUSHES[2].fetch_add(dropped as u64, Ordering::Relaxed); - let ahead = spans.len() > 1; + let ahead = spans.len() > 1 && !crate::watch::is_kept(); if ahead { let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); crate::watch::ask_ahead(&ranges); @@ -9053,9 +9084,21 @@ impl Batch { } 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) { + crate::shadow::wide_chunks(due.len(), 32, move |range| { + let mut need = [0usize; 32]; + let mut n_need = 0usize; + { + let journal = crate::watch::read_journal(); + for i in range { + let (shadow, from, to) = &due[i]; + if !shadow.nothing_new_with(&journal, *from, *to - *from) { + need[n_need] = i; + n_need += 1; + } + } + } + for &i in &need[..n_need] { + let (shadow, from, to) = &due[i]; Self::update(shadow, *from, *to); } }); @@ -9130,7 +9173,8 @@ impl Batch { const CHUNK: usize = 128; let all = items.len(); if all <= FEW { - items.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + let journal = crate::watch::read_journal(); + items.retain(|(shadow, from, to)| !shadow.nothing_new_with(&journal, *from, *to - *from)); return all - items.len(); } let words = all.div_ceil(64); @@ -9161,12 +9205,15 @@ impl Batch { let slice = unsafe { ptr.slice(start, end) }; let mut mask0 = 0u64; let mut mask1 = 0u64; - for (offset, (shadow, from, to)) in slice.iter().enumerate() { - if !shadow.nothing_new(*from, *to - *from) { - if offset < 64 { - mask0 |= 1u64 << offset; - } else { - mask1 |= 1u64 << (offset - 64); + { + let journal = crate::watch::read_journal(); + for (offset, (shadow, from, to)) in slice.iter().enumerate() { + if !shadow.nothing_new_with(&journal, *from, *to - *from) { + if offset < 64 { + mask0 |= 1u64 << offset; + } else { + mask1 |= 1u64 << (offset - 64); + } } } } @@ -9202,7 +9249,7 @@ impl Batch { } // One write-watch asking for the copies that lie close together, // not one per copy. - let ahead = self.refreshes.len() > 1; + let ahead = self.refreshes.len() > 1 && !crate::watch::is_kept(); if ahead { let started = std::time::Instant::now(); let ranges: Vec<(usize, usize)> = self diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 2ac83e472..f76c542a2 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -41,18 +41,28 @@ pub(crate) struct Shadow { start: u64, len: u64, /// Per page of title memory from `start`'s on: the write-watch asking - /// after which it was last copied (0: never). - copied: Mutex>, + /// after which it was last copied (0: never). Fixed-size and atomic so + /// [`Shadow::nothing_new_with`] reads it lock-free; writers serialize on + /// `copy_lock` and store `now` with `Release` only after copying bytes. + copied: Box<[AtomicU64]>, + /// Serializes writers updating `copied` and `ranged` (`copy_stale`, + /// `merge_under_writes`, `landed`). + copy_lock: Mutex<()>, /// Two ranges of title memory taken whole, the last one and the longest, /// and the asking after which each was ([`Shadow::copy_stale`]). A page /// a range holds in part cannot say so in `copied`. Locked inside - /// `copied`'s lock. + /// `copy_lock`. ranged: Mutex<[(usize, usize, u64); 2]>, + /// Fast-path flag: `true` once `ranged` holds any non-zero range. + ranged_any: AtomicBool, /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex>, + /// Fast-path flag: `true` while `pending` is non-empty, avoiding the + /// `pending` mutex lock on read-only buffers during refreshes. + pending_any: AtomicBool, /// With [`relay`]: how many submissions not yet copied back declared /// each range of `pending` ([`Flights`]). Locked inside `pending`'s /// lock. @@ -733,8 +743,8 @@ pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize continue; }; let written: std::collections::HashMap = written.into_iter().collect(); - let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone(); - for (i, &at) in copied.iter().enumerate() { + for (i, slot) in shadow.copied.iter().enumerate() { + let at = slot.load(Ordering::Acquire); let page = start / PAGE + i; if at == 0 || written.get(&page).is_some_and(|&w| w > at) { continue; @@ -1820,6 +1830,35 @@ pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) wide(jobs); } +/// Calls `work` with disjoint contiguous chunks of `0..n` of size up to +/// `chunk`, claimed per worker with a single atomic increment: reduces +/// cache-line contention on `next` and allows per-chunk amortization of +/// shared read locks and counters. +pub(crate) fn wide_chunks(n: usize, chunk: usize, work: impl Fn(std::ops::Range) + Send + Sync + 'static) { + if n == 0 { + return; + } + let chunk = chunk.max(1); + let next = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let work = Arc::new(work); + let threads = (wide_threads() + 1).min(n.div_ceil(chunk)); + let jobs = (0..threads) + .map(|_| { + let (next, work) = (next.clone(), work.clone()); + Box::new(move || { + loop { + let start = next.fetch_add(chunk, Ordering::Relaxed); + if start >= n { + break; + } + work(start..(start + chunk).min(n)); + } + }) as Job + }) + .collect(); + wide(jobs); +} + /// About this many bytes to a piece of work for [`wide`]. const WIDE_JOB: usize = 1 << 20; @@ -3033,13 +3072,13 @@ mod piece_tests { /// merged nor a reason to settle; the refresh leaves such ranges alone, and /// shaders read zeros there (fxceless/victory-fork#206: missing geometry /// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`). -fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { +fn stale_pages_in(base: usize, copied: &[AtomicU64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { (a / PAGE..e.div_ceil(PAGE)) .filter(|&page| page >= base) - .filter(|&page| match copied.get(page - base) { + .filter(|&page| match copied.get(page - base).map(|v| v.load(Ordering::Acquire)) { None => false, Some(0) => true, - Some(&at) => written + Some(at) => written .binary_search_by_key(&page, |&(p, _)| p) .is_ok_and(|i| written[i].1 > at), }) @@ -3156,7 +3195,7 @@ mod stale_tests { #[test] fn pages_never_taken_are_stale_written_or_not() { let base = 0x100; - let copied = [5, 0, 5, 5]; + let copied = [5u64, 0, 5, 5].map(AtomicU64::new); let at = |page: usize| page * PAGE; // Page 0x101 was never taken; page 0x102 was written after it was // taken, page 0x103 before. @@ -3204,8 +3243,7 @@ pub(crate) fn window_use() -> [u64; 8] { let mut out = [0u64; 8]; let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); for s in loose.values() { - let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner()); - let pages = copied.iter().filter(|&&at| at != 0).count() as u64; + let pages = s.copied.iter().filter(|at| at.load(Ordering::Relaxed) != 0).count() as u64; out[0] += (pages * PAGE as u64).min(s.len); if crate::host::references(&s.buffer) > 1 { out[1] += 1; @@ -3403,10 +3441,13 @@ impl Shadow { gpu, start, len, - copied: Mutex::new(vec![0; pages as usize]), + copied: (0..pages as usize).map(|_| AtomicU64::new(0)).collect::>().into_boxed_slice(), + copy_lock: Mutex::new(()), ranged: Mutex::default(), + ranged_any: AtomicBool::new(false), watched: AtomicU8::new(0), pending: Mutex::default(), + pending_any: AtomicBool::new(false), flights: Mutex::default(), before: Mutex::default(), merging: RwLock::default(), @@ -3519,6 +3560,7 @@ impl Shadow { // lists). if self.card.is_some() { pending.push(range); + self.pending_any.store(true, Ordering::Release); return; } // The parts no declared range holds yet: their bytes are taken now, @@ -3543,6 +3585,7 @@ impl Shadow { parts = rest; } pending.push(range); + self.pending_any.store(true, Ordering::Release); let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); let total = self.len as usize; @@ -3832,6 +3875,7 @@ impl Shadow { } else { pending.retain(|r| !ranges.contains(r)); } + self.pending_any.store(!pending.is_empty(), Ordering::Release); if !pending.is_empty() || self.card.is_some() { return; } @@ -3889,12 +3933,15 @@ impl Shadow { /// Whether shaders of a submission not yet copied back may be writing /// the copy. pub(crate) fn writes_pending(&self) -> bool { - !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + self.pending_any.load(Ordering::Acquire) } /// Whether one of those submissions may be writing in title memory /// `[from, to)`. pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool { + if !self.pending_any.load(Ordering::Acquire) { + return false; + } self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) } @@ -3930,9 +3977,8 @@ impl Shadow { return true; } let base = start / PAGE; - let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { - Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), + Some((_, written)) => !stale_pages_in(base, &self.copied, a, e, &written).is_empty(), None => true, }) } @@ -3991,10 +4037,7 @@ impl Shadow { note_stale(1); return true; }; - let stale: Vec = { - let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - stale_pages_in(base, &copied, a, e, &written) - }; + let stale: Vec = stale_pages_in(base, &self.copied, a, e, &written); if stale.is_empty() { continue; } @@ -4066,10 +4109,10 @@ impl Shadow { drop(before); drop(merging); { - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let _copy = self.copy_lock.lock().unwrap_or_else(|e| e.into_inner()); for page in taken { - if let Some(at) = copied.get_mut(page - base) { - *at = now; + if let Some(at) = self.copied.get(page - base) { + at.store(now, Ordering::Release); } } } @@ -4182,8 +4225,17 @@ impl Shadow { /// Whether [`Shadow::update`] of `[address, address + len)` would copy /// nothing, and knows it without asking anything - /// (`crate::watch::nothing_new`). `false` if it would have to ask. + /// (`crate::watch::JournalRead::nothing_new_atomic`). `false` if it would + /// have to ask. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + let journal = crate::watch::read_journal(); + self.nothing_new_with(&journal, address, len) + } + + /// As [`Shadow::nothing_new`], reusing a caller-held [`crate::watch::JournalRead`] + /// and reading `copied` lock-free to avoid mutex and `RwLock` contention + /// across thousands of no-op refreshes per frame. + pub(crate) fn nothing_new_with(&self, journal: &crate::watch::JournalRead, address: usize, len: usize) -> bool { if self.place.is_some() { return true; } @@ -4196,11 +4248,12 @@ impl Shadow { return false; } // Around ranges shaders are writing the refresh asks gap by gap. - if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { + if self.pending_any.load(Ordering::Acquire) + && self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) + { return false; } - let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to)); + let same = journal.nothing_new_atomic(from, to, start / PAGE, &self.copied, || self.ranged(from, to)); #[cfg(feature = "diagnostics")] if same { use crate::copystat::{C, add}; @@ -4211,8 +4264,11 @@ impl Shadow { } /// The latest asking after which a range that holds `[from, to)` was - /// taken whole (0: none is known). The caller holds `copied`'s lock. + /// taken whole (0: none is known). fn ranged(&self, from: usize, to: usize) -> u64 { + if !self.ranged_any.load(Ordering::Acquire) { + return 0; + } let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0) } @@ -4309,7 +4365,7 @@ impl Shadow { /// asking), whole pages within the buffer. fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { let base = self.start as usize / PAGE; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let _copy = self.copy_lock.lock().unwrap_or_else(|e| e.into_inner()); let mut writes = written.iter().peekable(); // Pages the range holds in part are never noted in `copied`, and // were copied again at every refresh of the range, written or not: @@ -4320,7 +4376,12 @@ impl Shadow { 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(); + // Whole pages whose `copied` generation will be published once their + // bytes are in `self.data` (so lock-free readers never observe `now` + // before `take_all` finishes). + let mut updated_pages: Vec = Vec::new(); let last = (to - 1) / PAGE; + let (start, end) = (self.start as usize, (self.start + self.len) as usize); for page in from / PAGE..=last { let write = match writes.peek() { Some(&&(p, w)) if p == page => { @@ -4329,14 +4390,13 @@ impl Shadow { } _ => 0, }; - let at = &mut copied[page - base]; - let taken = (*at).max(ranged); + let prev = self.copied[page - base].load(Ordering::Relaxed); + let taken = prev.max(ranged); if taken == 0 || write > taken { // A page only partly in the range is copied in part: it // stays stale for the rest. - let (start, end) = (self.start as usize, (self.start + self.len) as usize); if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { - *at = now; + updated_pages.push(page - base); } // Cut where pages taken before meet pages never taken. let again = taken != 0; @@ -4360,6 +4420,9 @@ impl Shadow { } let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at)); let bytes = self.take_all(runs); + for idx in updated_pages { + self.copied[idx].store(now, Ordering::Release); + } if crate::watch::light() { // All of the range is in the copy as of this asking. let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); @@ -4367,6 +4430,7 @@ impl Shadow { if to - from >= ranged[1].1 - ranged[1].0 { ranged[1] = (from, to, now); } + self.ranged_any.store(true, Ordering::Release); } bytes } @@ -4497,6 +4561,7 @@ impl Shadow { }; let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); let start = self.start as usize; + let (mut send_checked, mut send_same, mut send_bytes, mut send_runs) = (0u64, 0u64, 0u64, 0u64); TITLE.with_borrow_mut(|title| { title.resize(PAGE, 0); let mut at = from; @@ -4511,7 +4576,7 @@ impl Shadow { // refresh lie apart. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); - let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + let runs = if whole { vec![(0, n)] } else { word_runs(at, held, title) }; for &(a, len) in &runs { held[a..a + len].copy_from_slice(&title[a..a + len]); self.changed(at - start + a, at - start + a + len); @@ -4520,15 +4585,28 @@ impl Shadow { if let Some(was) = was { crate::host::upcheck::note(self.id, at - start, &was, held); } - SEND[0].fetch_add(n as u64, Ordering::Relaxed); + send_checked += n as u64; if runs.is_empty() { - SEND[1].fetch_add(n as u64, Ordering::Relaxed); + send_same += n as u64; + } else { + send_bytes += runs.iter().map(|r| r.1 as u64).sum::(); + send_runs += runs.len() as u64; } - SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); - SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed); at += n; } }); + if send_checked > 0 { + SEND[0].fetch_add(send_checked, Ordering::Relaxed); + } + if send_same > 0 { + SEND[1].fetch_add(send_same, Ordering::Relaxed); + } + if send_bytes > 0 { + SEND[2].fetch_add(send_bytes, Ordering::Relaxed); + } + if send_runs > 0 { + SEND[3].fetch_add(send_runs, Ordering::Relaxed); + } to - from } @@ -5021,13 +5099,14 @@ impl Shadow { let Some(page) = block.checked_sub(self.start as usize / PAGE) else { return false; }; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - let Some(at) = copied.get_mut(page) else { + let _copy = self.copy_lock.lock().unwrap_or_else(|e| e.into_inner()); + let Some(slot) = self.copied.get(page) else { return false; }; - let held = *at != 0 && *at >= before && crate::watch::block_published(block); + let at = slot.load(Ordering::Relaxed); + let held = at != 0 && at >= before && crate::watch::block_published(block); if held { - *at = (*at).max(now); + slot.store(at.max(now), Ordering::Release); } held } @@ -5162,6 +5241,7 @@ mod land_tests { return; // no host GPU }; shadow.pending.lock().unwrap().push((title, title + LEN)); + shadow.pending_any.store(true, Ordering::Release); // SAFETY: committed, aligned; touched as atomics or by the landing's // stores of whole dwords. let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) }; @@ -5215,6 +5295,38 @@ mod land_tests { assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last)); }); } + + #[test] + fn wide_chunks_visits_every_index_once() { + for &(n, chunk) in &[(0usize, 32usize), (1, 32), (5, 32), (32, 32), (64, 32), (1000, 32), (257, 17)] { + let hits: std::sync::Arc> = + std::sync::Arc::new((0..n).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + let hits_work = hits.clone(); + super::wide_chunks(n, chunk, move |range| { + let (lo, hi) = (range.start, range.end); + assert!(lo < hi, "empty chunk ({lo}..{hi}) for n={n}"); + assert!(hi <= n, "out of bounds ({lo}..{hi}) for n={n}"); + assert!(hi - lo <= chunk, "oversized chunk ({lo}..{hi}) > {chunk}"); + for slot in &hits_work[lo..hi] { + slot.fetch_add(1, Ordering::Relaxed); + } + }); + for (i, slot) in hits.iter().enumerate() { + assert_eq!(slot.load(Ordering::Relaxed), 1, "index {i} for n={n}, chunk={chunk}"); + } + } + } + + #[test] + fn journal_read_atomic_matches_watch_nothing_new() { + let journal = crate::watch::read_journal(); + let copied = [u64::MAX]; + let atomic = [std::sync::atomic::AtomicU64::new(u64::MAX)]; + assert_eq!( + journal.nothing_new_atomic(0x1000, 0x2000, 0x1000, &atomic, || u64::MAX), + crate::watch::nothing_new(0x1000, 0x2000, 0x1000, &copied, u64::MAX), + ); + } } struct Entry { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 3e52023e7..935f2ab5d 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -28,6 +28,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::ops::{Bound, RangeBounds}; +use std::sync::atomic::Ordering; use std::sync::{Condvar, Mutex, RwLock}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's @@ -406,7 +407,20 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; /// submissions refresh thousands of host copies (6,664 askings a frame, /// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are /// left to `writes`. +/// Fast-path mirror of `journal().kept`: avoids building/sorting `ask_ahead` +/// ranges and taking an exclusive `journal_mut()` write lock on every flush +/// while a submission's one asking (`VICTORY_ASK_ONCE`) stands. +static JOURNAL_KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether the submission's one asking (`ask_once`) currently stands. +pub(crate) fn is_kept() -> bool { + JOURNAL_KEPT.load(Ordering::Acquire) +} + pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + if is_kept() { + return; + } let mut pieces: Vec<(usize, usize)> = ranges .iter() // Not view memory known by its bits: the kernel would refuse the @@ -595,6 +609,9 @@ fn ask_early(every: std::time::Duration) { /// The submission's refreshes are done: `writes` asks the kernel again. pub(crate) fn ask_ahead_done() { + if is_kept() { + return; + } let mut j = journal_mut(); if !j.kept { j.ahead.clear(); @@ -680,17 +697,23 @@ fn ask_rest(ranges: &[(usize, usize)]) { for (page, parts) in written { j.note(page, parts, now); } - j.kept = !ahead.is_empty(); + let kept = !ahead.is_empty(); + j.kept = kept; j.ahead = ahead; + JOURNAL_KEPT.store(kept, Ordering::Release); } /// The submission's one asking stands no longer: its refreshes are done, /// or title memory was written in a way the journal was not told. pub(crate) fn ask_once_end() { + if !is_kept() { + return; + } let mut j = journal_mut(); if j.kept { j.kept = false; j.ahead.clear(); + JOURNAL_KEPT.store(false, Ordering::Release); } } @@ -698,6 +721,9 @@ pub(crate) fn ask_once_end() { /// stands (the title's buffer copies, done at submission): its pages count /// as written after that asking, so the refreshes that follow copy them. pub(crate) fn wrote(at: usize, len: usize) { + if !is_kept() || len == 0 { + return; + } let mut j = journal_mut(); if !j.kept || len == 0 { return; @@ -844,29 +870,69 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve Some(answer) } +/// A held read guard on the write-watch journal, allowing callers to check +/// many buffers with [`JournalRead::nothing_new_atomic`] without acquiring +/// `JOURNAL`'s `RwLock` on every single buffer. +/// +/// Callers MUST drop `JournalRead` before calling any function that acquires +/// `journal_mut()` (such as [`writes`]). +pub(crate) struct JournalRead(std::sync::RwLockReadGuard<'static, Journal>); + +/// Acquires a shared read guard on the write-watch journal for batched +/// [`JournalRead::nothing_new_atomic`] checks. +pub(crate) fn read_journal() -> JournalRead { + JournalRead(journal()) +} + +impl JournalRead { + /// Lock-free check of whether nothing of `[start, end)` was written since + /// `copied` (one `AtomicU64` per 64 KiB page from `base` on) was taken. + /// Only invokes `ranged_fn` (which may lock `Shadow.ranged`) when a page in + /// `[first, last)` is partial (`0`) or older than a recorded write, keeping + /// the common whole-page no-op path 100% mutex-free. + pub(crate) fn nothing_new_atomic( + &self, + start: usize, + end: usize, + base: usize, + copied: &[std::sync::atomic::AtomicU64], + ranged_fn: impl FnOnce() -> u64, + ) -> bool { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let known = published(start, end); + #[cfg(feature = "diagnostics")] + if known { + crate::faultbook::note(crate::faultbook::What::Known, first, last, 1); + } + let j = &*self.0; + if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return false; + } + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + let all_nonzero = taken.iter().all(|at| at.load(Ordering::Acquire) != 0); + if all_nonzero && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].load(Ordering::Acquire)) { + return true; + } + let ranged = ranged_fn(); + (ranged != 0 || all_nonzero) + && j.written + .range(first..last) + .all(|(&page, &write)| write <= taken[page - first].load(Ordering::Acquire).max(ranged)) + } +} + /// Whether nothing of `[start, end)` was written that a copy with the notes /// `copied` (the asking after which each page from page `base` on was taken) /// and `ranged` (the asking after which a range that holds this one was /// taken whole, or 0) does not hold, as [`writes`] would answer with nothing /// asked: the submission's asking covers the range, or its blocks are known /// by their bits. `false` if something would have to be asked. +#[cfg(test)] pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool { - let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - // The bits first, then the journal, as in `writes`. - let known = published(start, end); - #[cfg(feature = "diagnostics")] - if known { - crate::faultbook::note(crate::faultbook::What::Known, first, last, 1); - } - let j = journal(); - if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { - return false; - } - let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { - return false; - }; - (ranged != 0 || taken.iter().all(|&at| at != 0)) - && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) + let atomic: Vec = copied.iter().map(|&v| std::sync::atomic::AtomicU64::new(v)).collect(); + read_journal().nothing_new_atomic(start, end, base, &atomic, || ranged) } impl Tracked { From bbf23eabbb018dd5893d6f816b22015655638395 Mon Sep 17 00:00:00 2001 From: Hefty Date: Sat, 28 Nov 2026 20:39:55 +0800 Subject: [PATCH 22/22] feat(scripts): warn when NVIDIA NGX DLSS override DLLs are present Streamline may load sl_*_override_* from ProgramData instead of nvidia-sdk, correlating with DLSS 0xbad00005 and black cutscenes (#449, #99). Co-authored-by: Cursor --- scripts/Test-NvidiaNgxOverride.ps1 | 24 ++++++++++++++++++++++++ scripts/play-community-rendering.ps1 | 14 ++++++++++++++ scripts/play-foxhound.ps1 | 1 + 3 files changed, 39 insertions(+) create mode 100644 scripts/Test-NvidiaNgxOverride.ps1 create mode 100644 scripts/play-community-rendering.ps1 diff --git a/scripts/Test-NvidiaNgxOverride.ps1 b/scripts/Test-NvidiaNgxOverride.ps1 new file mode 100644 index 000000000..42395dbd1 --- /dev/null +++ b/scripts/Test-NvidiaNgxOverride.ps1 @@ -0,0 +1,24 @@ +# Detects NVIDIA App / NGX per-game DLSS override plugins (sl_*_override_0). +# When active, Streamline loads override DLLs instead of VICTORY_STREAMLINE_DIR and +# DLSS evaluate often fails with 0xbad00005 (see issue #449, #99). +param([switch]$Quiet) +$roots = @( + Join-Path $env:ProgramData 'NVIDIA\NGX\models' + 'C:\ProgramData\NVIDIA\NGX\models' +) +$hits = [System.Collections.Generic.List[string]]::new() +foreach ($root in $roots) { + if (-not (Test-Path -LiteralPath $root)) { continue } + Get-ChildItem -LiteralPath $root -Directory -Filter 'sl_*_override_*' -ErrorAction SilentlyContinue | + ForEach-Object { $hits.Add($_.FullName) } +} +if ($hits.Count -eq 0) { + if (-not $Quiet) { Write-Host 'NGX DLSS override: not detected under ProgramData\NVIDIA\NGX\models' } + return 0 +} +if (-not $Quiet) { + Write-Warning 'NVIDIA NGX DLSS override is present. Streamline may load override DLLs instead of nvidia-sdk.' + Write-Warning 'If cutscenes are black or DLSS logs 0xbad00005, disable DLSS Override for victory.exe in NVIDIA App.' + $hits | ForEach-Object { Write-Warning " $_" } +} +return 1 \ No newline at end of file diff --git a/scripts/play-community-rendering.ps1 b/scripts/play-community-rendering.ps1 new file mode 100644 index 000000000..6873d2713 --- /dev/null +++ b/scripts/play-community-rendering.ps1 @@ -0,0 +1,14 @@ +# 本地社区补丁栈 hefty/community-rendering(#33 #703 #280 #168 #814) +# 用法与 play-nvidia.ps1 完全相同,例如: +# .\scripts\play-community-rendering.ps1 -Exe 'D:\Entertainment\GTA6\game_scarlett_master.exe' -Dlss off +$repo = Split-Path $PSScriptRoot -Parent +$branch = (git -C $repo branch --show-current 2>$null) +if ($branch -ne 'hefty/community-rendering') { + Write-Warning "当前分支为 '$branch',不是 hefty/community-rendering。请先: git checkout hefty/community-rendering; cargo build --release -p victory" +} +$victory = Join-Path $repo 'target\release\victory.exe' +if (-not (Test-Path $victory)) { + Write-Error "未找到 $victory 。请先 cargo build --release -p victory" + exit 1 +} +& "$PSScriptRoot\play-nvidia.ps1" @args \ No newline at end of file diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1 index f04e0c27f..74d9f4417 100644 --- a/scripts/play-foxhound.ps1 +++ b/scripts/play-foxhound.ps1 @@ -125,6 +125,7 @@ if ($Dlss -ne 'off') { Write-Host "No NVIDIA files in ${sl}: running without DLSS and frame generation. Get-NVIDIA-DLSS.cmd in the" Write-Host "repository folder fetches them from NVIDIA once (about 70 MB); VICTORY_STREAMLINE_DIR names another folder." } + & "$PSScriptRoot\Test-NvidiaNgxOverride.ps1" | Out-Null } # AMD FSR 3 frame generation: made ready as DLSS Frame Generation is (on, or ready and off for the F1 menu). # auto: the layer uses it only where DLSS Frame Generation does not run; fsr: DLSS Frame Generation is not asked.