diff --git a/README.md b/README.md index 2fbe26718d..ca851f2533 100644 --- a/README.md +++ b/README.md @@ -55,10 +55,10 @@ 3. Double-click it. Windows may say the publisher is unknown (the file is not signed): "More info", then "Run anyway". -The supported Xbox Series build shows the stock Victory keyboard prompts by -default. Animated hold prompts retain their original icons. -Use `--set VICTORY_PROMPTS=gamepad` with `victory play` to show Xbox prompts. -The optional custom mouse-and-keyboard profile continues to use gamepad prompts. +Prompts follow the F1 settings only, nothing is detected: Xbox button prompts +by default, keyboard keys when CONTROLS is KEYBOARD or MOUSE AND KEYBOARD is on. +Animated hold prompts keep their original icons. A custom mouse-and-keyboard +bindings file keeps the gamepad pictures. - The first start asks once whether to download NVIDIA's DLSS and frame generation files (about 70 MB) from NVIDIA's own GitHub. They are NVIDIA's diff --git a/apps/victory/src/native_1440p.rs b/apps/victory/src/native_1440p.rs index 6983b5cfce..47f05141c2 100644 --- a/apps/victory/src/native_1440p.rs +++ b/apps/victory/src/native_1440p.rs @@ -193,9 +193,11 @@ pub(super) fn prepare(image: &mut PreparedImage, render_1080p: bool) -> Result<( // no more than 0x1FFFFF of it is left over (`0x247AF25`). Rounded to // 2 MiB: 0x5E00000 (94 MiB). The stock Series X 64 MiB had no room for // the legacy surfaces (the title's allocator asserted, `int3` at - // `0x56A2AFD`). + // `0x56A2AFD`). The UI targets stay 2560x1440 at every output size: sized + // for a wider output (3440x1440: 12.25 MiB more), more than 0x1FFFFF was + // left over and every start stopped at that assert (`int3` at `0x247AF2D`). let pool_size = u32::try_from( - (ui_surface_bytes(LEGACY_UI_WIDTH, LEGACY_UI_HEIGHT)? * 2 + ui_surface_bytes(width(), height())? * 2) + (ui_surface_bytes(LEGACY_UI_WIDTH, LEGACY_UI_HEIGHT)? * 2 + ui_surface_bytes(DEFAULT.0, DEFAULT.1)? * 2) .next_multiple_of(2 << 20), )?; let pool = field::<5>(image, UI_POOL)?; diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index 2d6beacc3d..3acffe2284 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -122,6 +122,11 @@ const SETTINGS: &[(&str, &str)] = &[ // 默认跳过人脸重定位和热浪过程;启用人脸修复的启动器会只保留热浪跳过。 // Left out: the face-relocation compute and the heat-haze pass ("VICTORY_LEAVE_OUT", "02384a60fda6f2d0,731a39171b568298"), + // Wave32: write-only last resort for every refused wave64 compute program + // (play clears other VICTORY_* from the surroundings; without this the + // layer's unset default can be missed if a settings file left the name + // empty or at 0. Kamioku on PR #1: picture only with =1.) + ("VICTORY_LDS_LAST_RESORT", "1"), // Pipelines the title makes are written down, for `victory warm` ("VICTORY_PIPELINE_BOOK", "1"), // Memory stack (skornuta): texture slots left unused are given back, old command allocators diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index a50991ecc8..f1912a7007 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -686,8 +686,14 @@ pub fn run( // generation is on (bound as before otherwise). let interposed = victory_hle::modules::fidelityfx::Interpose { inner: &with_dlls }; show(&exe_name, image.bind_imports(&interposed, policy)?); - if execute && std::env::var_os("VICTORY_PROMPTS").is_none_or(|mode| mode == "keys") { + // Prompts follow the settings only, nothing is detected: keyboard keys + // when CONTROLS is KEYBOARD or MOUSE AND KEYBOARD is on, the title's own + // Xbox pictures otherwise. (Keys used to be drawn unless + // VICTORY_PROMPTS said otherwise, so players on a pad saw keys.) + if execute && keyboard_selected() { show_keys_in_prompts(&image, build); + } else if execute { + println!("prompts gamepad pictures: CONTROLS is not KEYBOARD and MOUSE AND KEYBOARD is off"); } if execute { let size = image.info().size_of_image as usize; @@ -823,6 +829,32 @@ pub fn run( Ok(()) } +/// Whether the settings ask for keyboard prompts: CONTROLS is KEYBOARD +/// (`VICTORY_CONTROLS=keyboard`) or MOUSE AND KEYBOARD is on (`VICTORY_MNK=1`). +fn keyboard_selected() -> bool { + keyboard_selected_by(std::env::var("VICTORY_CONTROLS").ok().as_deref(), std::env::var("VICTORY_MNK").ok().as_deref()) +} + +fn keyboard_selected_by(controls: Option<&str>, mnk: Option<&str>) -> bool { + controls.is_some_and(|c| c.eq_ignore_ascii_case("keyboard")) || mnk == Some("1") +} + +#[cfg(test)] +mod prompt_choice_tests { + use super::keyboard_selected_by; + + /// Keys only when keyboard is selected; a pad setting or nothing set gives the Xbox pictures. + #[test] + fn keys_only_when_keyboard_is_selected() { + assert!(keyboard_selected_by(Some("keyboard"), None)); + assert!(keyboard_selected_by(None, Some("1"))); + assert!(keyboard_selected_by(Some("gamepad"), Some("1"))); + assert!(!keyboard_selected_by(None, None)); + assert!(!keyboard_selected_by(Some("gamepad"), None)); + assert!(!keyboard_selected_by(Some("dualsense"), Some("0"))); + } +} + #[cfg(windows)] fn show_keys_in_prompts( image: &victory_loader::LoadedImage, diff --git a/crates/victory-gpu/src/alias_rt.rs b/crates/victory-gpu/src/alias_rt.rs index ab33a63e9c..365e697d8d 100644 --- a/crates/victory-gpu/src/alias_rt.rs +++ b/crates/victory-gpu/src/alias_rt.rs @@ -42,11 +42,11 @@ const ST_PHYSICAL: usize = 2; const ST_OVERFLOW: usize = 3; const ST_FALLBACK: usize = 4; -/// Whether physical-page transient RT aliasing is enabled (on by default; -/// `VICTORY_ALIAS_TARGETS=0` disables). +/// Whether physical-page transient RT aliasing is enabled (off by default: +/// it left block artifacts; `VICTORY_ALIAS_TARGETS=1` turns it on). pub(crate) fn on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_TARGETS").is_none_or(|v| v != "0")) + *ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_TARGETS").is_some_and(|v| v == "1")) } /// Physical local VRAM bytes currently held by aliased RT heap chunks. diff --git a/crates/victory-gpu/src/compilemem.rs b/crates/victory-gpu/src/compilemem.rs index 5af27462ff..7352fa5911 100644 --- a/crates/victory-gpu/src/compilemem.rs +++ b/crates/victory-gpu/src/compilemem.rs @@ -76,6 +76,23 @@ fn on() -> bool { }) } +/// Whether, once free commit is under twice the commit floor, only one +/// compile runs at a time (`VICTORY_COMPILE_SERIAL`, on). Off with `=0`. +fn serial_near_commit() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COMPILE_SERIAL").is_none_or(|v| v != "0")) +} + +/// A Create*PipelineState that returned E_OUTOFMEMORY: raise the expected +/// cost so the next admits stay one-at-a-time until small compiles teach it +/// down again. +pub(crate) fn note_oom() { + let g = gate(); + let mut state = g.state.lock().unwrap_or_else(|e| e.into_inner()); + state.estimator.record(MOST); + g.changed.notify_all(); +} + /// What compiles are expected to take, from what they took. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(crate) struct Estimator { @@ -160,6 +177,19 @@ impl State { } else { Verdict::Allow }; + // Near the commit floor (under 2×): one compile at a time. The first + // guess of 1 GB under-counted mesh compiles that took ~2.8 GB + // (upstream #2303), so several were let through and then failed with + // 0x8007000E for good. `VICTORY_COMPILE_SERIAL=0` turns this off. + if gated + && serial_near_commit() + && !self.running.is_empty() + && let Some(f) = figures + && floors.commit > 0 + && f.free_commit < floors.commit.saturating_mul(2) + { + verdict = Verdict::Throttle; + } // Short of free physical memory (a soft floor): compiles go one at a // time, never refused for that alone. if verdict == Verdict::Throttle && self.running.is_empty() { @@ -443,6 +473,22 @@ mod tests { assert_eq!(admit(figures(0, 0), off, 12, 6 * GB, false), Verdict::Allow); } + #[test] + fn near_the_commit_floor_a_second_compile_waits() { + // 6 GB free over a 4 GB floor: admit alone would allow two of 1 GB, but + // under 2× the floor the serial rule holds the second. + let f = figures(30 * GB, 6 * GB); + let mut s = State::default(); + assert_eq!(s.try_start("a", f, floors(), 0, true, false).0, Verdict::Allow); + // Without the serial rule this would be Allow (6−1 ≥ 4). + assert_eq!(admit(f, floors(), 1, GB, false), Verdict::Allow); + // With it applied in try_start (and serial on by default): Throttle. + let second = s.try_start("b", f, floors(), 0, true, false).0; + if serial_near_commit() { + assert_eq!(second, Verdict::Throttle); + } + } + #[test] fn an_allocation_that_just_failed_lets_no_second_compile_start() { // Plenty of room, but the system just said out of memory: one goes on diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index e43be1c08e..5f889120dd 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -224,6 +224,57 @@ pub(crate) fn place_process() { }); } +/// On a hybrid processor (P + E cores), carve one physical P-core for +/// `victory-submit` alone (`VICTORY_SUBMIT_PCORE=1`, off by default). The +/// rest of the process keeps the remaining P-cores (and E-cores stay for the +/// title / pipeline makers via the usual fast-core selection). Aimed at +/// 20-thread Intel parts (i7-12700K class) where the submitting thread is the +/// frame wall (~50 ms) and sharing a P-core's SMT sibling costs idle GPU time. +fn carve_submit_pcore() { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask, SetProcessDefaultCpuSets}; + if submit_core_mode() == SubmitCore::Off || std::env::var_os("VICTORY_SUBMIT_PCORE").is_none_or(|v| v != "1") { + return; + } + let sets = cpu_sets(); + let classes: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.1)).collect(); + let fast = fast_of(&classes); + if fast.is_empty() { + tracing::info!("VICTORY_SUBMIT_PCORE=1: no hybrid P/E split; nothing carved"); + return; + } + let Some((id, others_fast)) = carve_core(&sets, &fast) else { + tracing::info!(fast = fast.len(), "VICTORY_SUBMIT_PCORE=1: could not carve a P-core"); + return; + }; + // Process default: every set except the carved P-core's physical core. + let carved_core = sets.iter().find(|s| s.0 == id).map(|s| s.3); + let others: Vec = sets + .iter() + .filter(|s| carved_core.is_none_or(|c| s.3 != c)) + .map(|s| s.0) + .collect(); + let every = sets.iter().fold(0usize, |m, s| m | 1 << s.2); + let (mut ours, mut all) = (0usize, 0usize); + // SAFETY: this process's own masks. + if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut ours, &mut all) } != 0 && ours & every != every { + tracing::warn!(mask = %format!("{ours:#x}"), "the process was started with an affinity mask: no P-core kept for the submitting thread"); + return; + } + // SAFETY: our own process and a list of the system's own set ids. + if unsafe { SetProcessDefaultCpuSets(GetCurrentProcess(), others.as_ptr(), others.len() as u32) } == 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "no P-core kept for the submitting thread: the process's sets were refused"); + return; + } + let _ = PROCESS_SETS.set(others); + SUBMIT_SET.store(id, std::sync::atomic::Ordering::Release); + SUBMIT_ALONE.store(true, std::sync::atomic::Ordering::Release); + tracing::info!( + set = id, + remaining_p = others_fast.len(), + "a physical P-core kept for the submitting thread alone (VICTORY_SUBMIT_PCORE=1)" + ); +} + /// Where the process is not put on one half ([`place_process`]): on a processor of one core class /// with two logical processors a core and six cores or more, one physical core (both its logical /// processors) is kept for `victory-submit` alone, every other thread of the process off it, as @@ -237,12 +288,14 @@ pub(crate) fn place_process() { fn carve_submit_core_alone() { use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask, SetProcessDefaultCpuSets}; if submit_core_mode() == SubmitCore::Off || std::env::var_os("VICTORY_SUBMIT_CORE_ALONE").is_none_or(|v| v != "1") { + carve_submit_pcore(); return; } let sets = cpu_sets(); let classes: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.1)).collect(); - // Two kinds of cores: the submitting thread is kept on the fast ones already. + // Two kinds of cores: prefer the hybrid P-core carve when asked. if !fast_of(&classes).is_empty() { + carve_submit_pcore(); return; } let mut cores: Vec = sets.iter().map(|s| s.3).collect(); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 784d0390b9..9226ce14e5 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2896,6 +2896,13 @@ pub(crate) const DYNAMIC: u32 = 1 << 18; /// `null - extra` can never underflow. const PORTABLE_DYNAMIC_CAP: u32 = DYNAMIC << 1; +/// The dynamic slots of a capped host heap without `VICTORY_DYNAMIC_SLOTS`: +/// 393,216, leaving the title 606,783. [`DYNAMIC`] ran out as a new area +/// streamed in (up to 1,900 draws dropped in five seconds: see-through +/// patches on the character and a ghosted picture); with these no draw was +/// dropped on the same walk, and no title slot past 475,711 was asked for. +const PORTABLE_DYNAMIC_DEFAULT: u32 = DYNAMIC + (DYNAMIC >> 1); + fn dynamic_slots_override() -> Option { static OVERRIDE: std::sync::OnceLock> = std::sync::OnceLock::new(); *OVERRIDE.get_or_init(|| { @@ -2930,7 +2937,7 @@ fn dynamic_slots_for(count: u32, null: u32, requested: Option) -> (u32, boo // `count`, while still granting unused headroom up to `ceiling` // (even count so dynamic pairs stay aligned). let spare = (null.saturating_sub(count) & !1).min(ceiling); - (spare.max(floor), false) + (spare.max(PORTABLE_DYNAMIC_DEFAULT.min(ceiling)).max(floor), false) } }; } @@ -9686,8 +9693,8 @@ void main() { #[test] fn dynamic_slots_for_portable_and_uncapped_hosts() { let nvidia_null = PORTABLE_VIEWS - 1; - assert_eq!(dynamic_slots_for(1_000_000, nvidia_null, None), (DYNAMIC, false)); - assert_eq!(dynamic_slots_for(1_048_576, nvidia_null, None), (DYNAMIC, false)); + assert_eq!(dynamic_slots_for(1_000_000, nvidia_null, None), (PORTABLE_DYNAMIC_DEFAULT, false)); + assert_eq!(dynamic_slots_for(1_048_576, nvidia_null, None), (PORTABLE_DYNAMIC_DEFAULT, false)); assert_eq!(dynamic_slots_for(1_000_000, nvidia_null, Some(393_216)), (393_216, false)); assert_eq!(dynamic_slots_for(1_000_000, nvidia_null, Some(524_288)), (524_288, false)); assert_eq!( @@ -9716,8 +9723,8 @@ void main() { }; // SAFETY: live heap query. assert_eq!(unsafe { default_heap.heap.GetDesc().NumDescriptors }, PORTABLE_VIEWS); - assert_eq!(default_heap.dynamic, DYNAMIC); - assert_eq!(default_heap.count, nvidia_null - DYNAMIC); + assert_eq!(default_heap.dynamic, PORTABLE_DYNAMIC_DEFAULT); + assert_eq!(default_heap.count, nvidia_null - PORTABLE_DYNAMIC_DEFAULT); let raised = HostHeap::new_with(false, 1_000_000, Some(nvidia_null), Some(393_216)) .expect("PORTABLE_VIEWS heap with 393,216 dynamic slots"); diff --git a/crates/victory-gpu/src/descriptor/slots.rs b/crates/victory-gpu/src/descriptor/slots.rs index 88727447bd..34aee68bb2 100644 --- a/crates/victory-gpu/src/descriptor/slots.rs +++ b/crates/victory-gpu/src/descriptor/slots.rs @@ -27,9 +27,70 @@ pub(crate) struct DynamicSlots { /// Level 1 coarse summary bitmap: bit `w` is `1` iff `bits[w] == u64::MAX` /// (or `w >= bits.len()`). full: Vec, + /// One flag per slot, scanned as before #704; the default (see [`plain`]). + /// `None`: the bitmaps above are used. + plain: Option>, +} + +/// The bitmap allocator only with `VICTORY_SLOTS_BITMAP=1`: with it, draws +/// on the character could pick up another draw's descriptors (blocky, +/// see-through patches while moving), so the plain scan is the default. +fn plain() -> bool { + if cfg!(test) { + return false; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SLOTS_BITMAP").is_none_or(|v| v != "1")) } impl DynamicSlots { + /// The pre-#704 next-fit scan over one flag per slot. + fn plain_alloc(&mut self, n: u32) -> Option { + let taken = self.plain.as_mut()?; + let end = taken.len(); + let enough = n > 0 && self.free >= n && n < self.too_long; + let n = n as usize; + let cursor = self.cursor as usize; + let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end); + let starts = (cursor..end).chain(0..second_end); + let mut run = 0; + let mut found = None; + let mut last = usize::MAX; + for at in starts.take(if enough { usize::MAX } else { 0 }) { + if at != last.wrapping_add(1) { + run = 0; + } + last = at; + run = if taken[at] { 0 } else { run + 1 }; + if run == n { + found = Some(at + 1 - n); + break; + } + } + let Some(first) = found else { + if enough { + self.too_long = self.too_long.min(n as u32); + } + return None; + }; + taken[first..first + n].fill(true); + self.free -= n as u32; + self.cursor = ((first + n) % end) as u32; + Some(first as u32) + } + + /// The pre-#704 release: flags cleared, the freed count given back. + fn plain_release(&mut self, at: u32, n: u32) -> u32 { + let Some(taken) = self.plain.as_mut() else { return 0 }; + let end = (at as usize).saturating_add(n as usize).min(taken.len()); + let Some(slots) = taken.get_mut(at as usize..end) else { return 0 }; + let given = slots.iter().filter(|t| **t).count() as u32; + slots.fill(false); + self.free += given; + self.too_long = u32::MAX; + given + } + /// Creates an allocator managing `len` initially free slots (`0..len`). pub(crate) fn new(len: u32) -> Self { if len == 0 { @@ -40,6 +101,7 @@ impl DynamicSlots { too_long: u32::MAX, bits: Vec::new(), full: Vec::new(), + plain: plain().then(Vec::new), }; } let words = (len as usize).div_ceil(64); @@ -61,6 +123,7 @@ impl DynamicSlots { too_long: u32::MAX, bits, full, + plain: plain().then(|| vec![false; len as usize]), } } @@ -74,6 +137,9 @@ impl DynamicSlots { #[cfg_attr(not(any(feature = "diagnostics", test)), allow(dead_code))] #[inline] pub(crate) fn is_taken(&self, index: u32) -> Option { + if let Some(taken) = &self.plain { + return taken.get(index as usize).copied(); + } (index < self.len).then(|| { let i = index as usize; (self.bits[i >> 6] >> (i & 63)) & 1 != 0 @@ -84,6 +150,9 @@ impl DynamicSlots { /// wrapping to `0` (extending past the cursor by `n - 1` so runs crossing /// the cursor are found, while never wrapping a single run past `len`). pub(crate) fn alloc(&mut self, n: u32) -> Option { + if self.plain.is_some() { + return self.plain_alloc(n); + } if n == 0 || n > self.len { return None; } @@ -125,6 +194,9 @@ impl DynamicSlots { /// overlapping, duplicate, zero-length, or out-of-range inputs. Returns /// the number of slots that were actually taken and freed. pub(crate) fn release(&mut self, at: u32, n: u32) -> u32 { + if self.plain.is_some() { + return self.plain_release(at, n); + } if at >= self.len || n == 0 { return 0; } @@ -141,6 +213,9 @@ impl DynamicSlots { /// Produces the exact same state as calling [`Self::release`] on each /// range in order. Returns total slots freed. pub(crate) fn release_batch(&mut self, ranges: impl IntoIterator) -> u32 { + if self.plain.is_some() { + return ranges.into_iter().map(|(at, n)| self.plain_release(at, n)).sum(); + } let mut total_given = 0u32; for (at, n) in ranges { if at >= self.len || n == 0 { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7959e73ad6..c3874f02f5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -147,8 +147,20 @@ pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool { (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms } +/// For tests (the memory bench, `membench`): the free physical RAM that +/// [`available_physical_ram`] and the pressure of [`crate::residency`] tell, +/// plus one; 0 (the default): the system's. What is kept by free RAM +/// (`ram_idle_ms`) is looked at with it. +#[cfg(test)] +pub(crate) static FREE_RAM_SAID: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`. pub(crate) fn available_physical_ram() -> Option { + #[cfg(test)] + if let Some(said) = FREE_RAM_SAID.load(Ordering::Relaxed).checked_sub(1) { + return Some(said); + } use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; // SAFETY: plain data the call fills in. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; @@ -730,6 +742,13 @@ pub(crate) fn references(object: &impl Interface) -> u32 { } } +/// Pressure-only retirement of idle host lists and oversized fetch buffers. +/// A process-wide opt-out for matched measurements and compatibility diagnosis. +fn idle_reclaim() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_IDLE_RECLAIM").is_none_or(|v| v != "0")) +} + /// Once a second, before a submission starts: lets go of what nothing /// names any more (copies of windows of title memory, staging buffers, /// host copies of textures the title fills). @@ -755,6 +774,9 @@ fn sweep() { crate::book::check(); crate::residency::refresh(); if crate::residency::pressured() { + if idle_reclaim() { + crate::list::trim_idle(now); + } trim_spare_uploads(); trim_spare_chunks(); crate::texback::trim_read_backs(); @@ -2855,6 +2877,13 @@ fn scratch_pool() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0")) } +/// Whether a list gives its scratch chunks back when its submission lands +/// ([`HostList::release_scratch`]; on by default, `VICTORY_SCRATCH_AT_LANDING=0`: at its reset). +fn scratch_at_landing() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_AT_LANDING").is_none_or(|v| v != "0")) +} + /// Things of some sizes that nothing holds now, kept for whoever next asks /// for one of the same size. struct Spare { @@ -3104,6 +3133,30 @@ fn give_chunks_to(chunks: Vec<(Chunk, u64)>, shared: bool) { drop(freed); } +/// [`give_chunks`] for a list whose submission has landed but which is reset only after the +/// bury lag ([`HostList::release_scratch`]): the chunks the spare pool takes go there, and +/// the others are handed back, to be freed at that reset as before (nothing is freed earlier +/// than it was). +fn spare_what_fits(chunks: Vec<(Chunk, u64)>) -> Vec<(Chunk, u64)> { + let mut kept = Vec::new(); + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + let limit = if keep_freed() && !crate::residency::limited_host_ram() { + SPARE_KEPT + } else { + SPARE_MOST + }; + for (chunk, size) in chunks { + match spare.give(chunk, size, limit) { + None => { + ALIVE[3].fetch_add(1, Ordering::Relaxed); + ALIVE[4].fetch_add(size, Ordering::Relaxed); + } + Some(chunk) => kept.push((chunk, size)), + } + } + kept +} + /// Bytes of spare scratch chunks freed by the trim ([`allocator_trim`]) /// since the start. pub(crate) static SPARE_TRIMMED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -3326,6 +3379,8 @@ struct CardWork { jobs_taken: u32, /// Where the pieces that differ are fetched to: PC memory, mapped. fetched: Option<(ID3D12Resource, usize, u64)>, + /// Last time this capacity was needed, not merely read from. + fetched_large_at: u64, /// The dwords of `differs` taken by plans whose results were not read /// yet. taken: u32, @@ -5889,6 +5944,8 @@ struct RelayFetch { sent: u64, /// Buffer, mapping, bytes. buffer: Option<(ID3D12Resource, usize, u64)>, + /// Last time this capacity was needed, not merely read from. + buffer_large_at: u64, /// Pieces caught while a later flight was writing them. suspects: torn::Suspects, /// What earlier fetches brought of flights not landed yet. @@ -6252,6 +6309,8 @@ mod fill_wait; pub(crate) mod indirects; mod font; mod lazy; +#[cfg(test)] +mod membench; pub(crate) mod gaps; mod menu; pub use menu::{settings_pad_capture, settings_pad_key}; @@ -6873,6 +6932,7 @@ impl Host { check: vec![list()?], fetch: list()?, fetched: None, + fetched_large_at: 0, jobs_taken: 0, taken: 0, out: 0, @@ -7526,12 +7586,49 @@ impl Host { event, sent: 0, buffer: None, + buffer_large_at: 0, suspects: torn::Suspects::default(), had: crate::land::Had::default(), }) } } + /// Reuse ordinary fetch capacity; release a peak only after two seconds + /// below that size and under memory pressure. Called between completed + /// fetch/merge operations, never while GPU or CPU users hold the mapping. + fn resize_fetch( + &self, + buffer: &mut Option<(ID3D12Resource, usize, u64)>, + large_at: &mut u64, + needed: u64, + ) { + let now = now_ms(); + let capacity = buffer.as_ref().map_or(0, |b| b.2); + let wanted = needed.next_multiple_of(16 << 20); + let grow = needed > capacity; + if wanted >= capacity { + *large_at = now; + } + let shrink = idle_reclaim() && crate::residency::pressured() + && wanted < capacity && now.saturating_sub(*large_at) >= 2_000; + if grow || shrink { + if wanted == 0 { + *buffer = None; + } else if grow { + // The old one, too small, is let go first: its memory may be + // what the new one needs (the last fetch on it was waited + // for). The new one steps down when refused (`fetchmem`); + // failed growth keeps the caller's allocation-failure path. + *buffer = None; + *buffer = self.fetch_buffer(needed); + } else if let Some(replacement) = self.shared_buffer(wanted).map(|(b, p)| (b, p as usize, wanted)) { + // Failed shrinking leaves a usable old allocation. + *buffer = Some(replacement); + } + *large_at = now; + } + } + /// [`relay`], on the thread that lands flights: for the plans of the /// flights being landed (the card has run them), the pieces their /// compares flagged are fetched, once each, with a list and a wait of @@ -7656,6 +7753,13 @@ impl Host { // The sends these flights ran behind, all a fetch on the copy queue // is known to have run behind. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0); + if let Some(f) = fetch.as_mut() { + // The preceding fetch and its CPU readers finished on this same + // relay thread before this call; none refers to the old mapping now. + self.resize_fetch(&mut f.buffer, &mut f.buffer_large_at, total); + #[cfg(test)] + membench::RELAY_FETCH.store(f.buffer.as_ref().map_or(0, |b| b.2), Ordering::Relaxed); + } if pieces.is_empty() { // Nothing to fetch: every send so far is older than the next // fetch, if that goes to the queue the sends went to. @@ -7669,10 +7773,6 @@ impl Host { let Some(f) = fetch.as_mut() else { fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); }; - if f.buffer.as_ref().is_none_or(|b| b.2 < total) { - let size = total.next_multiple_of(16 << 20); - f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); - } let Some((buffer, data, _)) = f.buffer.clone() else { if !crate::fetchmem::on() { fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); @@ -7925,6 +8025,7 @@ impl Host { } for detached in &mut flight.lists { detached.release_tables(); + detached.release_scratch(); } landed.push((flight.lists, flight.order)); crate::land::spent(crate::land::stat::READ_BACKS, telling) @@ -8072,11 +8173,10 @@ impl Host { crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); } let mut written = vec![0usize; plan.ranges.len()]; + // Serialized by CARD_WORK and the submission lock; the previous copy + // fence and CPU merge were waited for before returning. + self.resize_fetch(&mut work.fetched, &mut work.fetched_large_at, total); if !pieces.is_empty() { - if work.fetched.as_ref().is_none_or(|f| f.2 < total) { - let size = total.next_multiple_of(16 << 20); - work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); - } let Some((fetched, data, _)) = &work.fetched else { if !crate::fetchmem::on() { fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); @@ -8574,6 +8674,7 @@ impl Host { } for detached in &mut flight.lists { detached.release_tables(); + detached.release_scratch(); } landed.push((flight.lists, flight.order)); } @@ -9803,6 +9904,22 @@ impl HostList { false } + /// Its submission has landed: the card read its scratch chunks for the last time, so + /// the next lists may take them now ([`spare_what_fits`]) rather than at its reset, + /// after the bury lag (16 or 64 submissions, [`bury_lag`]; a list held its chunks all + /// that time, 130 MB for 42 landed lists in the memory bench at only 8 lists a frame). + /// Only with shared chunks ([`scratch_pool`]); `VICTORY_SCRATCH_AT_LANDING=0`: at the + /// reset, as before. + pub(crate) fn release_scratch(&self) { + if !scratch_pool() || !scratch_at_landing() { + return; + } + let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + (scratch.current, scratch.used) = (0, 0); + let chunks = std::mem::take(&mut scratch.chunks); + scratch.chunks = spare_what_fits(chunks); + } + /// Its prelude to [`PRELUDES`] (or gone, past [`PRELUDES_KEPT`]). Only /// after the list's last submission finished. pub(crate) fn give_prelude(&self) { diff --git a/crates/victory-gpu/src/host/membench.rs b/crates/victory-gpu/src/host/membench.rs new file mode 100644 index 0000000000..d8facbc9f4 --- /dev/null +++ b/crates/victory-gpu/src/host/membench.rs @@ -0,0 +1,899 @@ +//! A memory bench for the GPU side, without the game: synthetic frames go +//! through the title's own calls, and what each class of the layer holds is +//! read after a warm-up and at the end, with the process's private bytes and +//! the card's memory as the system counts it. It is to memory changes what +//! the differential shader oracle is to the translator: a change that makes +//! a class grow frame over frame, or keeps what pressure should let go, +//! shows in its table (and fails its checks). +//! +//! The title's side is the real one, called through the objects' tables as +//! the title calls them: two queues and a fence, command allocators and +//! lists, committed buffers in write-watched memory from a title allocator +//! (`crate::resource::use_allocator`, as the runtime's xmem), buffer copies, +//! submissions, a queue that waits for the other's fence, and the queue side +//! of a present. A frame `f`: +//! +//! - the title's CPU writes words of the source buffer and of memory outside +//! buffers (a heap of eight 4 MiB windows, one title buffer placed in it); +//! - six graphics lists, each: copies source to destination (a buffer whose +//! host copy a view made, so the copy is done on the card out of the list's +//! scratch, `HostList::place_copy`, and declared as written), a copy into a +//! 32 MiB buffer whose host copy is in the card's memory (compared and +//! fetched back), and a draw's read of the heap through a root view (the +//! steps of `draw::root_view`: `shadow::find`, `Shadow::refresh`), in two +//! submissions; +//! - two lists on a compute queue that first waits for the graphics queue's +//! fence: the submission is held, its host lists are taken from the +//! title's (`crate::list::detach_parts`), run when the graphics queue +//! signals, and given to the pool (`crate::list::recycle`). With the relay +//! on (`VICTORY_RELAY=2`, as runs have it) the graphics lists go the same +//! way, as flights; +//! - the queue side of a present (settle, release what queues hold) and the +//! frame count moves on. +//! +//! What it cannot reach without the game (or translated programs): draws and +//! dispatches, with what only they touch (descriptor heaps and their views, +//! textures and their host copies, staging and blocks, indirect arguments, +//! pipelines), the swap chain's copy, and the thin path (`VICTORY_THIN=1`). +//! +//! Each test wants a process of its own (it names the title allocator, and +//! the switches are read once): +//! +//! `cargo test -p victory-gpu --lib memory_bench_steady_state -- --ignored --nocapture` +//! +//! and the same with `VICTORY_RELAY=2 VICTORY_RELAY_COPY=1` for the relay's +//! paths (`scripts/play-foxhound.ps1` sets both). `VICTORY_MEMBENCH_STRICT=1` +//! also asserts that pressure lets go of what a spike made (the list pool, +//! spare scratch, fetch buffers). + +use std::ffi::c_void; + +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, +}; + +use super::*; +use crate::object::{HRESULT, IUNKNOWN, S_OK, This, slot}; + +const WRITE_WATCH: u32 = 0x20_0000; + +/// The bytes of the relay's fetch buffer (`Host::relay_card_back`), which +/// lives on the relay's thread. +pub(super) static RELAY_FETCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +const MB: u64 = 1 << 20; + +/// The source of the copies (the title's CPU writes it), their destination +/// (with a host copy in the PC's memory), and a buffer big enough for its +/// copy to be in the card's memory (16 MiB and up on a card of 12 GB). +const SRC: usize = 8 << 20; +const DST: usize = 4 << 20; +const BIG: usize = 32 << 20; +/// A copy of a frame's list, and of its one copy into the big buffer. +const COPY: usize = 16 << 10; +const BIG_COPY: usize = 256 << 10; +const COPIES: usize = 8; +/// What a draw reads through a root view. +const READ: u64 = 64 << 10; +/// The windows' grid (`crate::shadow::WINDOW`) and the heap's windows. +const WINDOW: usize = 4 << 20; +const WINDOWS: usize = 8; +/// Where draws read in a window: past the buffer placed in window 0. +const READ_AT: usize = 0x28_0000; +/// The buffer placed in the heap (a placed resource's memory): its +/// resource key, where it lies in window 0, its bytes. +const INNER_KEY: usize = 0x6d65_6d62_656e_6368; +const INNER_AT: usize = 1 << 20; +const INNER_LEN: usize = 1 << 20; +const GRAPHICS_LISTS: usize = 6; +const COMPUTE_LISTS: usize = 2; +/// The spike: a loading screen's many long lists at once, and copies of +/// 8 MiB into the big buffer (all of it written, all of it fetched back). +const SPIKE_LISTS: usize = 64; +const SPIKE_COPIES: usize = 2000; +const SPIKE_BIG: usize = 8 << 20; + +extern "system" fn title_alloc(size: usize, _attributes: u64) -> *mut c_void { + // SAFETY: a fresh allocation of ours. + unsafe { + VirtualAlloc( + std::ptr::null(), + size, + MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, + PAGE_READWRITE, + ) + } +} + +extern "system" fn title_free(at: *mut c_void, _attributes: u64) { + // SAFETY: one of `title_alloc`'s. + unsafe { VirtualFree(at, 0, MEM_RELEASE) }; +} + +fn release(object: This) -> u32 { + slot:: u32>(object, 0x10)(object) +} + +/// A title queue, called through its table (newer layouts have signal and +/// wait two slots later). +struct Queue { + this: This, + newer: bool, +} + +impl Queue { + fn new(kind: u32) -> Queue { + // The title's description: type, priority, flags, node mask. + let desc: [u32; 4] = [kind, 0, 0, 1]; + let mut this = std::ptr::null(); + assert_eq!( + crate::queue::create(std::ptr::null(), desc.as_ptr().cast(), &IUNKNOWN, &mut this), + S_OK + ); + Queue { + this, + newer: crate::device::newer(), + } + } + + fn execute(&self, lists: &[This]) { + slot::(self.this, 0x50)( + self.this, + lists.len() as u32, + lists.as_ptr(), + ); + } + + fn signal(&self, fence: This, value: u64) { + let at = if self.newer { 0x80 } else { 0x70 }; + assert_eq!( + slot:: HRESULT>(self.this, at)( + self.this, fence, value + ), + S_OK + ); + } + + fn wait(&self, fence: This, value: u64) { + let at = if self.newer { 0x88 } else { 0x78 }; + assert_eq!( + slot:: HRESULT>(self.this, at)( + self.this, fence, value + ), + S_OK + ); + } +} + +/// A title list with an allocator of its own, open after it is made. +struct List { + this: This, + allocator: This, + open: bool, +} + +impl List { + fn new(kind: u32) -> List { + let null = std::ptr::null(); + let (mut allocator, mut this) = (null, null); + assert_eq!( + crate::list::create_allocator(null, kind, &IUNKNOWN, &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, kind, allocator, null, &IUNKNOWN, &mut this), + S_OK + ); + List { + this, + allocator, + open: true, + } + } + + /// The title's reset, before it records the list again. + fn begin(&mut self) { + if !self.open { + let reset = slot:: HRESULT>(self.this, 0x50); + assert_eq!(reset(self.this, self.allocator, std::ptr::null()), S_OK); + self.open = true; + } + } + + fn copy(&self, dst: This, dst_offset: usize, src: This, src_offset: usize, len: usize) { + let copy = slot::(self.this, 0x78); + copy( + self.this, + dst, + dst_offset as u64, + src, + src_offset as u64, + len as u64, + ); + } + + /// A draw's read of title memory through a root view, as + /// `draw::root_view` does it for a view without a length. + fn draw_reads(&self, address: usize) { + crate::list::with_state(self.this, |list, _| { + let shadow = + crate::shadow::find(address as u64, 1).expect("a host copy of title memory"); + shadow.refresh(list, address as u64, READ.min(shadow.left(address as u64))); + }); + } + + fn end(&mut self) { + assert_eq!( + slot:: HRESULT>(self.this, 0x48)(self.this), + S_OK + ); + self.open = false; + } +} + +impl Drop for List { + fn drop(&mut self) { + release(self.this); + release(self.allocator); + } +} + +/// The title of the bench: its queues, fence, lists and memory. +struct Rig { + graphics: Queue, + compute: Queue, + fence: This, + drawn: Vec, + computed: Vec, + /// Title buffers: the resource and the address of its memory. + src: (This, usize), + dst: (This, usize), + big: (This, usize), + /// The heap's first window (the reservation is kept for the process: + /// host copies of its windows outlive the rig). + heap: usize, + frame: u64, +} + +impl Rig { + /// `None` without a host GPU. + fn new() -> Option { + host()?; + crate::resource::use_allocator(title_alloc, title_free); + let mut fence = std::ptr::null(); + assert_eq!( + crate::fence::create( + std::ptr::null(), + 0, + 0, + &crate::fence::FENCE_IIDS[0], + &mut fence + ), + S_OK + ); + let buffer = |size: usize| { + let resource = crate::resource::test_buffer(size as u64); + let (at, len) = crate::resource::buffer_bytes(resource).expect("a buffer"); + assert_eq!(len, size as u64); + (resource, at as usize) + }; + let (src, dst, big) = (buffer(SRC), buffer(DST), buffer(BIG)); + // Host copies made by views, as a draw's would. + crate::shadow::find(dst.1 as u64, 1).expect("the destination's host copy"); + let carded = crate::shadow::find(big.1 as u64, 1) + .expect("the big buffer's host copy") + .carded(); + // SAFETY: a reservation of ours, never freed. + let base = unsafe { + VirtualAlloc( + std::ptr::null(), + WINDOWS * WINDOW + WINDOW, + MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(base, 0); + let heap = base.next_multiple_of(WINDOW); + crate::shadow::register(INNER_KEY, (heap + INNER_AT) as u64, INNER_LEN as u64); + crate::shadow::find((heap + INNER_AT) as u64, 1).expect("the placed buffer's host copy"); + println!( + "memory bench: relay {}, flights (late) {}, the present settles {}, the big buffer's copy on the card {carded}", + relay(), + late(), + !late_free_present() + ); + Some(Rig { + graphics: Queue::new(0), + compute: Queue::new(2), + fence, + drawn: (0..GRAPHICS_LISTS).map(|_| List::new(0)).collect(), + computed: (0..COMPUTE_LISTS).map(|_| List::new(2)).collect(), + src, + dst, + big, + heap, + frame: 0, + }) + } + + /// Where a draw of the frame reads in window `w`. + fn read_at(&self, w: usize) -> usize { + self.heap + w * WINDOW + READ_AT + (self.frame as usize % 16) * READ as usize + } + + /// The title's CPU: new words in the source, a word in each window read. + fn title_writes(&self, windows: usize) { + let f = self.frame as usize; + // SAFETY: the rig's own title memory, inside the buffers and heap. + unsafe { + let src = self.src.1 as *mut u64; + for k in 0..64 { + src.add((f * 977 + k * 4111) % (SRC / 8)) + .write_volatile((f << 16 | k) as u64); + } + for w in 0..windows { + (self.read_at(w) as *mut u64) + .add(f % 512) + .write_volatile(f as u64); + } + } + } + + /// One frame; its draws read the first `windows` windows of the heap. + fn frame(&mut self, windows: usize) { + let f = self.frame as usize; + self.title_writes(windows); + let (src, dst, big) = (self.src.0, self.dst.0, self.big.0); + let reads: Vec = (0..GRAPHICS_LISTS + COMPUTE_LISTS) + .map(|i| self.read_at(i % windows)) + .collect(); + for (i, list) in self.drawn.iter_mut().enumerate() { + list.begin(); + for k in 0..COPIES { + let to = (f * 31 + i * COPIES + k) % (DST / COPY) * COPY; + let from = (f * 17 + k * 7 + i) % (SRC / COPY) * COPY; + list.copy(dst, to, src, from, COPY); + } + list.copy( + big, + (f * GRAPHICS_LISTS + i) % (BIG / BIG_COPY) * BIG_COPY, + src, + i * BIG_COPY, + BIG_COPY, + ); + list.draw_reads(reads[i]); + list.draw_reads(self.dst.1 + (f + i) % (DST / COPY) * COPY); + list.end(); + } + let drawn: Vec = self.drawn.iter().map(|l| l.this).collect(); + let half = GRAPHICS_LISTS / 2; + self.graphics.execute(&drawn[..half]); + self.graphics.execute(&drawn[half..]); + let value = self.frame + 1; + self.compute.wait(self.fence, value); + for (j, list) in self.computed.iter_mut().enumerate() { + list.begin(); + for k in 0..COPIES / 2 { + let to = (f * 13 + j * COPIES + k + DST / COPY / 2) % (DST / COPY) * COPY; + list.copy(dst, to, src, (f + k) % (SRC / COPY) * COPY, COPY); + } + list.draw_reads(reads[GRAPHICS_LISTS + j]); + list.end(); + } + let computed: Vec = self.computed.iter().map(|l| l.this).collect(); + self.compute.execute(&computed); + self.graphics.signal(self.fence, value); + present(); + self.frame += 1; + } + + /// A loading screen's spike: many long lists in one held submission, + /// and the big buffer written and fetched back whole. The title lets + /// go of those lists afterwards. + fn spike(&mut self) { + let value = self.frame + 1; + let (src, dst, big) = (self.src.0, self.dst.0, self.big.0); + let mut heavy = List::new(0); + for k in 0..BIG / SPIKE_BIG { + heavy.copy(big, k * SPIKE_BIG, src, 0, SPIKE_BIG); + } + heavy.end(); + self.compute.wait(self.fence, value); + let mut lists: Vec = (0..SPIKE_LISTS).map(|_| List::new(2)).collect(); + for (i, list) in lists.iter_mut().enumerate() { + for k in 0..SPIKE_COPIES { + list.copy(dst, (k * 4096 + i * 256) % DST, src, (k * 512) % SRC, 256); + } + list.end(); + } + self.graphics.execute(&[heavy.this]); + self.compute + .execute(&lists.iter().map(|l| l.this).collect::>()); + self.graphics.signal(self.fence, value); + present(); + self.frame += 1; + quiesce(); + } +} + +impl Drop for Rig { + fn drop(&mut self) { + quiesce(); + self.drawn.clear(); + self.computed.clear(); + crate::shadow::unregister(INNER_KEY, (self.heap + INNER_AT) as u64); + for object in [ + self.src.0, + self.dst.0, + self.big.0, + self.graphics.this, + self.compute.this, + self.fence, + ] { + release(object); + } + } +} + +/// The queue side of the title's present (`crate::queue::present`): what +/// was sent ahead is settled unless the present goes ahead too, and what +/// queues hold runs; then the frame count moves on. +fn present() { + if late() && !late_free_present() { + settle_for_present(); + crate::queue::release_held(false); + settle_for_present(); + } else if late() { + crate::queue::release_held(false); + } + crate::queue::release_held(true); + crate::frame::test_advance(); +} + +/// Nothing in the air and nothing held: for a census. +fn quiesce() { + settle_now(WHY_SYNC); + crate::queue::release_held(true); + settle_now(WHY_SYNC); +} + +#[derive(Clone, Copy, PartialEq)] +enum Unit { + Count, + Bytes, +} + +/// How far an item may move between two censuses of a steady state. +#[derive(Clone, Copy)] +enum Flat { + /// Not looked at (the working set, uses counted since the start). + Any, + /// Up to this many of the item's unit. + Within(u64), +} + +#[derive(Clone)] +struct Item { + class: &'static str, + what: &'static str, + unit: Unit, + flat: Flat, + value: u64, +} + +/// What the layer holds now, by class, with the process and the card. +#[rustfmt::skip] +fn census() -> Vec { + use Flat::{Any, Within}; + use Unit::{Bytes, Count}; + use std::sync::atomic::Ordering::Relaxed; + let mut items = Vec::new(); + let mut add = |class, what, unit, flat, value| { + items.push(Item { class, what, unit, flat, value }); + }; + let (working, private) = process_memory(); + add("process", "private bytes", Bytes, Within(16 * MB), private); + add("process", "working set", Bytes, Any, working); + let [own, shared] = host().and_then(|h| h.video_memory_groups()).unwrap_or_default(); + add("card", "its own memory in use", Bytes, Within(16 * MB), own[1]); + add("card", "PC memory shared with it in use", Bytes, Within(16 * MB), shared[1]); + let alive = ALIVE.each_ref().map(|a| a.load(Relaxed)); + let lists = LISTS.each_ref().map(|l| l.load(Relaxed)); + let made = MADE.each_ref().map(|m| m.load(Relaxed)); + let (idle, idle_bytes) = crate::list::idle(); + let (landed, landed_scratch) = { + let line = line(); + let lists = line.landed.iter().flat_map(|(l, _)| l.iter()); + let scratch = lists.clone().map(|l| l.host().scratch_kept()).sum::(); + (lists.count() as u64, scratch) + }; + add("host lists", "alive", Count, Within(16), alive[0]); + add("host lists", "idle in the pool", Count, Within(16), idle as u64); + add("host lists", "scratch the idle ones keep", Bytes, Within(8 * MB), idle_bytes); + add("host lists", "landed, waiting for the bury lag", Count, Within(64), landed); + add("host lists", "scratch the landed ones keep", Bytes, Within(32 * MB), landed_scratch); + add("host lists", "made since the start", Count, Within(8), lists[0]); + add("host lists", "preludes made", Count, Within(8), lists[1]); + add("host lists", "never reset", Count, Any, lists[3]); + add("list scratch", "chunks alive", Count, Within(16), alive[1]); + add("list scratch", "their bytes", Bytes, Within(32 * MB), alive[2]); + add("list scratch", "spare chunks", Count, Within(16), alive[3]); + add("list scratch", "spare bytes", Bytes, Within(32 * MB), alive[4]); + add("list scratch", "taken from the spare ones", Count, Any, alive[5]); + add("list uploads", "alive", Count, Within(16), alive[6]); + add("list uploads", "their bytes", Bytes, Within(32 * MB), alive[7]); + let copies = crate::shadow::memory(); + let on_card = crate::shadow::live_span_bytes(); + add("host copies", "alive", Count, Within(4), copies[0]); + add("host copies", "title bytes they copy", Bytes, Within(8 * MB), copies[1]); + add("host copies", "on the card (copies, windows)", Bytes, Within(8 * MB), on_card); + add("windows", "alive", Count, Within(2), copies[2]); + add("windows", "their bytes", Bytes, Within(8 * MB), copies[3]); + add("windows", "bytes over title buffers", Bytes, Within(8 * MB), windows_over_buffers()); + add("windows", "let go since the start", Count, Any, crate::shadow::windows()[0]); + add("snapshots", "kept for reuse", Count, Within(16), copies[4]); + add("snapshots", "bytes they reserve", Bytes, Within(32 * MB), copies[5]); + let (fetch, preludes) = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map_or( + (0, 0), + |w| (w.fetched.as_ref().map_or(0, |f| f.2), (w.sync.len() + w.check.len()) as u64), + ); + add("card copies", "fetch buffer (no relay)", Bytes, Within(0), fetch); + add("card copies", "fetch buffer (relay)", Bytes, Within(0), RELAY_FETCH.load(Relaxed)); + add("card copies", "send and compare lists kept", Count, Within(4), preludes); + let staged = crate::texture::memory(); + let blocks = crate::pool::memory(); + add("staging", "alive", Count, Within(4), staged[0]); + add("staging", "their bytes", Bytes, Within(8 * MB), staged[1]); + add("staging", "let go since the start", Count, Any, crate::texture::let_go()[0]); + add("blocks", "of textures", Bytes, Within(0), blocks[0] * MB); + add("blocks", "of staging", Bytes, Within(0), blocks[1] * MB); + let textures = crate::resource::HOST_TEXTURES[0].load(Relaxed); + add("host textures", "alive", Count, Within(0), textures); + let retired: usize = RETIRED.iter().map(|shard| shard.lock().unwrap_or_else(|e| e.into_inner()).len()).sum(); + add("retired", "waiting for the bury lag", Count, Within(256), retired as u64); + // Made since the start: a steady state makes (next to) none. + add("made", "upload buffers", Count, Within(8), made[0]); + add("made", "upload bytes", Bytes, Any, made[1]); + add("made", "shared buffers", Count, Within(8), made[2]); + add("made", "shared bytes", Bytes, Any, made[3]); + add("made", "card buffers", Count, Within(8), made[4]); + add("made", "card bytes", Bytes, Any, made[5]); + items +} + +/// The process's working set and private bytes (committed), from Windows. +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + if unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) } == 0 { + return (0, 0); + } + (c.WorkingSetSize as u64, c.PagefileUsage as u64) +} + +/// The bytes of windows that lie over title buffers (memory that a buffer's +/// host copy may copy as well). +fn windows_over_buffers() -> u64 { + let spans = crate::shadow::spans(); + let (windows, buffers): (Vec<_>, Vec<_>) = spans.iter().partition(|s| s.2); + windows + .iter() + .map(|&&(at, len, _)| { + buffers + .iter() + .map(|&&(b, n, _)| (at + len).min(b + n).saturating_sub(at.max(b))) + .sum::() + }) + .sum() +} + +fn shown(unit: Unit, value: i128) -> String { + match unit { + Unit::Count => format!("{value}"), + Unit::Bytes => format!("{:.1} MB", value as f64 / MB as f64), + } +} + +/// The censuses side by side, and what changed from the first to the last +/// (per frame over `frames`, if given). +fn table(heading: &str, columns: &[(&str, &[Item])], frames: Option) { + println!("\n{heading}"); + let mut line = format!("{:<14} {:<34}", "class", "item"); + for (name, _) in columns { + line += &format!(" {name:>14}"); + } + line += &format!(" {:>12}", "change"); + if frames.is_some() { + line += &format!(" {:>12}", "per frame"); + } + println!("{line}"); + let (first, last) = (columns[0].1, columns[columns.len() - 1].1); + for (i, item) in first.iter().enumerate() { + let mut line = format!("{:<14} {:<34}", item.class, item.what); + for (_, census) in columns { + line += &format!(" {:>14}", shown(item.unit, i128::from(census[i].value))); + } + let change = i128::from(last[i].value) - i128::from(item.value); + let sign = if change > 0 { "+" } else { "" }; + line += &format!( + " {:>12}", + if change == 0 { + "-".to_owned() + } else { + format!("{sign}{}", shown(item.unit, change)) + } + ); + if let Some(frames) = frames { + let per = change as f64 / frames.max(1) as f64; + line += &format!( + " {:>12}", + match item.unit { + Unit::Count => format!("{per:.2}"), + Unit::Bytes => format!("{:.1} KB", per / 1024.0), + } + ); + } + println!("{line}"); + } +} + +/// The items that moved more than they may in a steady state. +fn grown(before: &[Item], after: &[Item]) -> Vec { + before + .iter() + .zip(after) + .filter_map(|(a, b)| match a.flat { + Flat::Within(most) if a.value.abs_diff(b.value) > most => Some(format!( + "{} {}: {} to {}", + a.class, + a.what, + shown(a.unit, i128::from(a.value)), + shown(a.unit, i128::from(b.value)) + )), + _ => None, + }) + .collect() +} + +fn value(census: &[Item], class: &str, what: &str) -> u64 { + census + .iter() + .find(|i| i.class == class && i.what == what) + .map_or(0, |i| i.value) +} + +/// Frames run, each at least `least` long (a title's pace, so that the +/// once-a-second sweep comes by). +fn frames(rig: &mut Rig, n: u64, windows: usize, least: std::time::Duration) { + for _ in 0..n { + let started = std::time::Instant::now(); + rig.frame(windows); + if let Some(rest) = least.checked_sub(started.elapsed()) { + std::thread::sleep(rest); + } + } +} + +/// Frames until `ms` milliseconds went by, at 60 a second. +fn frames_for(rig: &mut Rig, ms: u64, windows: usize) -> u64 { + let started = std::time::Instant::now(); + let mut n = 0; + while started.elapsed().as_millis() < u128::from(ms) || n < 8 { + frames(rig, 1, windows, std::time::Duration::from_millis(16)); + n += 1; + } + n +} + +/// The steady state: after a warm-up, frame after frame of the same work +/// holds the same memory in every class. +#[test] +#[ignore = "on the card; a process of its own: cargo test -p victory-gpu --lib memory_bench_steady_state -- --ignored --nocapture"] +fn memory_bench_steady_state() { + const WARM: u64 = 60; + const MEASURED: u64 = 240; + let Some(mut rig) = Rig::new() else { + eprintln!("no host GPU: nothing measured"); + return; + }; + let pace = std::time::Duration::from_millis(8); + let started = std::time::Instant::now(); + frames(&mut rig, WARM, WINDOWS, pace); + quiesce(); + let warm = census(); + let measured = std::time::Instant::now(); + frames(&mut rig, MEASURED, WINDOWS, pace); + quiesce(); + let end = census(); + println!( + "memory bench, steady state: {WARM} frames of warm-up, {MEASURED} measured in {:.1} s ({:.1} s in all)", + measured.elapsed().as_secs_f64(), + started.elapsed().as_secs_f64() + ); + table( + "what each class holds", + &[("after warm-up", &warm), ("at the end", &end)], + Some(MEASURED), + ); + let grown = grown(&warm, &end); + drop(rig); + assert!( + grown.is_empty(), + "memory grew in the steady state: {grown:#?}" + ); + // Lists whose submission has landed give their scratch chunks back then, not at their + // reset after the bury lag (`HostList::release_scratch`; `VICTORY_SCRATCH_AT_LANDING=0`: not). + if super::scratch_at_landing() { + let kept = value(&end, "host lists", "scratch the landed ones keep"); + assert_eq!(kept, 0, "landed lists keep {kept} bytes of scratch"); + } +} + +/// Pressure: what idles while the PC has room is kept (five minutes with +/// 12 GiB free, ten seconds on a PC of 32 GB or less); told that only 1 GiB +/// is free (`FREE_RAM_SAID`, which `crate::residency` hears too), the same +/// idle memory is let go within a few seconds. Then what pressure does not +/// reach is listed (and with `VICTORY_MEMBENCH_STRICT=1` asserted to come +/// down). +#[test] +#[ignore = "on the card; a process of its own: cargo test -p victory-gpu --lib memory_bench_pressure_lets_idle_go -- --ignored --nocapture"] +fn memory_bench_pressure_lets_idle_go() { + use std::sync::atomic::Ordering::Relaxed; + const WARM: u64 = 40; + /// Longer than the idle time under pressure (2 s) and the sweep's second. + const IDLE_MS: u64 = 3_500; + let Some(mut rig) = Rig::new() else { + eprintln!("no host GPU: nothing measured"); + return; + }; + let pace = std::time::Duration::from_millis(16); + frames(&mut rig, WARM, WINDOWS, pace); + quiesce(); + let warm = census(); + rig.spike(); + // Until the spike's lists are past the bury lag and in the pool. + frames(&mut rig, 32, WINDOWS, pace); + quiesce(); + let spiked = census(); + // Idle: only window 0 is read from here on, with the PC's own free RAM. + let free = available_physical_ram().unwrap_or(0); + let calm = frames_for(&mut rig, IDLE_MS, 1); + quiesce(); + let roomy = census(); + // The same, with 1 GiB free as far as the layer can tell. + FREE_RAM_SAID.store((1u64 << 30) + 1, Relaxed); + let pressed = frames_for(&mut rig, IDLE_MS, 1); + quiesce(); + let short = census(); + FREE_RAM_SAID.store(0, Relaxed); + println!( + "memory bench, pressure: {WARM} frames, the spike ({SPIKE_LISTS} lists of {SPIKE_COPIES} copies, {} MB fetched back), \ + 32 frames; idle {calm} frames with {} MB free, {pressed} frames told 1024 MB", + BIG >> 20, + free >> 20 + ); + table( + "what each class holds", + &[ + ("before spike", &warm), + ("after spike", &spiked), + ("idle, roomy", &roomy), + ("idle, short", &short), + ], + None, + ); + let windows = |c: &[Item]| value(c, "windows", "alive"); + // Kept by free RAM: idle windows stay while 12 GiB are free. + if free >= 13u64 << 30 { + assert_eq!( + windows(&roomy), + windows(&spiked), + "idle windows are kept while the PC has room" + ); + } else { + println!( + "(only {} MB free: the retention by free RAM is not looked at)", + free >> 20 + ); + } + // Let go under pressure: all but the window still read. + assert!( + windows(&short) <= 1, + "idle windows are let go under pressure: {} alive", + windows(&short) + ); + // What pressure does not reach. + let kept: Vec<(&str, &str)> = [ + ("host lists", "idle in the pool"), + ("list scratch", "spare bytes"), + ("card copies", "fetch buffer (no relay)"), + ("card copies", "fetch buffer (relay)"), + ("process", "private bytes"), + ] + .into_iter() + .filter(|&(class, what)| { + value(&short, class, what) > value(&warm, class, what) + && value(&short, class, what) >= value(&spiked, class, what) + }) + .collect(); + for &(class, what) in &kept { + println!( + "kept under pressure since the spike: {class} {what}: {} before it, {} under pressure", + value(&warm, class, what), + value(&short, class, what) + ); + } + drop(rig); + if std::env::var_os("VICTORY_MEMBENCH_STRICT").is_some_and(|v| v == "1") { + assert!( + kept.is_empty(), + "pressure keeps what a spike made: {kept:?}" + ); + } +} + +/// Retirement must allow a second burst to allocate/reuse storage and return +/// the same bytes, in both relay and synchronous processes. +#[test] +#[ignore = "on the card; a process of its own; exercise reclamation and regrowth"] +fn memory_bench_reclaims_and_regrows_with_correct_bytes() { + use std::sync::atomic::Ordering::Relaxed; + let Some(mut rig) = Rig::new() else { + eprintln!("no host GPU: nothing measured"); + return; + }; + struct Pressure; + impl Drop for Pressure { + fn drop(&mut self) { FREE_RAM_SAID.store(0, Relaxed); } + } + let _pressure = Pressure; + let pace = std::time::Duration::from_millis(16); + frames(&mut rig, 40, WINDOWS, pace); + for round in 0..2 { + FREE_RAM_SAID.store(0, Relaxed); + // Refresh the cached pressure state before the next burst; otherwise + // a long burst may still retire its capacity using the previous round. + crate::residency::refresh(); + quiesce(); + // Make every piece differ in both bursts so the second one must + // grow the fetch buffer again, rather than reuse a small matching tail. + // SAFETY: the owned source allocation is idle and has SRC bytes. + unsafe { std::slice::from_raw_parts_mut(rig.src.1 as *mut u8, SRC).fill(0x35 + round); } + rig.spike(); + let active_fetch = if relay() { "fetch buffer (relay)" } else { "fetch buffer (no relay)" }; + let fetched = value(&census(), "card copies", active_fetch); + assert!(fetched >= BIG as u64, "round {round}: the burst fetched only {fetched} bytes of capacity" ); + // SAFETY: the rig owns both mapped allocations and spike waited for + // every submitted copy and merge; no CPU or GPU writer is outstanding. + unsafe { + let want = std::slice::from_raw_parts(rig.src.1 as *const u8, SPIKE_BIG); + let got = std::slice::from_raw_parts(rig.big.1 as *const u8, BIG); + for (chunk, bytes) in got.chunks_exact(SPIKE_BIG).enumerate() { + assert!(bytes == want, "round {round}, fetched chunk {chunk} differs"); + } + } + frames(&mut rig, 32, WINDOWS, pace); + quiesce(); + let peak = census(); + + FREE_RAM_SAID.store((1u64 << 30) + 1, Relaxed); + frames_for(&mut rig, 3_500, 1); + quiesce(); + let short = census(); + assert!(value(&short, "host lists", "idle in the pool") < value(&peak, "host lists", "idle in the pool"), + "round {round}: old idle lists were retained"); + for what in ["fetch buffer (no relay)", "fetch buffer (relay)"] { + let before = value(&peak, "card copies", what); + if before > 16 << 20 { + assert!(value(&short, "card copies", what) < before, "round {round}: {what} retained its peak"); + } + } + println!("reclaim/regrow round {round}: copied bytes match; idle lists and peak fetch capacity reclaimed"); + } +} diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs index a82eff241a..46d812b4ad 100644 --- a/crates/victory-gpu/src/host/panel.rs +++ b/crates/victory-gpu/src/host/panel.rs @@ -786,9 +786,12 @@ fn advice(s: &Sample) -> Vec { ); } if s.making == 0 && s.dropped >= 1.0 { + // Dropped draws with nothing being made: Wave32 LDS refusals, Create* + // WaveSize(64) rejects, or other permanent pipeline misses — the OSD + // used to imply only "cannot convert", which hid the VICTORY_LDS_* levers. add( format!("NOTE: {:.0} DRAWS SKIPPED, THEIR SHADERS CANNOT BE CONVERTED YET", s.dropped), - "NOTHING ON YOUR SIDE. A LATER BUILD FIXES THESE", + "VICTORY_LDS_LAST_RESORT=1 ON WAVE32, OR A LATER BUILD", ); } out diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 25790e328a..38c50dedcd 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -308,6 +308,12 @@ impl Detached { // The submitted host recording was taken from the title list. self._state.tables_done(true); } + + /// Gives the list's scratch chunks to the next lists once its submission has landed + /// ([`crate::host::HostList::release_scratch`]), like [`Self::release_tables`]. + pub(crate) fn release_scratch(&self) { + self.host.release_scratch(); + } } /// A host list that has run and waits to be used again, the bytes of @@ -339,6 +345,34 @@ static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::ne #[cfg(windows)] const IDLE_MOST: (usize, u64) = (512, 256 << 20); +/// For the memory bench (`crate::host::membench`): the host lists idle in +/// [`IDLE`] and the scratch bytes they keep. +#[cfg(all(windows, test))] +pub(crate) fn idle() -> (usize, u64) { + let idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + (idle.0.len(), idle.1) +} + +/// Drop old excess lists only under pressure. Recent lists and a small warm +/// reserve stay reusable; only reset, GPU-complete lists are in IDLE. +#[cfg(windows)] +pub(crate) fn trim_idle(now: u64) { + const WARM: usize = 16; + const REST_MS: u64 = 2_000; + let retired = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + // Share the upstream age calculation; pressure adds a warm reserve. + let n = stale(idle.0.iter().map(|entry| entry.2), now, REST_MS) + .min(idle.0.len().saturating_sub(WARM)); + let retired: Vec = idle.0.drain(..n).collect(); + idle.1 -= retired.iter().map(|entry| entry.1).sum::(); + retired + }; + TRIMMED_LISTS.fetch_add(retired.len() as u64, std::sync::atomic::Ordering::Relaxed); + // Releasing D3D12 objects and returning scratch must not hold the pool lock. + drop(retired); +} + // Idle-list trim: memory stack by skornuta (skornuta/victory-memory-stack 57fb136, GPL-3.0), // patch 13 (and the idle trim of its base). diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 8792742c9b..fac4b3e3b1 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -830,8 +830,24 @@ pub(crate) fn pipeline( let Some(_permit) = crate::compilemem::begin(name) else { return Err(crate::memguard::refusal()); }; - MADE.fetch_add(1, Ordering::Relaxed); - return create(); + // Same as the library path below: a driver OOM is deferred, not final. + return match create() { + Ok(pso) => { + MADE.fetch_add(1, Ordering::Relaxed); + Ok(pso) + } + Err(e) if e.code() == windows::Win32::Foundation::E_OUTOFMEMORY => { + crate::residency::allocation_error(&e); + crate::compilemem::note_oom(); + crate::memguard::refuse_compile( + name, + crate::memguard::Verdict::Commit, + crate::memguard::figures_now(), + ); + Err(crate::memguard::refusal()) + } + Err(e) => Err(e), + }; }; let began = std::time::Instant::now(); let (loaded, named, held, during_save) = if never_load() { @@ -893,7 +909,27 @@ pub(crate) fn pipeline( return Err(crate::memguard::refusal()); }; let _call = call("make", name); - create()? + // A Create*PipelineState that returns E_OUTOFMEMORY is the same class of + // failure as a compile the memory gate put off: the driver's compiler + // found no commit after we let it start (the guess was short, or another + // thread took the rest). Record it as deferred so `pipeline::make` tries + // again once memory frees, instead of refusing the key for the rest of + // the run (v2026.11.29.01 black screen: ~2,000 pipelines at 0x8007000E, + // retried=0, then 10 s screen waits on made=false; upstream #2303/#2564). + match create() { + Ok(pso) => pso, + Err(e) if e.code() == windows::Win32::Foundation::E_OUTOFMEMORY => { + crate::residency::allocation_error(&e); + crate::compilemem::note_oom(); + crate::memguard::refuse_compile( + name, + crate::memguard::Verdict::Commit, + crate::memguard::figures_now(), + ); + return Err(crate::memguard::refusal()); + } + Err(e) => return Err(e), + } }; MADE.fetch_add(1, Ordering::Relaxed); MAKE_US.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index ef3117d9ce..923eb48456 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -985,10 +985,29 @@ fn wait_free_only() -> bool { /// are past their budget. In one run's world loading every screen wait that /// reached the 10 s budget ended without the pipeline (55 waits, 550 s) and /// 34 of the 43 waits after such a one ran out again, while every wait under -/// 5 s got its pipeline. `VICTORY_SCREEN_WAIT_ONCE=1`; off by default. +/// 5 s got its pipeline. On by default since v2026.11.29.01's black-screen +/// stalls (`VICTORY_SCREEN_WAIT_ONCE=0` restores the old forever-retry). fn screen_wait_once() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_SCREEN_WAIT_ONCE").is_some_and(|v| v == "1")) + *ON.get_or_init(|| std::env::var_os("VICTORY_SCREEN_WAIT_ONCE").is_none_or(|v| v != "0")) +} + +/// Waits for a build or a memory deferral. Returns whether the budget ran out. +fn wait_for_pipeline(p: &Pending, started: Instant, budget: Duration) -> bool { + let (lock, done) = &DONE; + let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); + // A compile the memory guard (or a driver E_OUTOFMEMORY) put off notifies + // here with `made` still empty and `retry_waits` set: leave at once instead + // of spending the rest of the screen budget on a cooldown (upstream #2188). + while p.made.get().is_none() && !p.retry_waits() { + let rest = budget.saturating_sub(started.elapsed()); + if rest.is_zero() { + return true; + } + let _span = crate::timeline::span("wait for demanded pipeline"); + held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; + } + false } /// Waits for `p` while frame `frame` has budget left. @@ -1036,22 +1055,13 @@ fn wait(p: &Pending, frame: u64) { if p.waiters.fetch_add(1, Ordering::SeqCst) == 0 { boost(p, true); } - let (lock, done) = &DONE; - let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); - while p.made.get().is_none() { - let rest = left.saturating_sub(started.elapsed()); - if rest.is_zero() { - break; - } - let _span = crate::timeline::span("wait for demanded pipeline"); - held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; - } - drop(held); + let timed_out = wait_for_pipeline(p, started, left); if p.waiters.fetch_sub(1, Ordering::SeqCst) == 1 && p.made.get().is_none() { boost(p, false); } let waited = started.elapsed().min(left); if screen + && timed_out && screen_wait_once() && p.made.get().is_none() && !p.ran_out.swap(true, Ordering::Relaxed) @@ -1872,6 +1882,30 @@ mod tests { /// A compile the memory guard put off is not recorded as refused: the /// pipeline is made again once the pause is over and the memory is back. + #[test] + fn a_deferred_compile_exits_the_wait_without_a_timeout() { + let p = Pending::new(Vec::new(), None); + assert!(wait_for_pipeline(&p, Instant::now(), Duration::ZERO)); + std::thread::scope(|threads| { + let (starting, started) = std::sync::mpsc::channel(); + let (result, finished) = std::sync::mpsc::channel(); + let pipeline = &p; + threads.spawn(move || { + starting.send(()).unwrap(); + let timed_out = wait_for_pipeline(pipeline, Instant::now(), Duration::from_secs(5)); + result.send(timed_out).unwrap(); + }); + started.recv().unwrap(); + let (lock, done) = &DONE; + let _held = lock.lock().unwrap_or_else(|error| error.into_inner()); + p.retry_at.store(u64::MAX, Ordering::Relaxed); + done.notify_all(); + drop(_held); + assert!(!finished.recv_timeout(Duration::from_secs(2)).expect("waiter left on deferral")); + assert!(p.made.get().is_none()); + }); + } + #[test] fn a_compile_put_off_for_memory_is_tried_again_not_recorded() { let slot: OnceLock> = OnceLock::new(); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index a3d8da421a..a2b6022c50 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -722,7 +722,7 @@ pub(crate) fn texture_widest_free() -> u64 { } /// For the memory line: blocks of textures and of staging buffers, in MiB. -#[cfg(feature = "diagnostics")] +#[cfg(any(test, feature = "diagnostics"))] pub(crate) fn memory() -> [u64; 2] { [ (lock(&TEXTURES).blocks() + lock(&SMALL).blocks()) as u64 * (BLOCK >> 20), diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs index bf3b2d83a6..398b966d10 100644 --- a/crates/victory-gpu/src/residency.rs +++ b/crates/victory-gpu/src/residency.rs @@ -12,7 +12,17 @@ pub(crate) fn memory_status() -> Option { // SAFETY: the API initializes the fields of a correctly sized structure. let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; status.dwLength = std::mem::size_of::() as u32; - (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status) + // SAFETY: a sized structure. + let ok = unsafe { GlobalMemoryStatusEx(&mut status) } != 0; + // The free RAM the memory bench tells (`crate::host::FREE_RAM_SAID`). + #[cfg(test)] + if let Some(said) = crate::host::FREE_RAM_SAID + .load(Ordering::Relaxed) + .checked_sub(1) + { + status.ullAvailPhys = said; + } + ok.then_some(status) } /// What is left to commit, as the layer's decisions count it: what is left diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 3424581e1a..94ebfcc851 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -407,11 +407,24 @@ pub(crate) fn has_twin(this: This) -> bool { if this.is_null() { return false; } + if !lazy_twins() { + // Made at the first question, so no sync into the twin is skipped + // (a twin made later started from stale content: block artifacts). + return ensure_twin(this).is_some(); + } let r = resource(this); let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); made.as_ref().is_some_and(|(_, twin)| twin.is_some()) } +/// `VICTORY_LAZY_TWINS=1`: a depth texture's colour twin is made only when a +/// view first needs it, and syncs into it are skipped until then. +#[cfg(windows)] +fn lazy_twins() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TWINS").is_some_and(|v| v == "1")) +} + /// Ensures title texture `this`'s depth-UAV colour twin is allocated if eligible. #[cfg(windows)] fn ensure_twin(this: This) -> Option> { diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index d27a92cf83..82255e49f6 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -47,8 +47,9 @@ pub(crate) fn counts() -> (u64, u64) { /// `VICTORY_HDR_CLAMP=0`, `VICTORY_SAMPLED_MARKS=1` or `VICTORY_DEFRAG=0` still /// were. The other switches the translator reads are in the key another way or /// change no translation: the tests check each of them. -const KEYED: [&str; 45] = [ +const KEYED: [&str; 46] = [ "VICTORY_WAVE_WIDE", + "VICTORY_SCALAR_SPLITS", "VICTORY_WATER_VOLUME_PORTALS", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_OWN_BITS", @@ -961,6 +962,12 @@ mod tests { "VICTORY_SHADER_SOURCE_HASH", "VICTORY_SHADER_SWITCHES", "VICTORY_REQUIRE_HW_GPU", + // The differential fuzzer's (oracle_tests.rs): how many programs, from + // which seed, which shapes it leaves out, where it writes its cases. + "VICTORY_ORACLE_RUNS", + "VICTORY_ORACLE_SEED", + "VICTORY_ORACLE_AVOID", + "VICTORY_ORACLE_OUT", ]; let read: Vec<&str> = victory_shader::emit::SWITCHES.split(',').filter(|s| !s.is_empty()).collect(); assert!(read.contains(&"VICTORY_WAVE_WIDE"), "the translator's switches are listed: {read:?}"); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0c572f4ee7..2075d3fd08 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -4834,7 +4834,7 @@ fn trim(windows: impl Iterator) -> [u64; 3] { /// For the memory line: the windows let go since the start and their /// bytes, and of the bytes of the windows alive, how many lie between the /// lowest and the highest address ever asked for in each. -#[cfg(feature = "diagnostics")] +#[cfg(any(test, feature = "diagnostics"))] pub(crate) fn windows() -> [u64; 3] { let asked: u64 = { let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); @@ -4949,7 +4949,7 @@ pub(crate) fn live_copies() -> [u64; 2] { /// For the memory line: host copies alive and their bytes, of them the /// windows of memory outside buffers and their bytes, and the snapshot /// buffers kept for reuse and the bytes they reserve. -#[cfg(feature = "diagnostics")] +#[cfg(any(test, feature = "diagnostics"))] pub(crate) fn memory() -> [u64; 6] { #[cfg(feature = "diagnostics")] if census_due() { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 00b3c3ad7a..d92307fc36 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -719,7 +719,7 @@ impl Drop for Staging { /// For the memory line: staging buffers alive, their bytes, and how many /// of them their texture still has (the others wait for a list's reset). -#[cfg(feature = "diagnostics")] +#[cfg(any(test, feature = "diagnostics"))] pub(crate) fn memory() -> [u64; 3] { use std::sync::atomic::Ordering::Relaxed; let kept = STAGING @@ -734,7 +734,7 @@ pub(crate) fn memory() -> [u64; 3] { static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// For the memory line: staging buffers let go as idle, and their bytes. -#[cfg(feature = "diagnostics")] +#[cfg(any(test, feature = "diagnostics"))] pub(crate) fn let_go() -> [u64; 2] { use std::sync::atomic::Ordering::Relaxed; [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)] diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index edacc1e7c5..cf1df0d303 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -204,6 +204,135 @@ struct PadState { right_y: f32, } +/// The pads' readings written to a file, and played back from one, for test +/// runs nobody sits at: `VICTORY_INPUT_RECORD=` writes every change of +/// a pad's reading with the milliseconds since the first poll; +/// `VICTORY_INPUT_REPLAY=` gives the title those readings at those +/// times instead of the pads'. A line is `ms slot -` (no pad) or +/// `ms slot buttons lt rt lx ly rx ry`, all in hex (the floats' bits). In a +/// replayed file a line `wait` holds the readings until the file +/// `.go` exists; the times after it count from that moment. +mod padtape { + use super::{PADS, PadState}; + use std::io::Write; + use std::sync::{Mutex, OnceLock}; + use std::time::Instant; + + type Pads = [Option; PADS]; + + struct Record { + file: std::fs::File, + last: Option, + } + + struct Replay { + /// `None`: a `wait` line. + steps: Vec)>>, + at: usize, + now: Pads, + /// The milliseconds the times of the steps count from. + from: u64, + go: std::path::PathBuf, + asked: u64, + } + + fn start() -> Instant { + static START: OnceLock = OnceLock::new(); + *START.get_or_init(Instant::now) + } + + fn line(text: &str) -> Option<(u64, usize, Option)> { + let mut words = text.split_whitespace(); + let ms = u64::from_str_radix(words.next()?, 16).ok()?; + let slot = usize::from_str_radix(words.next()?, 16).ok().filter(|&s| s < PADS)?; + let rest: Vec = words.map_while(|w| u32::from_str_radix(w, 16).ok()).collect(); + let pad = (rest.len() == 7).then(|| PadState { + buttons: rest[0], + left_trigger: f32::from_bits(rest[1]), + right_trigger: f32::from_bits(rest[2]), + left_x: f32::from_bits(rest[3]), + left_y: f32::from_bits(rest[4]), + right_x: f32::from_bits(rest[5]), + right_y: f32::from_bits(rest[6]), + }); + Some((ms, slot, pad)) + } + + pub(super) fn apply(pads: &mut Pads) { + static REPLAY: OnceLock>> = OnceLock::new(); + static RECORD: OnceLock>> = OnceLock::new(); + let ms = start().elapsed().as_millis() as u64; + let replay = REPLAY.get_or_init(|| { + let path = std::env::var_os("VICTORY_INPUT_REPLAY").filter(|v| !v.is_empty())?; + let text = std::fs::read_to_string(&path).ok()?; + let steps: Vec<_> = text + .lines() + .filter_map(|l| if l.trim() == "wait" { Some(None) } else { line(l).map(Some) }) + .collect(); + println!("input replayed from a file: {} steps", steps.len()); + let mut go = path.clone(); + go.push(".go"); + Some(Mutex::new(Replay { steps, at: 0, now: [None; PADS], from: 0, go: go.into(), asked: 0 })) + }); + if let Some(replay) = replay { + let mut r = replay.lock().unwrap_or_else(|e| e.into_inner()); + while let Some(&step) = r.steps.get(r.at) { + match step { + None => { + // Asked four times a second at most. + if ms < r.asked + 250 { + break; + } + r.asked = ms; + if !r.go.exists() { + break; + } + r.from = ms; + } + Some((at, slot, pad)) => { + if at > ms - r.from { + break; + } + r.now[slot] = pad; + } + } + r.at += 1; + } + *pads = r.now; + return; + } + let record = RECORD.get_or_init(|| { + let path = std::env::var_os("VICTORY_INPUT_RECORD").filter(|v| !v.is_empty())?; + let file = std::fs::File::create(path).ok()?; + println!("input recorded to a file"); + Some(Mutex::new(Record { file, last: None })) + }); + if let Some(record) = record { + let mut r = record.lock().unwrap_or_else(|e| e.into_inner()); + for slot in 0..PADS { + if r.last.is_some_and(|last| last[slot] == pads[slot]) { + continue; + } + let _ = match pads[slot] { + None => writeln!(r.file, "{ms:x} {slot:x} -"), + Some(p) => writeln!( + r.file, + "{ms:x} {slot:x} {:x} {:x} {:x} {:x} {:x} {:x} {:x}", + p.buttons, + p.left_trigger.to_bits(), + p.right_trigger.to_bits(), + p.left_x.to_bits(), + p.left_y.to_bits(), + p.right_x.to_bits(), + p.right_y.to_bits(), + ), + }; + } + r.last = Some(*pads); + } + } +} + /// One key held down: scan code (0xE0xx when extended), character, key. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -753,7 +882,8 @@ impl Hub { fn poll(&self) { let (pads, keys, mouse, overlay) = { let mut source = lock(&self.source); - let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); + let mut pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); + padtape::apply(&mut pads); let keys = source.keys(); let mouse = source.mouse(); let overlay = source.overlay(&pads, &keys); diff --git a/crates/victory-shader/src/emit/lds.rs b/crates/victory-shader/src/emit/lds.rs index e146e1354f..e57b895a6b 100644 --- a/crates/victory-shader/src/emit/lds.rs +++ b/crates/victory-shader/src/emit/lds.rs @@ -175,6 +175,8 @@ thread_local! { /// Runs `f` (a translation) with the write-only shortcut on, as `VICTORY_LDS_WRITE_ONLY_OK=1` /// has it: what a wave64 compute program falls back to on a 32-lane host when the proof the /// analysis asks for is missing and the program would otherwise be dropped (issue #1435). +/// Gated by [`super::lower::last_resort_wanted`] (on for every refused program unless +/// `VICTORY_LDS_LAST_RESORT=0` / a hash list / `builder`). pub(super) fn with_last_resort(f: impl FnOnce() -> T) -> T { let before = LAST_RESORT.replace(true); let out = f(); diff --git a/crates/victory-shader/src/emit/lower/analysis.rs b/crates/victory-shader/src/emit/lower/analysis.rs index 482e3d6650..352a762c87 100644 --- a/crates/victory-shader/src/emit/lower/analysis.rs +++ b/crates/victory-shader/src/emit/lower/analysis.rs @@ -327,19 +327,52 @@ pub(in crate::emit) fn wide_fallback_skipped() -> bool { }) } -/// The programs given the LDS last resort (`lds::with_last_resort`) when the analysis refuses -/// them on a 32-lane host. By default only the ray-tracing structure builder's one refused -/// program: its 53 stages run all or none, so without it ray tracing stays off. Brought back -/// for every refused program (`VICTORY_LDS_LAST_RESORT=1`) they cost 3.6 fps and left garbage -/// in window reflections (play session 2026-11-28). A list of hashes picks others; `0`: none. -const LAST_RESORT_DEFAULT: [&str; 1] = ["e63d22c4def9ba6a"]; +/// Programs given the LDS last resort when a list is asked for explicitly +/// (`VICTORY_LDS_LAST_RESORT=builder` or a hash list). Includes the RT builder +/// (`e63d22c4…`), the #799/#833 Wave32 cohort, and the #1435 "no wave32 +/// lowering" set (8 of those 10 recover with write-only; `6871d6e4…` and +/// `6b82bc7d…` still refuse). +const LAST_RESORT_BUILDER: [&str; 17] = [ + "e63d22c4def9ba6a", + // #799 / #833 + "02384a60fda6f2d0", + "2cc4c197ee29e291", + "2da4beb386509b77", + "369cbe906ea72764", + "5dc3b259", + "6f225b64", + // #1435 Wave32 refusals (write-only recovers all but 6871d6e4 / 6b82bc7d) + "0e366d15868e17bd", + "1f1fbd86759b3da2", + "21f7ad7863620328", + "55679a0547649d0b", + "5964b734c70b91eb", + "6871d6e4b3ac9a10", + "6b82bc7d22016cb5", + "7c9a6a83826cdfac", + "89d08e561897d4e5", + "caf96a3229145fa6", +]; +/// Whether a wave64 program the LDS analysis refuses on a 32-lane host is tried +/// again with the write-only shortcut (`lds::with_last_resort`), the rule before +/// #43. Unset or `1`: every refused program (v2026.11.28.03-shaped coverage on +/// Wave32; without it RTX 3080 runs of v2026.11.29.01 dropped the picture with +/// "DRAWS SKIPPED, THEIR SHADERS CANNOT BE CONVERTED YET"). `0`: none. `builder`: +/// only [`LAST_RESORT_BUILDER`]. A comma/`+` list of hash prefixes picks those. +/// Trade-off when on for every program: a few fps and occasional reflection +/// garbage (play session 2026-11-28); better than a black screen on Wave32. pub(in crate::emit) fn last_resort_wanted() -> bool { // `None`: every refused program. static LIST: std::sync::OnceLock>> = std::sync::OnceLock::new(); let list = LIST.get_or_init(|| match std::env::var("VICTORY_LDS_LAST_RESORT") { - Err(_) => Some(LAST_RESORT_DEFAULT.iter().map(|h| (*h).to_owned()).collect()), - Ok(v) if v.trim() == "1" => None, + // Unset, empty, or `1`: every refused program (empty can appear after + // `victory play` applies a blank line from victory-settings.txt). + Err(_) => None, + Ok(v) if v.trim().is_empty() || v.trim() == "1" => None, + Ok(v) if v.trim().eq_ignore_ascii_case("builder") => { + Some(LAST_RESORT_BUILDER.iter().map(|h| (*h).to_owned()).collect()) + } Ok(v) => Some( v.split([',', '+']) .map(|h| h.trim().to_ascii_lowercase()) diff --git a/crates/victory-shader/src/fold.rs b/crates/victory-shader/src/fold.rs index 73ecf87081..47e76f1a65 100644 --- a/crates/victory-shader/src/fold.rs +++ b/crates/victory-shader/src/fold.rs @@ -53,11 +53,13 @@ const SCC: u8 = 253; const TEMP_VGPRS: u16 = 2; /// Whether console wave64 compute programs that a 32-lane host cannot run in -/// another exact form are folded: on unless `VICTORY_WAVE_FOLDED=0`. Part of -/// the translation: the shader cache keys on it. +/// another exact form are folded: only with `VICTORY_WAVE_FOLDED=1`. Off by +/// default: on many cards the folded programs cost so much card time that +/// play fell to a few frames a second, and foliage flickered. Part of the +/// translation: the shader cache keys on it. pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_FOLDED").is_none_or(|v| v != "0")) + *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_FOLDED").is_some_and(|v| v == "1")) } /// Which console half a copy of a vector instruction runs for. diff --git a/docs/shader-memory-validation.md b/docs/shader-memory-validation.md new file mode 100644 index 0000000000..b68e16df45 --- /dev/null +++ b/docs/shader-memory-validation.md @@ -0,0 +1,102 @@ +# Synthetic shader correctness and pressure reclamation + + +This work supplements existing upstream fixes with four shader corrections and pressure-only reclamation of idle host lists and oversized fetch buffers. The new shader/memory tests use original synthetic fixtures; no game, captured asset, shader dump, game offset or private runtime log was supplied. Existing repository test data and its licensing caveats are unchanged; these commits add or modify no binary/table blob. No real-game correctness or FPS claim is made. + +## Current merged-tree validation + +Upstream base: `64d4931b3dd90305134512b805fc98f04119fb6e`. Final tested source: `b2a3dabad7daf0e7ba3943a0ace2515e487c25dd`. Published as [PR #479](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/479). + +- Full default workspace: **1095 passed, 0 failed, 52 ignored**, including **300 shader tests**. Nested HLE child results are not counted twice. +- Both Clippy configurations passed after integration; the final helper extraction also passes all-targets/all-features Clippy. Asset policy: **294 files pass**. +- On `e4641ee`, both unfiltered oracle seeds retain **1199 matching semantic comparisons, 1 ambiguous equal-input SCC case unchecked, 0 differences/refusals**. Relay and synchronous strict pressure and two-burst complete 32 MiB readback tests pass. The subsequent `b2a3dab` extraction moves these branch helpers without changing their statements; only visibility and whitespace differ, verified by text comparison and the full default suite. +- Pressure counters retain the measured improvements: idle lists **68 -> 19** with relay and **64 -> 16** synchronously; fetch capacity **32 -> 16 MiB** in both modes. +- The final all-features workspace run was **cancelled at the owner's request to reduce cost**, not completed. Its forced-termination exit is not a semantic test failure, and partial passing results are not presented as a full pass. Further optional queued compatibility runs were also cancelled. Older all-feature/steady-state/control results below belong only to their explicitly pinned revisions. +- Compatibility with the newly merged optional `VICTORY_ALLOCATOR_TRIM=1` path has not been separately completed. Upstream's age-based trimming and allocator/prelude reuse are retained; the pressure path reuses its age calculation and updates its trim counter. + +Integration changes: `16fb1d7` resolves the three upstream conflicts while retaining both shader helper sets and allocator/prelude behavior; `e4641ee` reuses the upstream idle-age helper and fixes two new modulo Clippy findings; `b2a3dab` extracts branch-state helpers to meet the existing lowerer file-size limit (652482 bytes versus 655360). No policy limit was relaxed. The historical measurements below are not substituted for this merged-tree validation. + +## Revisions and attribution + +Upstream baseline: `df2daafeb1b2170931cf7a6eddff6de254841d9c`. +Combined production implementation: `1e050de66330baef94db9c972ea0b774f5eda2c1`. The subsequent test-only refinement is `6e2171f2d98847dd083ea1409822aead90528dec`; it refreshes simulated pressure and samples burst capacity before later frames can shrink it. + +This is a stacked contribution. These existing upstream submissions are prerequisites, with their original commits and authors retained, not newly authored fixes: + +| Prerequisite | Pinned head | Author | Purpose | +|---|---|---|---| +| #108 | `245cb85145bfd083e3df6769adf68dbdbb670340` | Caasares | Numeric wave64 mask halves | +| #112, including #111 | `4ad8b9b4dd133bf1b2cfe5cb9ef25754f8fff38e` | simbaui4life | Landed scratch release and memory benchmark | +| #116, including #70 | `d212aea94fe54c0bd2f616e3a7a30ae11b1cfc5f` | simbaui4life | Compare-mask correction and differential oracle | +| #71 | `6f4813ca7337abedf4cbb7f02457e653de1562cc` | simbaui4life | Scalar condition codes and lane-index wrapping | +| #73 | `6e16352fa263b634c9d5a9c88451999fdb27c01a` | simbaui4life | Scalar values across lane-divergent branches | +| #425 | `7331b07bde8d7beca973f24a0575ca1866d034d4` | Togicx | Existing workspace CI and budget-test repairs | + +The #73/#116 integration preserves both lowerer changes and both regression suites. #70/#71/#73/#111/#112/#116 were closed without merging when inspected; closure is not presented as approval or rejection. The branch can be rebased as prerequisites land. #425 supplies the CI repairs; this contribution does not introduce another CI implementation. + +New implementation commits: `beec109a68ae4cd876a4a57b797157259538ca8d`, `53867f60f77d2e45c6bec44d864ceda71bfd708d`, and `1e050de66330baef94db9c972ea0b774f5eda2c1`. AI-assisted by OpenAI Codex; reviewed and tested as described below. + +## Changes + +- A standalone first-lane read requests guest-wave layout/cross-half exchange when needed. Descriptor waterfall reads and groups of at most 32 threads retain their existing lowering; unnecessarily fixing the wave size broke WARP pipeline creation and is avoided. +- Enable scalar/compare branch-state preservation by default for one complete 64-thread guest wave. Explicit `VICTORY_WAVE_WIDE=0` remains an opt-out; larger groups retain the existing opt-in rules. +- Execute WRITELANE updates even when the destination lane is inactive in EXEC, including divergent regions. Preserve existing lane wrapping and empty-branch handling. +- Keep intermediate mask phis live through uniform loop joins. This fixes numeric mask values silently turning into zero without globally enabling strict joins. +- Under memory pressure, retire reset/GPU-complete idle host lists older than two seconds, retaining the newest 16 and all recently used lists. Release retired objects outside the pool lock. +- Shrink a peak fetch allocation only under pressure after two seconds below that capacity, between completed fetch/CPU-merge operations. Retain 16 MiB allocation granularity; zero demand can release the allocation. Failed shrinking retains the usable old buffer. `VICTORY_IDLE_RECLAIM=0` disables the new reclamation for matched diagnostics. + +The new byte-readback test forces every source piece to change in each of two bursts, requires fetch capacity to grow to at least 32 MiB each time, compares the complete 32 MiB result, then verifies that pressure reclaims lists and peak fetch capacity. It runs separately with and without relay. Reclamation depends on subsequent submissions/fetch calls; this is not a background idle-process collector. + +## Environment and reproduction + +Windows 11 build 26300, Rust 1.98.1 MSVC, RTX 5090 (32 GiB), driver 621.24, Ryzen 9 9950X3D, 192 GiB system RAM. Existing WARP cases also run. Exclusive GPU use, four Cargo/Rayon workers, serial tests, locked/offline dependencies, empty synthetic configuration and fresh per-process cache/data directories. Clear inherited `VICTORY_*` switches before each independent run. + +```text +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +cargo xtask policy +cargo test --workspace --locked -- --test-threads=1 +cargo test --workspace --all-features --locked -- --test-threads=1 +``` + +For the oracle, set `VICTORY_ORACLE_RUNS=200` and `VICTORY_ORACLE_SEED=1` or `2`, leave `VICTORY_ORACLE_AVOID` unset, then run: + +```text +cargo test -p victory-shader --lib --locked oracle_fuzz -- --ignored --nocapture --test-threads=1 +``` + +For each memory test use its own process; repeat with relay switches unset and with `VICTORY_RELAY=2`, `VICTORY_RELAY_COPY=1`: + +```text +cargo test -p victory-gpu --lib --locked memory_bench_pressure_lets_idle_go -- --ignored --nocapture --test-threads=1 +cargo test -p victory-gpu --lib --locked memory_bench_reclaims_and_regrows_with_correct_bytes -- --ignored --nocapture --test-threads=1 +cargo test -p victory-gpu --lib --locked memory_bench_steady_state -- --ignored --nocapture --test-threads=1 +``` + +Set `VICTORY_MEMBENCH_STRICT=1` for the pressure test. It simulates 1 GiB free RAM in the layer's test-only accounting; it does not exhaust physical RAM. Repeat with `VICTORY_IDLE_RECLAIM=0` for the negative control. Do not run these singleton/allocator benchmarks together in one process. + +## Historical results before upstream 64d4931 + +- Default workspace at `1e050de`: **1074 passed, 0 failed, 50 ignored**. Counts exclude the HLE test's nested child-process result, which would otherwise be counted twice. This includes **299 shader tests**, with 5 ignored. +- All-features workspace at `6e2171f`: **1127 passed, 0 failed, 51 ignored**, also excluding the nested HLE child result. Production source matches `1e050de`; the later commit changes only the isolated regrowth fixture. +- Both workspace/all-targets Clippy configurations with `-D warnings`: pass. The subsequent fixture-only refinement also passes all-targets/all-features GPU Clippy. Asset policy passes, including this report (290 files). +- Unfiltered oracle on `6e2171f`, 200 generated programs per wave size per seed: seed 1 has wave32 199 matches and 1 unexamined equal-input min/max SCC case; wave64 default and exact both 200 matches. Seed 2 has 200 matches in each of wave32, wave64 default, and wave64 exact. **1199 semantic comparisons match; 1 is not checked; no refusals or differences in these two runs.** +- Each new targeted fixture fails on its corresponding pre-fix control and passes after repair: standalone first-lane (16 cases), single-wave branch state (16), inactive WRITELANE destinations (80), and uniform-loop masks (6). Development unfiltered seed 1 exposed 16 failing assertions before the WRITELANE repair; seed 2 exposed 3 before the mask-phi repair. WARP size (8) and waterfall (22) regression subsets pass after narrowing first-lane wave sizing. +- Strict pressure tests pass on `6e2171f` in relay and synchronous modes. Steady-state memory tests also pass in each mode. +- Forced regrowth and complete byte comparisons pass on `6e2171f` in both modes: two bursts of 32 MiB each per process, four complete readbacks altogether. An earlier version of this test failed its synchronous capacity assertion after later frames; the fixture now refreshes the cached simulated pressure state between rounds and samples capacity immediately after the burst. Its data comparisons were not relaxed. + +Pressure census on `6e2171f` (single process per mode; after spike -> after 3.5 seconds of simulated pressure): + +| Mode | Idle host lists | Fetch allocation | +|---|---:|---:| +| Relay | 68 -> 19 | 32 -> 16 MiB | +| Synchronous | 64 -> 16 | 32 -> 16 MiB | + +Recent lists may remain above the 16-list warm reserve. A matched negative control on `6e2171f` with `VICTORY_IDLE_RECLAIM=0` fails the strict test and retains 68 lists and a 32 MiB relay fetch allocation. This does not claim that all process memory returns to the pre-spike baseline, or that all pressure savings are caused by this patch: existing window and scratch reclamation also runs. + +The five default-ignored shader entries are: an explicit bitcode benchmark, the directory-input probe tool, the fuzz oracle (run separately above), strict-join propagation, and legacy denormal-mode expectations. The last two remain limitations below, not claimed passes. Other default-ignored workspace tests not expressly listed as separately executed here were not run. +## Limits + +Finite synthetic fuzzing does not establish general shader correctness. Refused programs and ambiguous equal-input SCC cases are disclosed separately from matches. The pre-existing strict-join ignored test still fails with default settings and passes by rejecting an unsupported scalar-memory value with `VICTORY_STRICT_JOINS=1`; globally enabling rejection is not a semantic implementation. The legacy FP64-to-FP32 ignored test assumes flushed denormals, whereas the active test checks IEEE behavior; no target-mode evidence justified changing either expectation. Multi-wave synchronization and unsupported instructions retain upstream limitations. + +Memory reclamation does not return every process allocation to its warm baseline. Process private bytes are noisy and include allocator/driver retention. The bounded list/fetch counters are stronger evidence than a single process-memory difference. Exact wave semantics may require additional synchronization, so these results do not demonstrate an FPS gain. No allocation-failure injection or real-game workload was performed.