diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index c3ed06b782..b5db963088 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -26,7 +26,7 @@ tempfile.workspace = true [target.'cfg(windows)'.dependencies] # The main monitor's size, for the output size's default (`native_1440p::size`). -windows-sys = { workspace = true, features = ["Win32_UI_WindowsAndMessaging"] } +windows-sys = { workspace = true, features = ["Win32_UI_WindowsAndMessaging", "Win32_System_SystemInformation"] } [features] # Debug-level logs and the debugging switches (frame capture, stack dumps, diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index 2d6beacc3d..0d06e1d9c4 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -75,8 +75,10 @@ const SETTINGS: &[(&str, &str)] = &[ // (foxhound 0.2.0-pre.4, from its PR #13; its launcher sets 8 and 1) ("VICTORY_TEXSPK_PASS_MS", "8"), ("VICTORY_PASSES_HOT", "1"), - // The layer's threads a frame waits for, above normal priority (foxhound: cutscene worst second 74.8 -> 63.8 ms) - ("VICTORY_HELPER_PRIORITY", "1"), + // The layer's threads a frame waits for, above normal priority (foxhound: cutscene worst second 74.8 -> 63.8 ms). + // "on", not a number: a number is also given to the eight threads that translate lists (`cores::ask`), + // level with the submitting thread; "on" raises only the helpers (`cores::helpers_raised`). + ("VICTORY_HELPER_PRIORITY", "on"), // Shader writes into big write-combined copies stay on the card ("VICTORY_WC_NO_BACK", "1"), ("VICTORY_WC_NO_BACK_MIN_KB", "1024"), @@ -173,6 +175,12 @@ fn stale_switch(name: &str) -> bool { const FG_TYPES: [&str; 4] = ["auto", "dlss", "fsr", "fsr4"]; /// Not a switch: what `settings` turned off for want of DLSS, for `prepare` to say and take out. const NO_DLSS_NOTE: &str = "VICTORY_MENU_NO_DLSS_NOTE"; + +/// Own memory up to which a card plays without the texture pool (`VICTORY_TEXTURE_POOL=0`): on +/// 8 GB cards the pool's 64 MB blocks held 1 to 1.7 GB of holes and the card ran out of memory, +/// then the device was lost (#597, #196); a 12 GB card played 47 minutes with it (#604). +const POOL_MEMORY: u64 = 8 << 30; + /// The default mouse and keyboard bindings, written beside the settings on first use. const MNK_BINDINGS: &str = include_str!("../../../bindings.ini"); @@ -408,7 +416,13 @@ fn parse_menu(text: &str) -> Vec<(String, String)> { /// The settings of a start and whether it is the Series S profile: the /// options, what the menu saved over them (`menu`), `--set` over both. /// `streamline`: the folder with NVIDIA's files, if there is one. -fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> (BTreeMap, bool) { +/// `card_memory`: the playing card's own memory (`hardware_adapter`), None when not known. +fn settings( + o: &Play, + menu: &[(String, String)], + streamline: Option<&Path>, + card_memory: Option, +) -> (BTreeMap, bool) { let saved = |k: &str| menu.iter().rev().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); let series_s = saved("VICTORY_MENU_CONSOLE").map_or(o.series_s, |c| c == "series-s"); let res = saved("VICTORY_MENU_RES").filter(|r| RESOLUTIONS.contains(r)).unwrap_or(&o.res); @@ -444,6 +458,10 @@ fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> ( let mut s: BTreeMap = SETTINGS.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); let mut set = |k: &str, v: &str| drop(s.insert(k.to_owned(), v.to_owned())); + // Before the menu's and `--set`'s switches, which still win. + if card_memory.is_some_and(|m| m <= POOL_MEMORY) { + set("VICTORY_TEXTURE_POOL", "0"); + } if !series_s { match res { "1440" => set("VICTORY_NATIVE_1440P", "1"), @@ -543,6 +561,35 @@ fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> ( (s, series_s) } +/// Physical memory up to which the host copies of title memory are cut finer, as +/// `scripts/play-foxhound.ps1` does (5e6a8163): on a PC of 16 GB the game committed 17 to +/// 18 GB and paged up to 270,000 times a second (docs/test-results-2026-11-29.md, runs F, G). +const SMALL_RAM: u64 = 16_896 << 20; + +/// `VICTORY_WINDOW_KB=1024 VICTORY_WINDOW_TAILS=1` on a PC with [`SMALL_RAM`] or less, unless +/// the menu or `--set` named them. +fn small_ram_windows(s: &mut BTreeMap, ram: Option) { + if ram.is_some_and(|r| r <= SMALL_RAM) { + s.entry("VICTORY_WINDOW_KB".to_owned()).or_insert_with(|| "1024".to_owned()); + s.entry("VICTORY_WINDOW_TAILS".to_owned()).or_insert_with(|| "1".to_owned()); + } +} + +/// The PC's physical memory. +fn pc_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::() as u32; + // SAFETY: a sized structure. + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullTotalPhys) +} + +/// The own memory of the card the layer plays on. +fn card_memory() -> Option { + victory_shader::emit::host::hardware_adapter().map(|(_, _, own)| own) +} + /// `year-month-day-hour-minute-second` (UTC) of `seconds` since 1970. fn stamp(seconds: u64) -> String { let (days, rest) = (seconds / 86_400, seconds % 86_400); @@ -1205,14 +1252,15 @@ pub(crate) fn prepare(o: &Play) -> Result { let menu_file = home.join("victory-settings.txt"); let menu = parse_menu(&std::fs::read_to_string(&menu_file).unwrap_or_default()); let picked = menu.iter().rev().find(|(k, _)| k == "VICTORY_MENU_DLSS").map(|(_, v)| v.as_str()); - let (planned, _) = settings(o, &menu, Some(Path::new("."))); + let (planned, _) = settings(o, &menu, Some(Path::new(".")), None); let uses_pc_fsr = planned.get("VICTORY_PC_FSR").is_some_and(|v| v == "1"); if !uses_pc_fsr && planned.contains_key("VICTORY_DLSS") && streamline_dir(&here).is_none() { offer_dlss(picked.is_some_and(|d| DLSS_MODES.contains(&d))); } let streamline = streamline_dir(&here); - let (mut s, series_s) = settings(o, &menu, streamline.as_deref()); + let (mut s, series_s) = settings(o, &menu, streamline.as_deref(), card_memory()); let no_dlss_note = s.remove(NO_DLSS_NOTE).unwrap_or_default(); + small_ram_windows(&mut s, pc_ram()); // Mouse and keyboard (F1, MOUSE AND KEYBOARD; ItsMK1/VIctory-MnK-patches, GPL-3.0): the // bindings in `bindings.ini` here, written with the defaults the first time; a // VICTORY_MNK_BINDINGS already set (--set) names another file. @@ -1572,7 +1620,7 @@ mod tests { #[test] fn a_plain_start_is_the_launchers() { let dir = Path::new(r"C:\nvidia"); - let (s, series_s) = settings(&options(), &[], Some(dir)); + let (s, series_s) = settings(&options(), &[], Some(dir), None); assert!(!series_s); for (k, v) in SETTINGS { assert_eq!(s.get(*k).map(String::as_str), Some(*v), "{k}"); @@ -1587,7 +1635,7 @@ mod tests { // ready, off, with a little memory held back for it, when asked let mut o = options(); o.framegen_ready = true; - let (s, _) = settings(&o, &[], Some(dir)); + let (s, _) = settings(&o, &[], Some(dir), None); let get = |k: &str| s.get(k).map(String::as_str); assert_eq!((get("VICTORY_FRAMEGEN"), get("VICTORY_FRAMEGEN_X")), (Some("1"), Some("0"))); assert_eq!(get("VICTORY_TEXTURE_ROOM_PERCENT"), Some("86")); @@ -1599,7 +1647,7 @@ mod tests { #[test] fn without_nvidias_files_there_is_no_dlss() { - let (s, _) = settings(&options(), &[], None); + let (s, _) = settings(&options(), &[], None, None); let get = |k: &str| s.get(k).map(String::as_str); assert!(!s.contains_key("VICTORY_DLSS") && !s.contains_key("VICTORY_FRAMEGEN")); assert_eq!(get("VICTORY_MENU_DLSS"), Some("off")); @@ -1611,7 +1659,7 @@ mod tests { // game (#331, #459) let mut o = options(); o.framegen_ready = true; - let (s, _) = settings(&o, &[], None); + let (s, _) = settings(&o, &[], None, None); assert!(!s.contains_key("VICTORY_FSR_FRAMEGEN") && !s.contains_key("VICTORY_FRAMEGEN_X")); } @@ -1620,11 +1668,11 @@ mod tests { let mut o = options(); o.dlss = "off".into(); let menu = parse_menu("VICTORY_MENU_DLSS=quality\r\nVICTORY_MENU_DLSS=balanced\r\n"); - let (missing, _) = settings(&o, &menu, None); + let (missing, _) = settings(&o, &menu, None, None); assert_eq!(missing["VICTORY_MENU_DLSS"], "balanced"); assert!(!missing.contains_key("VICTORY_DLSS")); assert!(!missing.contains_key("VICTORY_DLSS_MODE")); - let (installed, _) = settings(&o, &menu, Some(Path::new("sdk"))); + let (installed, _) = settings(&o, &menu, Some(Path::new("sdk")), None); assert_eq!(installed["VICTORY_DLSS_MODE"], "balanced"); assert_eq!(installed["VICTORY_DLSS"], "1"); } @@ -1634,7 +1682,7 @@ mod tests { let mut options = options(); options.fg_type = "fsr4".to_owned(); options.framegen = Some(2); - let (settings, _) = settings(&options, &[], None); + let (settings, _) = settings(&options, &[], None, None); assert_eq!(settings["VICTORY_PC_FSR"], "1"); assert_eq!(settings["VICTORY_FSR_FRAMEGEN"], "4"); assert_eq!(settings["VICTORY_DLSS_MODE"], "quality"); @@ -1645,7 +1693,7 @@ mod tests { #[test] fn what_dlss_off_turns_off_is_said() { - let note = |o: &Play, menu: &str, dir: Option<&Path>| settings(o, &parse_menu(menu), dir).0.remove(NO_DLSS_NOTE); + let note = |o: &Play, menu: &str, dir: Option<&Path>| settings(o, &parse_menu(menu), dir, None).0.remove(NO_DLSS_NOTE); let mut o = options(); assert_eq!(note(&o, "", None), None); (o.series_s, o.framegen, o.dlss) = (true, Some(2), "performance".to_owned()); @@ -1662,14 +1710,14 @@ mod tests { let mut o = options(); o.framegen = Some(3); let menu = parse_menu("VICTORY_MENU_FG_TYPE=fsr\r\n"); - let (s, _) = settings(&o, &menu, Some(Path::new("x"))); + let (s, _) = settings(&o, &menu, Some(Path::new("x")), None); let get = |k: &str| s.get(k).map(String::as_str); assert_eq!((get("VICTORY_DLSS"), get("VICTORY_FRAMEGEN")), (Some("1"), None)); assert_eq!((get("VICTORY_FSR_FRAMEGEN"), get("VICTORY_FRAMEGEN_X")), (Some("1"), Some("3"))); assert_eq!((get("VICTORY_MENU_FG_TYPE"), get("VICTORY_MENU_FRAMEGEN")), (Some("fsr"), Some("3"))); // dlss: no FSR 3 o.fg_type = "dlss".to_owned(); - let (s, _) = settings(&o, &[], Some(Path::new("x"))); + let (s, _) = settings(&o, &[], Some(Path::new("x")), None); assert_eq!((s.get("VICTORY_FRAMEGEN").map(String::as_str), s.get("VICTORY_FSR_FRAMEGEN")), (Some("1"), None)); } @@ -1680,7 +1728,7 @@ mod tests { let mut o = options(); o.dlss = "dlaa".to_owned(); o.framegen = Some(3); - let (s, _) = settings(&o, &[], Some(Path::new("x"))); + let (s, _) = settings(&o, &[], Some(Path::new("x")), None); let get = |k: &str| s.get(k).map(String::as_str); assert_eq!(get("VICTORY_DLSS"), Some("1")); assert_eq!(get("VICTORY_DLSS_MODE"), Some("dlaa")); @@ -1697,7 +1745,7 @@ mod tests { VICTORY_MENU_DLSS=performance\r\nVICTORY_MENU_FPS=60\r\nVICTORY_BVH_BUILDER=\r\n\ VICTORY_AMBIENT=0.5\r\nVICTORY_EARLY_DEPTH=\r\nnot a setting=1\r\n", ); - let (s, series_s) = settings(&options(), &menu, Some(Path::new("x"))); + let (s, series_s) = settings(&options(), &menu, Some(Path::new("x")), None); let get = |k: &str| s.get(k).map(String::as_str); assert!(series_s); // the Series S profile has no picture size of its own @@ -1716,46 +1764,46 @@ mod tests { let get = |s: &BTreeMap, k: &str| s.get(k).cloned(); let s_menu = |more: &str| parse_menu(&format!("VICTORY_MENU_CONSOLE=series-s\r\n{more}")); // not saved yet: the DLSS mode's size, and the mode as it was - let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=balanced\r\n"), Some(Path::new("x"))); + let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=balanced\r\n"), Some(Path::new("x")), None); assert_eq!(get(&s, "VICTORY_MENU_S_RES").as_deref(), Some("626")); assert_eq!(get(&s, "VICTORY_DLSS_MODE").as_deref(), Some("balanced")); // 540 with DLSS: its performance mode, whatever the DLSS line held - let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=quality\r\nVICTORY_MENU_S_RES=540\r\n"), Some(Path::new("x"))); + let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=quality\r\nVICTORY_MENU_S_RES=540\r\n"), Some(Path::new("x")), None); assert_eq!(get(&s, "VICTORY_DLSS_MODE").as_deref(), Some("performance")); assert_eq!(get(&s, "VICTORY_MENU_DLSS").as_deref(), Some("performance")); assert_eq!(get(&s, "VICTORY_FSR_PATH"), None); // 360 with DLSS: ultra performance let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=quality VICTORY_MENU_S_RES=360 -"), Some(Path::new("x"))); +"), Some(Path::new("x")), None); assert_eq!(get(&s, "VICTORY_DLSS_MODE").as_deref(), Some("ultraperformance")); assert_eq!(get(&s, "VICTORY_MENU_S_RES").as_deref(), Some("360")); // no DLAA on Series S (its game stops at that scene size): 720 at quality, from the // DLSS line, a 1080 saved before, or --dlss dlaa for more in ["VICTORY_MENU_DLSS=dlaa\r\n", "VICTORY_MENU_DLSS=dlaa\r\nVICTORY_MENU_S_RES=1080\r\n"] { - let (s, _) = settings(&options(), &s_menu(more), Some(Path::new("x"))); + let (s, _) = settings(&options(), &s_menu(more), Some(Path::new("x")), None); assert_eq!(get(&s, "VICTORY_DLSS_MODE").as_deref(), Some("quality"), "{more}"); assert_eq!((get(&s, "VICTORY_MENU_S_RES").as_deref(), get(&s, "VICTORY_MENU_DLSS").as_deref()), (Some("720"), Some("quality"))); } let mut o = options(); (o.series_s, o.dlss) = (true, "dlaa".to_owned()); - let (s, series_s) = settings(&o, &[], Some(Path::new("x"))); + let (s, series_s) = settings(&o, &[], Some(Path::new("x")), None); assert!(series_s); assert_eq!(get(&s, "VICTORY_DLSS_MODE").as_deref(), Some("quality")); // Series X keeps it - let (s, _) = settings(&options(), &parse_menu("VICTORY_MENU_DLSS=dlaa\r\n"), Some(Path::new("x"))); + let (s, _) = settings(&options(), &parse_menu("VICTORY_MENU_DLSS=dlaa\r\n"), Some(Path::new("x")), None); assert_eq!(get(&s, "VICTORY_DLSS_MODE").as_deref(), Some("dlaa")); // without DLSS (off, or no NVIDIA files): the game's 720, never the title's FidelityFX path for (more, dir) in [("VICTORY_MENU_DLSS=off\r\nVICTORY_MENU_S_RES=540\r\n", Some(Path::new("x"))), ("VICTORY_MENU_S_RES=540\r\n", None)] { - let (s, _) = settings(&options(), &s_menu(more), dir); + let (s, _) = settings(&options(), &s_menu(more), dir, None); assert_eq!((get(&s, "VICTORY_DLSS"), get(&s, "VICTORY_FSR_PATH"), get(&s, "VICTORY_DLSS_MODE")), (None, None, None)); assert_eq!(get(&s, "VICTORY_MENU_S_RES").as_deref(), Some("720")); } // 720 without DLSS: the game as it is - let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=off\r\nVICTORY_MENU_S_RES=720\r\n"), None); + let (s, _) = settings(&options(), &s_menu("VICTORY_MENU_DLSS=off\r\nVICTORY_MENU_S_RES=720\r\n"), None, None); assert_eq!((get(&s, "VICTORY_FSR_PATH"), get(&s, "VICTORY_DLSS_MODE")), (None, None)); // Series X: the Series S size changes nothing - let (s, series_s) = settings(&options(), &parse_menu("VICTORY_MENU_S_RES=540\r\n"), Some(Path::new("x"))); + let (s, series_s) = settings(&options(), &parse_menu("VICTORY_MENU_S_RES=540\r\n"), Some(Path::new("x")), None); assert!(!series_s); assert_eq!((get(&s, "VICTORY_DLSS_MODE").as_deref(), get(&s, "VICTORY_FSR_PATH")), (Some("quality"), None)); } @@ -1764,25 +1812,64 @@ VICTORY_MENU_S_RES=360 fn options_and_set_are_applied() { let mut o = options(); (o.res, o.dlss, o.framegen, o.fps) = ("1080to1440".to_owned(), "off".to_owned(), Some(4), 30); - o.more = vec!["VICTORY_AMBIENT=0".to_owned(), "VICTORY_NEW = 2".to_owned()]; - let (s, _) = settings(&o, &[], Some(Path::new("x"))); + o.more = vec!["VICTORY_AMBIENT=0".to_owned(), "VICTORY_NEW = 2".to_owned(), "VICTORY_HELPER_PRIORITY=1".to_owned()]; + let (s, _) = settings(&o, &[], Some(Path::new("x")), None); let get = |k: &str| s.get(k).map(String::as_str); assert_eq!((get("VICTORY_RENDER_1080P"), get("VICTORY_NATIVE_1440P")), (Some("1"), None)); // no DLSS, so no frame generation either assert_eq!((get("VICTORY_DLSS"), get("VICTORY_FRAMEGEN")), (None, None)); assert_eq!(get("VICTORY_FRAME_INTERVAL_US"), Some("33333")); assert_eq!((get("VICTORY_AMBIENT"), get("VICTORY_NEW")), (Some("0"), Some("2"))); + // a value of the user's wins over the launcher's "on" + assert_eq!(get("VICTORY_HELPER_PRIORITY"), Some("1")); } #[test] fn an_explicit_texture_room_limit_is_not_marked_as_a_frame_generation_reserve() { let mut o = options(); o.more = vec!["VICTORY_TEXTURE_ROOM_PERCENT=92".to_owned()]; - let (s, _) = settings(&o, &[], Some(Path::new(r"C:\nvidia"))); + let (s, _) = settings(&o, &[], Some(Path::new(r"C:\nvidia")), None); assert_eq!(s.get("VICTORY_TEXTURE_ROOM_PERCENT").map(String::as_str), Some("92")); assert!(!s.contains_key("VICTORY_FRAMEGEN_ROOM_RESERVE")); } + #[test] + fn pcs_of_16_gb_or_less_cut_host_copies_finer() { + let windows = |ram: Option, mine: Option<&str>| { + let mut s = BTreeMap::new(); + if let Some(v) = mine { + s.insert("VICTORY_WINDOW_KB".to_owned(), v.to_owned()); + } + small_ram_windows(&mut s, ram); + (s.get("VICTORY_WINDOW_KB").cloned(), s.get("VICTORY_WINDOW_TAILS").cloned()) + }; + // 16 GB says 15.1 to 16 GiB; 32 GB or unknown: as before + assert_eq!(windows(Some(15_507 << 20), None), (Some("1024".to_owned()), Some("1".to_owned()))); + assert_eq!(windows(Some(32 << 30), None), (None, None)); + assert_eq!(windows(None, None), (None, None)); + // the menu's or --set's value wins + assert_eq!(windows(Some(15_507 << 20), Some("4096")).0.as_deref(), Some("4096")); + } + + #[test] + fn cards_of_8_gb_or_less_play_without_the_texture_pool() { + let pool = |memory: Option, more: &[&str]| { + let mut o = options(); + o.more = more.iter().map(|m| (*m).to_owned()).collect(); + settings(&o, &[], None, memory).0.get("VICTORY_TEXTURE_POOL").cloned() + }; + // an RTX 5060 8 GB says 7895 MB; unknown or 12 GB: the pool, as before + assert_eq!(pool(Some(7895 << 20), &[]).as_deref(), Some("0")); + assert_eq!(pool(Some(8 << 30), &[]).as_deref(), Some("0")); + assert_eq!(pool(Some(12 << 30), &[]).as_deref(), Some("1")); + assert_eq!(pool(None, &[]).as_deref(), Some("1")); + // asked for, it is on: `--set`, or what the menu saved + assert_eq!(pool(Some(7895 << 20), &["VICTORY_TEXTURE_POOL=1"]).as_deref(), Some("1")); + let menu = parse_menu("VICTORY_TEXTURE_POOL=1 +"); + assert_eq!(settings(&options(), &menu, None, Some(4 << 30)).0["VICTORY_TEXTURE_POOL"], "1"); + } + /// AMD's files are offered only to cards without DLSS Frame Generation (or FSR 3 chosen). #[test] fn cards_with_dlss_frame_generation() { @@ -1857,7 +1944,7 @@ VICTORY_MENU_S_RES=360 fn mfg_unlocker_is_loaded_only_with_dlss_frame_generation() { let dir = Path::new(r"C:\nvidia"); let on = parse_menu("VICTORY_MFG_UNLOCKER=1\r\n"); - let loaded = |o: &Play, menu: &[(String, String)]| mfg_loaded(&settings(o, menu, Some(dir)).0); + let loaded = |o: &Play, menu: &[(String, String)]| mfg_loaded(&settings(o, menu, Some(dir), None).0); let mut o = options(); // frame generation off and not made ready, the default assert!(!loaded(&o, &on)); @@ -1872,7 +1959,7 @@ VICTORY_MENU_S_RES=360 o.framegen_ready = true; assert!(loaded(&o, &on)); // without NVIDIA's files there is no DLSS, nor its frame generation - assert!(!mfg_loaded(&settings(&o, &on, None).0)); + assert!(!mfg_loaded(&settings(&o, &on, None, None).0)); } /// Settings read again after `prepare` clears the others survive it. diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index d99a8e7ba2..029b80da67 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -157,7 +157,7 @@ fn set() -> Set { /// pipelines). pub(crate) fn on(role: Role) -> bool { let set = set(); - if set == Set::Off && specular().is_none() { + if set == Set::Off && specular().is_none() && raymiss_sky().is_none() { return false; } let builder = crate::pipeline::builder_runs(); @@ -271,6 +271,20 @@ fn specular() -> Option { *SET.get_or_init(|| parse_specular(&std::env::var("VICTORY_AMBIENT_SPECULAR").unwrap_or_default())) } +/// Whether the reflection estimate can use this layer's depth. The alpha +/// layer uses the opaque depth behind glass and can be opted out of. +pub(crate) fn specular_layer(layer: u32) -> bool { + static ALPHA: OnceLock = OnceLock::new(); + layer == MISS_OPAQUE || (layer == MISS_ALPHA && *ALPHA.get_or_init(|| { + !std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "0") + })) +} + +/// The estimate runs after the miss dispatch and needs its output. +pub(crate) fn keep_miss_for_specular(layer: u32) -> bool { + specular().is_some() && specular_layer(layer) && on(Role::Miss) +} + /// `VICTORY_AMBIENT_ONCE=1`: the estimate is one bounce of the light the /// title's own lighting put there, not of the stand-in's too. /// @@ -856,7 +870,12 @@ struct NeutralPass { } fn make_neutral(device: &ID3D12Device) -> windows::core::Result { - let code = crate::host::compile(NEUTRAL_SOURCE, s!("neutral"), s!("cs_5_1"))?; + make_pass(device, NEUTRAL_SOURCE, s!("neutral")) +} + +/// A one-pipeline pass of `source`, whose root signature is in it. +fn make_pass(device: &ID3D12Device, source: &str, entry: windows::core::PCSTR) -> windows::core::Result { + let code = crate::host::compile(source, entry, s!("cs_5_1"))?; // SAFETY: the shader contains its root signature; the code lives through creation. unsafe { let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?; @@ -902,6 +921,87 @@ pub(crate) fn neutral_after(list: &HostList, role: Role, desc: &D3D12_RESOURCE_D true } +/// `VICTORY_RAYMISS_SKY=` (0 to 1; unset: off): the reflections' miss +/// program runs for opaque and transparent surfaces (as with +/// `VICTORY_RAYMISS_KEEP=1`), and the sky's light it gives is scaled by +/// `share` right after it; 0 leaves those rays black. +/// +/// Why: left out (the default), the miss program's image is not written for +/// those rays, and what the screen-space passes do not resolve keeps bytes +/// that are not this frame's reflections (multicoloured patches on glass +/// and car bodies with ray tracing off, RTX 5060 session 2026-11-29). Run, +/// it writes the image of every variant at its own place, but its sky gives +/// grazing floors a white grain (`draw::sky_miss_left_out`). Scaled, the image +/// is this frame's and the grain is as dim as asked. Cheap: one pass over an +/// image of half the picture's size, nothing read but that image. +pub(crate) fn raymiss_sky() -> Option { + static SHARE: OnceLock> = OnceLock::new(); + *SHARE.get_or_init(|| parse_sky(&std::env::var("VICTORY_RAYMISS_SKY").unwrap_or_default())) +} + +fn parse_sky(value: &str) -> Option { + value.trim().parse::().ok().filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0)) +} + +/// The miss program's image: a 2D R11G11B10 texture. +fn sky_image(desc: &D3D12_RESOURCE_DESC) -> bool { + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && desc.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R11G11B10_FLOAT + && desc.SampleDesc.Count == 1 + && desc.DepthOrArraySize == 1 + && desc.Width > 0 + && desc.Width <= u64::from(u32::MAX) + && desc.Height > 0 +} + +const SKY_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), DescriptorTable(UAV(u0))" +cbuffer Params : register(b0) { float share; uint width; uint height; }; +RWTexture2D reflected : register(u0); +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void scale_sky(uint3 at : SV_DispatchThreadID) { + if (at.x >= width || at.y >= height) return; + float3 c = reflected[at.xy]; + c = any(isnan(c)) || any(isinf(c)) ? 0.0 : max(c, 0.0); + reflected[at.xy] = c * share; +} +"#; + +/// After a dispatch of the miss program for opaque or transparent surfaces +/// (`layer`), whose image is `desc` at `image` ([`raymiss_sky`]). Replaces the +/// list's compute root signature and pipeline; false if it recorded nothing. +pub(crate) fn sky_after(list: &HostList, layer: u32, desc: &D3D12_RESOURCE_DESC, image: D3D12_GPU_DESCRIPTOR_HANDLE) -> bool { + let Some(share) = raymiss_sky() else { return false }; + if !matches!(layer, MISS_OPAQUE | MISS_ALPHA) || !sky_image(desc) || crate::pipeline::builder_runs() { + return false; + } + static PASS: OnceLock> = OnceLock::new(); + let Some(pass) = PASS.get_or_init(|| { + make_pass(&host()?.device, SKY_SOURCE, s!("scale_sky")) + .inspect_err(|error| tracing::warn!(%error, "no scaling of the reflections' sky (VICTORY_RAYMISS_SKY)")) + .ok() + }) else { + return false; + }; + let words = [share.to_bits(), desc.Width as u32, desc.Height]; + let l = &list.list; + // SAFETY: the title's program just wrote this UAV; its heap is still set + // and the dispatch holds the texture. No other view is bound. + unsafe { + uav_barrier(l); + l.SetComputeRootSignature(&pass.root); + l.SetComputeRoot32BitConstants(0, 3, words.as_ptr().cast(), 0); + l.SetComputeRootDescriptorTable(1, image); + l.SetPipelineState(&pass.pipeline); + l.Dispatch((desc.Width as u32).div_ceil(8), desc.Height.div_ceil(8), 1); + uav_barrier(l); + } + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| tracing::info!(share, "the reflections' sky scaled after the miss program (VICTORY_RAYMISS_SKY)")); + true +} + /// Whether the light of a frame has been kept: the estimate has something /// to begin with. static KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -1256,6 +1356,40 @@ mod tests { } } + /// `VICTORY_RAYMISS_SKY`: a share from 0 (black) to 1, anything else + /// off; only the miss program's 2D R11G11B10 image; the pass compiles. + #[test] + fn the_reflections_sky_share_and_image() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_SAMPLE_DESC}; + for value in ["", "off", "nan", "inf"] { + assert_eq!(parse_sky(value), None, "{value}"); + } + assert_eq!(parse_sky("0"), Some(0.0)); + assert_eq!(parse_sky(" 0.25 "), Some(0.25)); + assert_eq!(parse_sky("3"), Some(1.0)); + assert_eq!(parse_sky("-1"), Some(0.0)); + let image = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Format: DXGI_FORMAT_R11G11B10_FLOAT, + Width: 960, + Height: 540, + DepthOrArraySize: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(sky_image(&image)); + for bad in [ + D3D12_RESOURCE_DESC { Format: DXGI_FORMAT_R32_UINT, ..image }, + D3D12_RESOURCE_DESC { DepthOrArraySize: 2, ..image }, + D3D12_RESOURCE_DESC { Height: 0, ..image }, + D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, ..image }, + ] { + assert!(!sky_image(&bad)); + } + let gpu = crate::indirect::tests::WarpHarness::new().expect("a D3D12 WARP adapter"); + make_pass(&gpu.device, SKY_SOURCE, s!("scale_sky")).unwrap(); + } + #[test] fn neutral_probe_replaces_colour_without_depth_and_preserves_bounds() { use crate::indirect::tests::WarpHarness; diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index e931b00d4d..eaa3b133db 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1979,13 +1979,17 @@ pub(crate) fn make_waiting() { /// the marks. With `VICTORY_SAMPLED_EVICT=1` it does, for those whose /// other slots are all a draw's to make again: their slots picked by index /// come with the others, flagged (the third field), and are queued again -/// once a shader reads them (`crate::sampled::evicted`). +/// once a shader reads them (`crate::sampled::evicted`). With `cold_since` +/// (`VICTORY_COLD_EVICT_S`, `crate::resource::cold_evict_ms`) the marks are +/// trusted so too, but a texture is cold only if no shader marked it since +/// frame `cold` (further back than `cutoff`). #[cfg(windows)] #[allow(clippy::type_complexity)] pub(crate) fn evictable_slots( raws: &std::collections::HashMap, frame: u64, cutoff: u64, + cold_since: Option, ) -> (std::collections::HashMap>, u64, u64, Vec) { let set: std::collections::HashSet = raws.keys().copied().collect(); let mut by_texture: std::collections::HashMap> = std::collections::HashMap::new(); @@ -2006,7 +2010,7 @@ pub(crate) fn evictable_slots( if lately { seen.insert(raw); } - if crate::sampled::sampled_since(index, cutoff).unwrap_or(true) { + if crate::sampled::sampled_since(index, cold_since.unwrap_or(cutoff)).unwrap_or(true) { sampled.insert(raw); } if ok || indexed { @@ -2027,7 +2031,7 @@ pub(crate) fn evictable_slots( .filter(|raw| !sampled.contains(raw) && !seen.contains(raw)) .filter_map(|raw| raws.get(raw).copied()) .collect(); - let trusted = crate::sampled::evict_on(); + let trusted = crate::sampled::evict_on() || cold_since.is_some(); by_texture.retain(|raw, _| { !seen.contains(raw) && (!blocked.contains(raw) || trusted && !other.contains(raw) && !sampled.contains(raw)) }); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 784d0390b9..9d8ea0a1f2 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1919,6 +1919,20 @@ struct Due { const _: () = assert!(std::mem::size_of::<(u32, u64, u32)>() == 16); const _: () = assert!(std::mem::size_of::<(u32, u64)>() == 16); +/// Give recent shader use priority when a regular texture pass hits its +/// residency limit. Background rechecks can otherwise consume the pass +/// before it reaches visible textures. The override keeps comparisons +/// possible (`VICTORY_DUE_HOT_FIRST=0` or `=1`). +fn due_hot_first(under_pressure: bool) -> bool { + static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let asked = *ASKED.get_or_init(|| match std::env::var_os("VICTORY_DUE_HOT_FIRST").as_deref() { + Some(value) if value == "0" => Some(false), + Some(value) if value == "1" => Some(true), + _ => None, + }); + asked.unwrap_or(under_pressure) +} + impl Due { fn with_capacity(again: usize, fresh: usize, checked: usize) -> Self { Due { @@ -1931,45 +1945,83 @@ impl Due { /// Up to `max` of them, in the order [`TextureQueue::due`] serves them. #[cfg(test)] fn order(self, max: usize) -> Vec<(u32, u64)> { - self.ordered(max).0 + self.ordered(max, false).0 } /// [`Due::order`], and beside it what [`TextureQueue::checked`] said of /// each when they were taken. - fn ordered(self, max: usize) -> (Vec<(u32, u64)>, Vec>) { + fn ordered(self, max: usize, under_pressure: bool) -> (Vec<(u32, u64)>, Vec>) { + self.ordered_by(max, due_hot_first(under_pressure), |index| { + crate::sampled::sampled_lately(index, 60) == Some(true) + }) + } + + /// [`Due::ordered`], with which slots a shader sampled lately (`hot`) + /// and whether they go before those looked at before (`hot_first`). + fn ordered_by(self, max: usize, hot_first: bool, hot: impl Fn(u32) -> bool) -> (Vec<(u32, u64)>, Vec>) { if max == 0 { return (Vec::new(), Vec::new()); } let Due { mut again, mut fresh, checked } = self; - // By the number of the write, counted over the run. - if again.len() > max { - again.select_nth_unstable_by_key(max, |e| std::cmp::Reverse(e.1)); - again.truncate(max); - } - again.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + let take_hot = |fresh: &mut Vec<(u32, u64)>| { + let mut out = Vec::new(); + fresh.retain(|&(index, write)| { + if hot(index) { + out.push((index, write)); + false + } else { + true + } + }); + out.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + out + }; let cap = (again.len() + fresh.len()).min(max); let mut order: Vec<(u32, u64)> = Vec::with_capacity(cap); let mut known: Vec> = Vec::with_capacity(cap); + if hot_first { + let mut visible = Vec::new(); + again.retain(|&item| { + if !hot(item.0) { + return true; + } + visible.push(item); + false + }); + fresh.retain(|&(index, write)| { + if !hot(index) { + return true; + } + visible.push((index, write, NO_CHECKED)); + false + }); + if visible.len() > max { + visible.select_nth_unstable_by_key(max, |e| std::cmp::Reverse(e.1)); + visible.truncate(max); + } + visible.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); + for (index, write, checked_pos) in visible { + order.push((index, write)); + known.push((checked_pos != NO_CHECKED).then(|| checked[checked_pos as usize])); + } + } + // By the number of the write, counted over the run. + let room = max - order.len(); + if again.len() > room { + again.select_nth_unstable_by_key(room, |e| std::cmp::Reverse(e.1)); + again.truncate(room); + } + again.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); for &(index, write, checked_pos) in &again { order.push((index, write)); known.push((checked_pos != NO_CHECKED).then(|| checked[checked_pos as usize])); } let need = max - order.len(); if need > 0 && !fresh.is_empty() { - let mut hot = Vec::new(); - fresh.retain(|&(index, write)| { - if crate::sampled::sampled_lately(index, 60) == Some(true) { - hot.push((index, write)); - false - } else { - true - } - }); - if !hot.is_empty() { - hot.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); - for item in hot.into_iter().take(max - order.len()) { - order.push(item); - } + // In hot-first mode all fresh entries were classified before + // the rechecks. A second scan would only revisit cold entries. + if !hot_first { + order.extend(take_hot(&mut fresh).into_iter().take(need)); } let need = max - order.len(); if need > 0 && !fresh.is_empty() { @@ -2103,6 +2155,31 @@ impl TextureQueue { back } + /// The card still has no room at `frame`, but of the slots held back for + /// lack of it those a shader sampled lately (`hot`) are due now: the + /// pass's first-upload allowance takes a slot on screen past the line, + /// and a held one waited out its hold (some 4 s) or the card's room, + /// which on an RTX 5060 8 GB did not come back for minutes (run of + /// 2026-11-29 15:20, up to 21,251 slots due, textures missing on + /// screen). Returns how many. + fn hot_back(&mut self, frame: u64, hot: impl Fn(u32) -> bool) -> usize { + if self.held.is_empty() { + return 0; + } + let back: Vec<(u32, u64)> = self.held.iter().filter(|&(&index, _)| hot(index)).map(|(&i, &w)| (i, w)).collect(); + let mut n = 0; + for (index, write) in back { + self.held.remove(&index); + if self.update_same(index, write, |e| e.due = e.due.min(frame)) { + n += 1; + } + } + if self.held.is_empty() { + self.marks.set_held(false); + } + n + } + /// Slot `index` was uploaded with `mapped` bytes of its memory there, /// not all of it: looked at again from frame `due`. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { @@ -3325,7 +3402,7 @@ impl HostHeap { /// ([`TextureQueue::census`]). #[cfg(test)] pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 6]) { - let (order, _, census) = self.texture_slots_due_known(frame, max); + let (order, _, census) = self.texture_slots_due_known(frame, max, false); (order, census) } @@ -3335,7 +3412,12 @@ impl HostHeap { /// [`TextureQueue::checked`] said of it then, read in the same take of /// the lock (the pass asked it slot by slot, under the lock each time); /// and the queue's counts ([`TextureQueue::census`]). - pub(crate) fn texture_slots_due_known(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, Vec>, [u64; 6]) { + pub(crate) fn texture_slots_due_known( + &self, + frame: u64, + max: usize, + under_pressure: bool, + ) -> (Vec<(u32, u64)>, Vec>, [u64; 6]) { if max == 0 { let census = self.queue(super::queue_site::DUE).census(frame); return (Vec::new(), Vec::new(), census); @@ -3350,7 +3432,7 @@ impl HostHeap { self.due_hints[0].store(next_hint(due.again.len()), Ordering::Relaxed); self.due_hints[1].store(next_hint(due.fresh.len()), Ordering::Relaxed); self.due_hints[2].store(next_hint(due.checked.len()), Ordering::Relaxed); - let (order, known) = due.ordered(max); + let (order, known) = due.ordered(max, under_pressure); (order, known, census) } @@ -3498,6 +3580,16 @@ impl HostHeap { self.queue(super::queue_site::MADE_DUE).room(frame) } + /// See [`TextureQueue::hot_back`]; the slots a shader marked in the last + /// 60 frames (`crate::sampled`). + pub(crate) fn texture_slots_hot_back(&self, frame: u64) -> usize { + if queue_marks() && !self.marks.has_held() { + return 0; + } + self.queue(super::queue_site::MADE_DUE) + .hot_back(frame, |index| crate::sampled::sampled_lately(index, 60) == Some(true)) + } + /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { @@ -8305,6 +8397,30 @@ void main() { assert_eq!(q.room(6), 0); } + /// With no room yet, the held slots a shader samples come back at once; + /// the others stay held until their frame or the card's room. + #[test] + fn held_slots_on_screen_come_back_without_room() { + let mut q = TextureQueue::default(); + for i in 0..4u32 { + q.written(30 + i, 1, 0, false); + } + for (index, write) in q.due(1, 100) { + q.hold(index, write, 500); + } + assert!(q.due(2, 100).is_empty()); + // Slots 31 and 33 are on screen. + assert_eq!(q.hot_back(8, |i| i == 31 || i == 33), 2); + let now: Vec = q.due(8, 100).into_iter().map(|d| d.0).collect(); + assert_eq!(now.len(), 2); + assert!(now.contains(&31) && now.contains(&33)); + // Asked again: nothing more on screen is held. + assert_eq!(q.hot_back(16, |i| i == 31 || i == 33), 0); + // The others come back with the room, as before. + assert_eq!(q.room(20), 2); + assert_eq!(q.room(21), 0); + } + /// Textures smaller than the 4 KiB head, back to back: the colour tables /// far buildings take their walls' tint from are 256 bytes each (three of /// a run's log, where writing one made its neighbours null and the walls @@ -8838,14 +8954,14 @@ void main() { q.recheck(31, w31, 5, (0x2000, 4096), 9, 0, 2); let w32 = write(&q, 32); q.later(32, w32, 2, 4); - let (order, known) = q.due_and_census(u64::MAX).0.ordered(100); + let (order, known) = q.due_and_census(u64::MAX).0.ordered(100, false); assert_eq!(order, q.due(u64::MAX, 100)); assert_eq!(known.len(), order.len()); for (&(index, _), knew) in order.iter().zip(&known) { assert_eq!(*knew, q.checked(index)); } assert_eq!(known.iter().filter(|k| k.is_some()).count(), 1); - let (order, known) = q.due_and_census(u64::MAX).0.ordered(1); + let (order, known) = q.due_and_census(u64::MAX).0.ordered(1, false); assert_eq!((order.len(), known.len()), (1, 1)); } @@ -9000,7 +9116,7 @@ void main() { q.partly(10, w10, 9, 8192); assert_eq!(q.mapped(10), 8192); assert_eq!(q.checked(10), None); - let (due, known) = q.due_and_census(9).0.ordered(100); + let (due, known) = q.due_and_census(9).0.ordered(100, false); let pos = due.iter().position(|&(slot, _)| slot == 10).unwrap(); assert_eq!(known[pos], None); check_invariants(&q); @@ -9068,6 +9184,53 @@ void main() { check_invariants(&q); } + /// `VICTORY_DUE_HOT_FIRST=1`: slots a shader sampled lately go before + /// those looked at before, which still go before the other fresh ones; + /// off, the order is as before (looked at before first). + #[test] + fn due_hot_first_serves_sampled_slots_before_rechecks() { + let due = || Due { + again: vec![(1, 10, NO_CHECKED), (2, 11, NO_CHECKED)], + fresh: vec![(3, 12), (4, 13), (5, 14)], + checked: Vec::new(), + }; + let calls = std::cell::Cell::new(0); + let hot = |index: u32| { + calls.set(calls.get() + 1); + index == 4 + }; + let (order, known) = due().ordered_by(4, true, hot); + assert_eq!(order, [(4, 13), (2, 11), (1, 10), (5, 14)]); + assert_eq!(known.len(), order.len()); + assert_eq!(calls.get(), 5); + let (order, _) = due().ordered_by(4, false, hot); + assert_eq!(order, [(2, 11), (1, 10), (4, 13), (5, 14)]); + // A hot burst bigger than `max` leaves no room for background slots. + let (order, _) = due().ordered_by(1, true, hot); + assert_eq!(order, [(4, 13)]); + } + + #[test] + fn sampled_rechecks_keep_their_fingerprints_ahead_of_background_slots() { + let mut queue = TextureQueue::default(); + queue.written(10, 1, 1, true); + let write = queue.entry(10).unwrap().write; + queue.recheck(10, write, 2, (0x1000, 64), 7, 0, 1); + let checked = queue.checked(10).unwrap(); + let due = || Due { + again: vec![(10, write, 0), (11, write + 3, NO_CHECKED)], + fresh: vec![(12, write + 1), (13, write + 2)], + checked: vec![checked], + }; + let (order, known) = due().ordered_by(3, true, |index| index == 10 || index == 12); + assert_eq!(order, [(12, write + 1), (10, write), (11, write + 3)]); + assert_eq!(known, [None, Some(checked), None]); + + let (order, known) = due().ordered_by(1, true, |index| index == 10 || index == 12); + assert_eq!(order, [(12, write + 1)]); + assert_eq!(known, [None]); + } + /// `Due::ordered` truncation matches a naive full-sort reference across /// `again.len() > max`, `fresh.len() > max`, mixed queues, and edge `max`. #[test] @@ -9122,7 +9285,7 @@ void main() { } } for max in 0..=32 { - let got = mixed.due_and_census(20).0.ordered(max); + let got = mixed.due_and_census(20).0.ordered(max, false); let want = reference(&mixed, 20, max); assert_eq!(got, want, "mixed mismatch at max={max}"); } @@ -9133,7 +9296,7 @@ void main() { fresh_only.written(200 + ((i * 7) % 23), 1, 0, false); } for max in 0..=25 { - let got = fresh_only.due_and_census(10).0.ordered(max); + let got = fresh_only.due_and_census(10).0.ordered(max, false); let want = reference(&fresh_only, 10, max); assert_eq!(got, want, "fresh-only mismatch at max={max}"); } @@ -9146,7 +9309,7 @@ void main() { again_only.recheck(300 + i, w, 4, (0x8000, 4096), u64::from(i) + 1, 0, 1); } for max in 0..=17 { - let got = again_only.due_and_census(10).0.ordered(max); + let got = again_only.due_and_census(10).0.ordered(max, false); let want = reference(&again_only, 10, max); assert_eq!(got, want, "again-only mismatch at max={max}"); } @@ -9222,8 +9385,8 @@ void main() { heap_batch.flush(&a); for at in [50, 60, 100, u64::MAX] { - let (oa, ka, ca) = a.texture_slots_due_known(at, 200); - let (ob, kb, cb) = b.texture_slots_due_known(at, 200); + let (oa, ka, ca) = a.texture_slots_due_known(at, 200, false); + let (ob, kb, cb) = b.texture_slots_due_known(at, 200, false); assert_eq!(oa, ob, "order mismatch at frame {at}"); assert_eq!(ka, kb, "known mismatch at frame {at}"); assert_eq!(ca, cb, "census mismatch at frame {at}"); @@ -9370,10 +9533,10 @@ void main() { let (di, ci) = idx.due_and_census(probe); assert_eq!(cf, ci, "census mismatch at step {step} probe {probe}"); assert_eq!(flat.census(probe), idx.census(probe), "census() mismatch at step {step}"); - assert_eq!(df.ordered(17), di.ordered(17), "ordered(17) mismatch at step {step}"); + assert_eq!(df.ordered(17, false), di.ordered(17, false), "ordered(17) mismatch at step {step}"); let (df2, _) = flat.due_and_census(probe); let (di2, _) = idx.due_and_census(probe); - assert_eq!(df2.ordered(200), di2.ordered(200), "ordered(200) mismatch at step {step}"); + assert_eq!(df2.ordered(200, false), di2.ordered(200, false), "ordered(200) mismatch at step {step}"); let mut af = flat.all_due(probe); let mut ai = idx.all_due(probe); af.sort_unstable(); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9bf4880945..430a452ef7 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -859,6 +859,58 @@ pub(crate) fn take_dropped() -> u64 { pub(crate) fn dropped_all() -> u64 { DROPPED.load(Ordering::Relaxed) } + +/// Why a draw or dispatch was dropped ([`take_drop_causes`]), in the order +/// of [`DROP_CAUSES`]: set where it fails, read where it is counted. +pub(crate) const WHY_NULL: u8 = 0; +pub(crate) const WHY_LEFT_OUT: u8 = 1; +pub(crate) const WHY_MAKING: u8 = 2; +pub(crate) const WHY_UNTRANSLATED: u8 = 3; +pub(crate) const WHY_REFUSED: u8 = 4; +const WHY_KIND: u8 = 5; +const WHY_BIND: u8 = 6; +const WHY_ROOT_SLOTS: u8 = 7; +const WHY_INDEX: u8 = 8; +const WHY_BUILDER: u8 = 9; +const WHY_OTHER: u8 = 10; + +/// What each cause is called in the line. +pub(crate) const DROP_CAUSES: [&str; 11] = [ + "no pipeline bound", + "pipeline left out on purpose", + "pipeline being made", + "a shader that does not translate", + "pipeline refused by the host", + "pipeline of another kind", + "binding failed (tables, views, title memory)", + "no free slot for a root view", + "index buffer without a host copy", + "ray-tracing builder off", + "other (rectangles, mesh tests)", +]; + +static DROP_COUNTS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + +thread_local! { + static WHY: std::cell::Cell = const { std::cell::Cell::new(WHY_OTHER) }; +} + +/// Notes why the draw being prepared on this thread fails; `false`. +fn why(cause: u8) -> bool { + WHY.set(cause); + false +} + +/// Counts a dropped draw or dispatch, by the cause last noted on this thread. +fn count_drop() { + DROPPED.fetch_add(1, Ordering::Relaxed); + DROP_COUNTS[usize::from(WHY.replace(WHY_OTHER))].fetch_add(1, Ordering::Relaxed); +} + +/// The dropped draws and dispatches by cause since the last call. +pub(crate) fn take_drop_causes() -> [u64; 11] { + std::array::from_fn(|i| DROP_COUNTS[i].swap(0, Ordering::Relaxed)) +} /// A root SRV's dynamic slot in a list, and the host copy it shows. type RootSlot = (u32, Option>); @@ -1317,6 +1369,15 @@ fn full_card_pass() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0")) } +/// `VICTORY_HELD_HOT=1` (off by default; needs `VICTORY_SAMPLED_MARKS=1`): +/// while the card has no room, every eighth frame the slots held back for +/// it that a shader sampled in the last 60 frames are due again at once +/// (`HostHeap::texture_slots_hot_back`), instead of after their hold of +/// about four seconds or once the card has room. +fn held_hot() -> bool { + crate::asked_for!("VICTORY_HELD_HOT") +} + /// Whether a texture that has its host copy is still brought up to date /// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: /// no). @@ -2503,6 +2564,7 @@ impl State { /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool { + WHY.set(WHY_OTHER); #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { return false; @@ -2515,11 +2577,11 @@ impl State { .filter(|_| sample_mask_on()) .and_then(|_| crate::pipeline::host_pipeline_masked(self.pipeline as This)); let Some(p) = masked.or_else(|| crate::pipeline::host_pipeline(self.pipeline as This)) else { - return false; + return why(crate::pipeline::why_no_host(self.pipeline as This)); }; if p.compute || p.mesh != mesh { once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); - return false; + return why(WHY_KIND); } if p.rects && self.topology != RECTANGLES { // Its geometry stage would turn each triangle into a rectangle. @@ -2540,6 +2602,9 @@ impl State { } } if !self.bind(list, p, false) { + if WHY.get() == WHY_OTHER { + why(WHY_BIND); + } return false; } let l = &list.list; @@ -2573,7 +2638,7 @@ impl State { if indexed { let v = self.index; let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { - return false; + return why(WHY_INDEX); }; shadow.refresh(list, v.address, u64::from(v.size)); let view = D3D12_INDEX_BUFFER_VIEW { @@ -3077,7 +3142,7 @@ impl State { crate::host::settle_for_fence(); host.dynamic(1) }) else { - return false; + return why(WHY_ROOT_SLOTS); }; self.dynamic.push((key.0, host.id(), index, 1)); if let Some((a, s)) = &shadow { @@ -3153,7 +3218,7 @@ impl State { crate::host::settle_for_fence(); host.dynamic(1) }) else { - return false; + return why(WHY_ROOT_SLOTS); }; self.dynamic.push((key.0, host.id(), index, 1)); match &shadow { @@ -3983,33 +4048,33 @@ impl State { let baking = crate::texture::BAKING.get(); let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); let frame_pass = !required && !baking && sync.is_none(); + let frame_cap = if frame_pass { texspk_pass_ms() } else { None }; static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); let pressured = crate::residency::pressured(); let vram_budget = memory.map(|[budget, ..]| budget); - // With `VICTORY_DUE_INDEX=1` and `VICTORY_TEXSPK_PASS_MS` set, skip the - // queue prep and due snapshot when this frame's pass time ceiling is - // already spent (even under catch-up scaling), while still flipping - // views whose uploads finished. - if crate::descriptor::host::due_index() - && frame_pass - && let Some(cap) = texspk_pass_ms() - && PASS_FRAME.load(Ordering::Relaxed) == frame - { + // Before counting the due slots, use the largest cap this pass could + // get, including catch-up when there is room and RAM is not pressured. + let cap_spent = frame_cap.is_some_and(|cap| { let max_cap = texspk_cap_ms(cap, vram_budget, room, pressured, catchup && room && !pressured); - if PASS_FRAME_NANOS.load(Ordering::Relaxed) >= max_cap.saturating_mul(1_000_000) { - before(1, || { - host.texture_views_remade(); - host.texture_slots_flip(); - }); - return false; - } + PASS_FRAME.load(Ordering::Relaxed) == frame + && PASS_FRAME_NANOS.load(Ordering::Relaxed) >= max_cap.saturating_mul(1_000_000) + }); + if cap_spent && crate::descriptor::host::due_index() { + before(1, || { + host.texture_views_remade(); + host.texture_slots_flip(); + }); + return false; } before(0, || { // Room again: the slots held back while the card was full are // due now (`full_card_pass`). if room { host.texture_slots_room(frame); + } else if held_hot() && frame.is_multiple_of(8) { + // No room: those a shader samples now come back all the same. + host.texture_slots_hot_back(frame); } // Slots whose texture's memory the runtime mapped, unmapped or // wrote since the last pass are due again. @@ -4032,9 +4097,14 @@ impl State { if room { before(0, || host.texture_slots_waiting(frame)); } + // The flat queue still processes remaps and publishes completed views, + // but an exhausted frame cannot use the due snapshot or its ordering. + if cap_spent { + return false; + } // (And what the queue knew of each, `known`: see `Tells`.) let (mut due, mut known, census) = - before(2, || host.texture_slots_due_known(frame, if baking { 1 << 16 } else { 4096 })); + before(2, || host.texture_slots_due_known(frame, if baking { 1 << 16 } else { 4096 }, frame_pass && !room)); // (Those that are due later after all that are due.) let on_time = due.len(); if baking { @@ -4042,7 +4112,7 @@ impl State { let taken: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); static AHEAD: AtomicU64 = AtomicU64::new(u64::MAX); let again = AHEAD.swap(frame, Ordering::Relaxed) == frame; - let (ahead, ahead_known, _) = host.texture_slots_due_known(frame + BAKE_AHEAD[usize::from(again)], 1 << 16); + let (ahead, ahead_known, _) = host.texture_slots_due_known(frame + BAKE_AHEAD[usize::from(again)], 1 << 16, false); for (slot, knew) in ahead.into_iter().zip(ahead_known) { if !taken.contains(&slot.0) { due.push(slot); @@ -4119,8 +4189,8 @@ impl State { // A frame's runs of the pass (its own and the early ones, not those // before a bake) within `VICTORY_TEXSPK_PASS_MS` together // ([`texspk_pass_ms`]). - let span = match texspk_pass_ms() { - Some(cap) if frame_pass => { + let span = match frame_cap { + Some(cap) => { if PASS_FRAME.swap(frame, Ordering::Relaxed) != frame { PASS_FRAME_NANOS.store(0, Ordering::Relaxed); } @@ -4642,7 +4712,7 @@ impl State { let took = began.elapsed().as_nanos() as u64; HEAP_TEXTURE_NANOS[4].fetch_add(took, Ordering::Relaxed); HEAP_TEXTURE_PASSES[3 + kind].fetch_add(took, Ordering::Relaxed); - if frame_pass && texspk_pass_ms().is_some() { + if frame_cap.is_some() { PASS_FRAME_NANOS.fetch_add(took, Ordering::Relaxed); } served @@ -4690,13 +4760,15 @@ impl State { self.window = None; #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { - DROPPED.fetch_add(1, Ordering::Relaxed); + count_drop(); crate::pipeline::note_drop(self.pipeline as This); return; } // The ray-tracing structure builder's stages run all or none. + WHY.set(WHY_OTHER); if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { - DROPPED.fetch_add(1, Ordering::Relaxed); + why(WHY_BUILDER); + count_drop(); #[cfg(feature = "diagnostics")] { crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned()); @@ -4709,7 +4781,8 @@ impl State { pipeline = format_args!("{:#x}", self.pipeline), "a dispatch without a host pipeline dropped" ); - DROPPED.fetch_add(1, Ordering::Relaxed); + why(crate::pipeline::why_no_host(self.pipeline as This)); + count_drop(); #[cfg(feature = "diagnostics")] { crate::pipeline::note_drop(self.pipeline as This); @@ -4725,7 +4798,10 @@ impl State { return; } if !self.bind(list, p, true) { - DROPPED.fetch_add(1, Ordering::Relaxed); + if WHY.get() == WHY_OTHER { + why(WHY_BIND); + } + count_drop(); // A stage of the structure builder that cannot be bound is a // dropped stage: the others stop too. if crate::pipeline::is_builder(self.pipeline as This) { @@ -4797,12 +4873,19 @@ impl State { /// and it gives each the sky's light: on floors seen at a grazing angle, a white grain the /// title's denoiser cannot smooth (play session 2026-11-27, the house's parquet). Left out, /// those rays keep what the screen-space passes found. Water's are kept: without them its - /// reflections hold earlier frames' bytes. + /// reflections hold earlier frames' bytes. An explicitly requested reflection estimate + /// also needs the miss output for the layers it can use. fn sky_miss_left_out(&self, p: &HostPipeline) -> bool { static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); - !*KEEP.get_or_init(|| crate::switch::on("VICTORY_RAYMISS_KEEP")) - && p.stages.first().and_then(|s| s.shader.ambient) == Some(crate::ambient::Role::Miss) - && matches!(self.miss_layer(p), crate::ambient::MISS_OPAQUE | crate::ambient::MISS_ALPHA) + if *KEEP.get_or_init(|| crate::switch::on("VICTORY_RAYMISS_KEEP")) + || crate::ambient::raymiss_sky().is_some() + || p.stages.first().and_then(|s| s.shader.ambient) != Some(crate::ambient::Role::Miss) + { + return false; + } + let layer = self.miss_layer(p); + matches!(layer, crate::ambient::MISS_OPAQUE | crate::ambient::MISS_ALPHA) + && !crate::ambient::keep_miss_for_specular(layer) } /// The stand-in for the indirect light after a dispatch of `p` @@ -4827,10 +4910,7 @@ impl State { // On again by default (2026-11-27): those dark patches were water tiles the tile // list had dropped (`VICTORY_LOOPS_WAVE`), not this; without it glass in a dark room // mirrors the bright sky (run fix2, spectacles 75 s into the opening). `=0`: off. - let alpha_too = !std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "0"); - if role == Role::Miss - && !(layer == crate::ambient::MISS_OPAQUE || (alpha_too && layer == crate::ambient::MISS_ALPHA)) - { + if role == Role::Miss && !crate::ambient::specular_layer(layer) { crate::ambient::note_miss(MissNote::Water); return false; } @@ -4948,6 +5028,14 @@ impl State { _ => false, } }; + // `VICTORY_RAYMISS_SKY`: the sky the miss program gave, scaled; no + // depth needed, and nothing else of the estimate. + if role == Role::Miss + && let Some((desc, handle)) = image.as_ref() + && crate::ambient::sky_after(list, layer, desc, *handle) + { + return true; + } if role == Role::Resolve && crate::ambient::neutral_level().is_some() && neutral_view() && let Some((desc, handle)) = image.as_ref() && crate::ambient::neutral_after(list, role, desc, *handle) @@ -5456,7 +5544,7 @@ impl State { false }; if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); + count_drop(); #[cfg(feature = "diagnostics")] dropped(self.pipeline); } @@ -6127,7 +6215,7 @@ impl State { DRAWN.fetch_add(1, Ordering::Relaxed); } if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); + count_drop(); #[cfg(feature = "diagnostics")] dropped(self.pipeline); } @@ -6311,7 +6399,7 @@ impl State { DRAWN.fetch_add(1, Ordering::Relaxed); } if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); + count_drop(); #[cfg(feature = "diagnostics")] dropped(self.pipeline); } @@ -8001,6 +8089,21 @@ mod tests { assert_eq!(direct_mesh_grid([4, 3, 0]), Some(([4, 3, 0], 0))); } + /// Each drop counts under the cause noted last on its thread, and a + /// drop with none noted under "other". (Other tests may drop draws too: + /// at least these.) + #[test] + fn drops_are_counted_by_the_cause_noted_last() { + use super::{WHY_INDEX, WHY_OTHER, count_drop, take_drop_causes, why}; + assert!(!why(WHY_INDEX)); + count_drop(); + count_drop(); + let causes = take_drop_causes(); + assert!(causes[usize::from(WHY_INDEX)] >= 1); + assert!(causes[usize::from(WHY_OTHER)] >= 1); + assert_eq!(super::DROP_CAUSES.len(), causes.len()); + } + #[test] fn a_frames_pass_runs_share_the_texspk_cap() { use super::pass_span_left; diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7959e73ad6..92b0b7bbb9 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -384,6 +384,7 @@ pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> { } } let us = started.elapsed().as_micros() as u64; + waited_here(1, us); MAPPED[0].fetch_add(1, Ordering::Relaxed); MAPPED[1].fetch_add(us, Ordering::Relaxed); MAPPED[2].fetch_max(us, Ordering::Relaxed); @@ -475,6 +476,7 @@ pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> window // SAFETY: a live heap or resource of the device's. let made = unsafe { device.MakeResident(&[Some(object)]) }; let us = started.elapsed().as_micros() as u64; + waited_here(0, us); RESIDENT[0].fetch_add(1, Ordering::Relaxed); RESIDENT[1].fetch_add(us, Ordering::Relaxed); RESIDENT[2].fetch_max(us, Ordering::Relaxed); @@ -663,6 +665,73 @@ pub(crate) fn before_send(queue: &ID3D12CommandQueue) { /// Times, microseconds and the longest of [`resident`]. static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +/// The threads that wait for new memory, by kind ([`WAIT_THREADS`]). +const WAIT_THREADS: [&str; 6] = ["the submitting thread", "list translators", "the relay", "helpers of ours", "others of ours", "the title's"]; + +/// Since the last frame line, of [`resident`] (0) and [`mapped`] (1), by +/// [`WAIT_THREADS`]: times, microseconds, the longest. +static WAITED: [[[std::sync::atomic::AtomicU64; 3]; 6]; 2] = + [const { [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 6] }; 2]; + +/// Of [`resident`] (0) or [`mapped`] (1): this thread waited `us`. +fn waited_here(which: usize, us: u64) { + let kind = match std::thread::current().name().unwrap_or("") { + "victory-submit" => 0, + name if name.starts_with("victory-list-") => 1, + "victory-relay" => 2, + name if name.starts_with("victory-wide-") || name.starts_with("victory-refresh-ahead") || name.starts_with("victory-land") => 3, + name if name.starts_with("victory-") => 4, + _ => 5, + }; + let w = &WAITED[which][kind]; + w[0].fetch_add(1, Ordering::Relaxed); + w[1].fetch_add(us, Ordering::Relaxed); + w[2].fetch_max(us, Ordering::Relaxed); +} + +/// For the frame-rate line: which threads waited for new memory. +fn waited_line(frames: f64) { + if !wait_resident() { + return; + } + let mut parts = Vec::new(); + for (which, what) in [(0, "made resident"), (1, "mapped")] { + let by: Vec = WAIT_THREADS + .iter() + .enumerate() + .filter_map(|(kind, name)| { + let w = &WAITED[which][kind]; + let [n, us, most] = [0, 1, 2].map(|i| w[i].swap(0, Ordering::Relaxed)); + (n > 0).then(|| format!("{name} {:.1} times {:.1} ms (the longest {:.1})", n as f64 / frames, us as f64 / 1e3 / frames, most as f64 / 1e3)) + }) + .collect(); + if !by.is_empty() { + parts.push(format!("{what}: {}", by.join(", "))); + } + } + if !parts.is_empty() { + tracing::info!( + "new memory waited for per frame, by the threads that waited (VICTORY_WAIT_RESIDENT_UPLOADS=0 makes upload memory resident at once): {}", + parts.join("; ") + ); + } +} + +/// Whether memory in the upload heap is made resident and waited for, as +/// other new memory is (on by default; `VICTORY_WAIT_RESIDENT_UPLOADS=0`: +/// made resident with its creation, not waited for). +/// +/// The waits are for what lists sent before the memory was made may read: +/// a slot of our descriptor heaps that shows it ([`wait_resident`]). Upload +/// memory is no slot's: its buffers are read by the lists recorded after +/// them (copy sources, constants, what goes up), which the system has wait +/// for their memory anyway. 149,000 waits, 78 s in 9 minutes, the longest +/// 1.2 s, in play log 20261128-235457 (all new memory). +fn wait_resident_uploads() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| wait_resident() && std::env::var_os("VICTORY_WAIT_RESIDENT_UPLOADS").is_none_or(|v| v != "0")) +} + /// Whether memory the card was given stays with it while there is room (on /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader /// that reads past a view (a raw load through a typed, structured or @@ -847,6 +916,7 @@ fn bury_lag() -> u64 { /// numbers come in order within each thread's shard. fn bury(finished: u64) { uav_pool::drain_retired_uavs(finished); + let began = std::time::Instant::now(); let finished = finished.saturating_sub(bury_lag()); let timing = relay_timing().then(Instant::now); let mut done: Vec<(u64, Retired)> = Vec::new(); @@ -867,7 +937,15 @@ fn bury(finished: u64) { } let count = done.len(); let drained = timing.map(|_| Instant::now()); - drop(done); + match bury_aside() { + Some(aside) => { + // (If the thread is gone, here after all.) + if let Err(e) = aside.send(done) { + drop(e.0); + } + } + None => drop(done), + } if let (Some(start), Some(lock_time), Some(drained)) = (timing, lock_time, drained) { let total = start.elapsed(); if total >= Duration::from_millis(5) { @@ -883,6 +961,46 @@ fn bury(finished: u64) { ); } } + crate::land::spent(crate::land::stat::BURY, began); +} + + +/// Whether what finished submissions held is let go of on a thread of its +/// own, `victory-bury` (`VICTORY_BURY_ASIDE=1`; off by default: on the +/// thread that saw them finish). +/// +/// With the texture pool off on a card of 8 GB, letting go of textures and +/// buffers took the relay's thread 590-980 ms a frame in the frames the +/// game froze (play log 20261128-235457, 00:02:08 and 00:02:50: "the rest" +/// of its landing), while the submitting thread waited for that thread's +/// landings (470 and 835 ms "waiting for flights"). What is let go of here +/// no submission names any more ([`bury_lag`] after it finished): later is +/// as good, only its memory comes back later. +fn bury_aside() -> Option<&'static std::sync::mpsc::Sender>> { + static ASIDE: OnceLock>>> = OnceLock::new(); + ASIDE + .get_or_init(|| { + if !crate::switch::on("VICTORY_BURY_ASIDE") { + return None; + } + let (send, take) = std::sync::mpsc::channel::>(); + let spawned = std::thread::Builder::new().name("victory-bury".into()).spawn(move || { + for done in take { + drop(done); + } + }); + match spawned { + Ok(_) => { + tracing::info!("what finished submissions held is let go of on a thread of its own (VICTORY_BURY_ASIDE=1)"); + Some(send) + } + Err(e) => { + tracing::warn!(error = %e, "no thread to let go of what finished submissions held"); + None + } + } + }) + .as_ref() } /// Objects [`retire`] dropped at once (no submission was running) and @@ -1563,6 +1681,17 @@ mod tests { assert_eq!(retry.attempt(recovered, || Ok::<_, ()>(43)), Some(Ok(43))); } + #[test] + fn the_drop_causes_line_names_those_there_were_per_frame() { + let mut causes = [0u64; 11]; + causes[0] = 50; + causes[8] = 5; + assert_eq!( + super::drop_causes_line(&causes, 10.0), + "draws and dispatches dropped per frame, by cause: 5.0 no pipeline bound, 0.5 index buffer without a host copy" + ); + } + /// A list of ours is found by its name, with the debug layer's note or not. #[cfg(feature = "diagnostics")] #[test] @@ -5550,6 +5679,18 @@ unsafe fn wait_host_fence(fence: &ID3D12Fence, target: u64, event: HANDLE, conte } } +/// The line of the frame line's dropped draws and dispatches by cause +/// (`draw::DROP_CAUSES`), per frame; the causes with none left out. +fn drop_causes_line(causes: &[u64], frames: f64) -> String { + let parts: Vec = causes + .iter() + .zip(crate::draw::DROP_CAUSES) + .filter(|(n, _)| **n > 0) + .map(|(n, what)| format!("{:.1} {what}", *n as f64 / frames)) + .collect(); + format!("draws and dispatches dropped per frame, by cause: {}", parts.join(", ")) +} + /// The thread that settles the flights once the card has run them all /// ([`late`]): without it a bottom-of-pipe write would reach the title only /// at the next call that settles, and a title thread that polls such a @@ -6246,6 +6387,7 @@ pub(crate) mod awake; #[cfg(test)] mod bus; mod card_steps; +pub(crate) mod early_refresh; #[cfg(feature = "diagnostics")] mod fill_wait; #[cfg(feature = "diagnostics")] @@ -6258,6 +6400,7 @@ pub use menu::{settings_pad_capture, settings_pad_key}; mod panel; pub(crate) mod place; mod pacing; +mod startup_textures; mod recycle; /// A buffer of at least `size` bytes for one recording of a list: taken @@ -8927,6 +9070,7 @@ impl Host { batch.fill(); next("submit: the last refreshes"); batch.flush(); + batch.settle_aside(ASIDE_OTHER); crate::watch::ask_once_end(); split.part(2); next("submit: snapshots"); @@ -11390,7 +11534,11 @@ impl HostList { copies += 1; } batch.fill(); - batch.title_written(); + if send::own() { + batch.title_written(); + } else { + batch.title_written_at(dst, len); + } // Into a heap's records: the rounds asked for earlier // did not see it (`crate::heap_marks`). if crate::heap_marks::on() && crate::descriptor::in_shader_heap(dst, len) { @@ -11442,6 +11590,8 @@ impl HostList { if free { batch.title_written(); } + // (It reads its copy.) + batch.settle_aside(ASIDE_OTHER); let kept = batch.forwards.iter().any(|f| f.copy == (n, i)); match p.prepare(free, kept) { Some((bytes, true)) => { @@ -11466,6 +11616,7 @@ impl HostList { } Step::Run(work) | Step::Host(work, _) => { batch.fill(); + batch.settle_aside(ASIDE_OTHER); #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { @@ -11517,6 +11668,7 @@ impl HostList { continue; } Step::Plane((_, len), fill) => { + batch.settle_aside(ASIDE_OTHER); let started = std::time::Instant::now(); fill(); PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -11604,6 +11756,51 @@ static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::A /// heaps' records with the slots after it (15), the lists sent (5). static SEND_SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; +/// Since the last frame-rate line, of the submission's refreshes on all the +/// threads that do them: copies looked at to find nothing new and the +/// microseconds of that; copies refreshed and theirs (where none of them is +/// found new, nothing at all is copied either way). +static REFRESH_WORK: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Adds `n` of `which` (0 looking, 1 refreshing) and the time since `from`. +fn refresh_work(which: usize, n: u64, from: std::time::Instant) { + REFRESH_WORK[2 * which].fetch_add(n, Ordering::Relaxed); + REFRESH_WORK[2 * which + 1].fetch_add(from.elapsed().as_micros() as u64, Ordering::Relaxed); +} + +/// `shadow`'s [`crate::shadow::Shadow::nothing_new`] of `[from, to)`, counted +/// in [`REFRESH_WORK`]. +fn looked(shadow: &crate::shadow::Shadow, from: usize, to: usize) -> bool { + let started = std::time::Instant::now(); + let same = shadow.nothing_new(from, to - from); + refresh_work(0, 1, started); + same +} + +/// For the frame-rate line: where the submission's refreshes go, summed over +/// the threads (the "refreshes" of the submitting thread's line is the time +/// it waits for them). +fn refresh_work_line(frames: f64) { + aside_line(frames); + let w: [f64; 4] = std::array::from_fn(|i| REFRESH_WORK[i].swap(0, Ordering::Relaxed) as f64 / frames); + if w[0] + w[2] > 0.0 { + let live = crate::shadow::live_bytes(); + let mb = |b: u64| b >> 20; + tracing::info!( + "the submission's refreshes per frame, on all the threads that do them: {:.0} copies looked at for something new in {:.1} ms, {:.0} refreshed in {:.1} ms; host copies of title memory now: {} copies, {} MB in the PC's memory ({} MB of it snapshots to compare with), {} MB on the card ({} MB of it hashes to compare with)", + w[0], + w[1] / 1000.0, + w[2], + w[3] / 1000.0, + live.copies, + mb(live.ram), + mb(live.ram_compare), + mb(live.card), + mb(live.card_compare), + ); + } +} + /// Since the last frame-rate line: flushes of refreshes, their refreshes, /// those known to copy nothing, and those done on several threads. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; @@ -11961,6 +12158,11 @@ struct Batch { gpu_writes_seen: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, declared: Vec, declared_at: ByCopy, + /// The last flush's copies, going on beside the steps + /// ([`refresh_beside`]). + aside: Option, + /// [`refresh_beside`] for this batch whatever the switch says (tests). + aside_forced: bool, } thread_local! { @@ -12019,7 +12221,7 @@ fn sift_front(spans: Vec<(std::sync::Arc, usize, usize)>) let (s, k) = (spans.clone(), keep.clone()); crate::shadow::wide_each(spans.len(), move |i| { let (shadow, from, to) = &s[i]; - if !shadow.nothing_new(*from, *to - *from) { + if !looked(shadow, *from, *to) { k[i].store(true, Ordering::Relaxed); } }); @@ -12269,6 +12471,7 @@ impl Batch { /// Emptied (the room kept) for the thread's next submission. fn give_back(mut self) { + self.settle_aside(ASIDE_OTHER); self.refreshes.clear(); self.index.clear(); self.textures.clear(); @@ -12376,6 +12579,10 @@ impl Batch { /// Before shaders are given a range of `shadow`'s copy: its pending /// refresh is done, the others stay pending. fn flush_one(&mut self, shadow: &std::sync::Arc) { + // Its copy beside the steps: done before the shaders are given it. + if self.aside.as_ref().is_some_and(|a| a.shadows.contains(&(std::sync::Arc::as_ptr(shadow) as usize))) { + self.settle_aside(ASIDE_SHADERS); + } // From here on it is refreshed around what the shaders write. (What // is in front of all the steps was, up to here.) if !self.front { @@ -12407,7 +12614,9 @@ impl Batch { let started = std::time::Instant::now(); let _one = crate::timeline::span("a copy's refresh"); let copied = shadow.update(from, to - from); + crate::memattrs::submitted(shadow.attr, copied); let us = started.elapsed().as_micros() as u64; + refresh_work(1, 1, started); #[cfg(feature = "diagnostics")] crate::copystat::range(from, to - from, us, 0); PREPARING[0].fetch_add(us, Ordering::Relaxed); @@ -12425,6 +12634,23 @@ impl Batch { /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); + self.settle_aside(ASIDE_OTHER); + self.ahead.clear(); + self.textures.clear(); + } + + /// [`Batch::title_written`] for a write of `[at, at + len)` alone: the + /// copies beside the steps go on unless one reads a page of it + /// ([`refresh_beside`]). + fn title_written_at(&mut self, at: usize, len: usize) { + self.flush(); + if let Some(aside) = &self.aside { + if aside.ahead || aside.touches(at, at + len) { + self.settle_aside(ASIDE_WRITE); + } else { + ASIDE_COUNTS[7].fetch_add(1, Ordering::Relaxed); + } + } self.ahead.clear(); self.textures.clear(); } @@ -12492,10 +12718,12 @@ impl Batch { } else { let all = spans.len(); if batch { + let checking = std::time::Instant::now(); let mut same = crate::shadow::nothing_new_all(spans.iter().map(|(shadow, from, to)| (&**shadow, *from, *to))).into_iter(); spans.retain(|_| !same.next().unwrap_or(false)); + refresh_work(0, all as u64, checking); } else { - spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + spans.retain(|(shadow, from, to)| !looked(shadow, *from, *to)); } let skipped = (all - spans.len()) as u64; if skipped != 0 { @@ -12651,6 +12879,8 @@ impl Batch { if self.refreshes.is_empty() { return; } + // One pass beside the steps at a time, in order. + self.settle_aside(ASIDE_OTHER); let (began, all) = (std::time::Instant::now(), self.refreshes.len()); let _flush = crate::timeline::span("refreshes of copies"); self.flush_all(); @@ -12674,10 +12904,12 @@ impl Batch { crate::watch::ahead_snapshot_into(&mut self.ahead_snap); let all = self.refreshes.len(); if batch { + let checking = std::time::Instant::now(); let mut same = crate::shadow::nothing_new_all(self.refreshes.iter().map(|(shadow, from, to)| (&**shadow, *from, *to))).into_iter(); self.refreshes.retain(|_| !same.next().unwrap_or(false)); + refresh_work(0, all as u64, checking); } else { - self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + self.refreshes.retain(|(shadow, from, to)| !looked(shadow, *from, *to)); } crate::cores::log::note(crate::cores::log::COPIES, started.elapsed().as_micros() as u64); PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -12716,6 +12948,16 @@ impl Batch { AMONG[1].fetch_add(lap.elapsed().as_nanos() as u64, Ordering::Relaxed); lap = std::time::Instant::now(); } + if self.aside_on() && !self.refreshes.is_empty() { + let check_noop = light && self.refreshes.len() > FEW && !sifted && !batch; + let refreshes = std::mem::take(&mut self.refreshes); + self.post_aside(refreshes, check_noop, ahead); + if many { + AMONG[2].fetch_add(lap.elapsed().as_nanos() as u64, Ordering::Relaxed); + } + // (The asking ahead ends when they are waited for.) + return; + } if wide_refresh() && self.refreshes.len() >= 4 { // Each copy on its own, several at a time: a copy's refresh // writes that copy and reads title memory, nothing of another's. @@ -12729,7 +12971,7 @@ impl Batch { crate::shadow::wide_each_scoped(self.refreshes.len(), if check_noop { 8 } else { 1 }, &|lo, hi| { let mut noops = 0u64; for (shadow, from, to) in &self.refreshes[lo..hi] { - if check_noop && shadow.nothing_new(*from, *to - *from) { + if check_noop && looked(shadow, *from, *to) { noops += 1; continue; } @@ -12774,6 +13016,154 @@ fn flush_sift() -> bool { *ON.get_or_init(|| crate::switch::on("VICTORY_FLUSH_SIFT")) } +/// Whether a flush's copies go on on the kept threads while the submitting +/// thread goes on with the steps (`VICTORY_REFRESH_BESIDE=1`; off by default). +/// +/// In play log 20261129-115844 (v2026.11.29.01) the submitting thread spent +/// 48.5 ms of its 95.8 a frame waiting for its refreshes: 1,145 real copies a +/// frame at 126 microseconds each (`docs/refresh-cost-h.md`). The copies' +/// order is kept by waiting for them where it matters, and only there +/// ([`Batch::settle_aside`]): before title memory on a page they read is +/// written ([`Batch::title_written_at`]), before a step of ours whose reads +/// and writes are not known (a run, a host step, a plane, a placed copy), +/// before shaders are given one of their copies ([`Batch::flush_one`]), +/// before the next flush, and at the end of the steps, before the snapshots, +/// the copies in the card's memory and the lists' sending read the copies. +/// The submitting thread's own reads of title memory between (fills, +/// textures) do not touch the copies. +fn refresh_beside() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_REFRESH_BESIDE")) +} + +/// The copies of a flush going on beside the steps ([`refresh_beside`]). +struct AsidePass { + /// Done when dropped. + copies: crate::shadow::Beside, + /// The 64 KiB pages of title memory they read, `[first, last)`, in order + /// and apart. + pages: Vec<(usize, usize)>, + /// The copies, by address. + shadows: std::collections::HashSet>, + /// The write watch was asked ahead for them: the asking ends when they + /// are done, and no title write goes on beside it. + ahead: bool, +} + +impl AsidePass { + /// Whether a copy reads a page of `[from, to)`. + fn touches(&self, from: usize, to: usize) -> bool { + pages_touch(&self.pages, from / crate::watch::PAGE, to.div_ceil(crate::watch::PAGE)) + } +} + +/// Of page ranges `[first, last)` in order and apart, whether one meets `[first, last)`. +fn pages_touch(pages: &[(usize, usize)], first: usize, last: usize) -> bool { + let at = pages.partition_point(|&(_, end)| end <= first); + pages.get(at).is_some_and(|&(start, _)| start < last) +} + +/// `ranges` (from, to) of bytes as 64 KiB page ranges in order and apart. +fn pages_of(ranges: impl Iterator) -> Vec<(usize, usize)> { + let mut pages: Vec<(usize, usize)> = ranges.map(|(from, to)| (from / crate::watch::PAGE, to.div_ceil(crate::watch::PAGE))).collect(); + pages.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for (first, last) in pages { + match merged.last_mut() { + Some((_, end)) if first <= *end => *end = (*end).max(last), + _ => merged.push((first, last)), + } + } + merged +} + +/// [`refresh_beside`] since the last frame-rate line: flushes left beside, +/// their copies, microseconds of refreshing on the kept threads, waits for +/// them at a title write on their pages, at a shader write, elsewhere (the +/// next flush, a step of ours, the end), nanoseconds waited, title writes +/// that went on beside them. +static ASIDE_COUNTS: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; +const ASIDE_WRITE: usize = 3; +const ASIDE_SHADERS: usize = 4; +const ASIDE_OTHER: usize = 5; + +fn aside_line(frames: f64) { + let a: [f64; 8] = std::array::from_fn(|i| ASIDE_COUNTS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if a[0] > 0.0 { + tracing::info!( + "refreshes beside the submitting thread per frame (VICTORY_REFRESH_BESIDE=1): {:.1} flushes, {:.0} copies, {:.1} ms \ + refreshing on the kept threads; waited for {:.1} ms: {:.1} times at a title write on their pages, {:.1} at a shader \ + write, {:.1} elsewhere; {:.1} title writes went on beside them", + a[0], + a[1], + a[2] / 1e3, + a[6] / 1e6, + a[3], + a[4], + a[5], + a[7], + ); + } +} + +impl Batch { + fn aside_on(&self) -> bool { + self.aside_forced || refresh_beside() + } + + /// `refreshes` begun on the kept threads ([`refresh_beside`]), those + /// known to copy nothing sifted there if `check_noop`. + fn post_aside(&mut self, refreshes: Vec<(std::sync::Arc, usize, usize)>, check_noop: bool, ahead: bool) { + const CHUNK: usize = 8; + let len = refreshes.len(); + FLUSHES[3].fetch_add(len as u64, Ordering::Relaxed); + ASIDE_COUNTS[0].fetch_add(1, Ordering::Relaxed); + ASIDE_COUNTS[1].fetch_add(len as u64, Ordering::Relaxed); + let pages = pages_of(refreshes.iter().map(|r| (r.1, r.2))); + let shadows = refreshes.iter().map(|r| std::sync::Arc::as_ptr(&r.0) as usize).collect(); + let all = std::sync::Arc::new(refreshes); + let jobs = (0..len) + .step_by(CHUNK) + .map(|lo| { + let all = all.clone(); + Box::new(move || { + for (shadow, from, to) in &all[lo..(lo + CHUNK).min(all.len())] { + if check_noop && looked(shadow, *from, *to) { + FLUSHES[2].fetch_add(1, Ordering::Relaxed); + continue; + } + let started = std::time::Instant::now(); + let _one = crate::timeline::span("a copy's refresh"); + let copied = shadow.update(*from, *to - *from); + refresh_work(1, 1, started); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + ASIDE_COUNTS[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + } + }) as Box + }) + .collect(); + self.aside = Some(AsidePass { copies: crate::shadow::run_beside(jobs), pages, shadows, ahead }); + } + + /// Waits for the copies beside the steps, counted under `why` + /// ([`refresh_beside`]). + fn settle_aside(&mut self, why: usize) { + let Some(aside) = self.aside.take() else { + return; + }; + let started = std::time::Instant::now(); + drop(aside.copies); + if aside.ahead { + crate::watch::ask_ahead_done(); + } + let ns = started.elapsed().as_nanos() as u64; + ASIDE_COUNTS[why].fetch_add(1, Ordering::Relaxed); + ASIDE_COUNTS[6].fetch_add(ns, Ordering::Relaxed); + SPLIT[6].fetch_add(ns, Ordering::Relaxed); + PREPARING[0].fetch_add(ns / 1000, Ordering::Relaxed); + } +} + /// [`flush_sift`]: the refreshes that may copy something, in their order. fn sift_refreshes(refreshes: Vec<(std::sync::Arc, usize, usize)>) -> Vec<(std::sync::Arc, usize, usize)> { use std::sync::atomic::AtomicBool; @@ -12782,7 +13172,7 @@ fn sift_refreshes(refreshes: Vec<(std::sync::Arc, usize, let (r, k) = (refreshes.clone(), keep.clone()); crate::shadow::wide_each(refreshes.len(), move |i| { let (shadow, from, to) = &r[i]; - if !shadow.nothing_new(*from, *to - *from) { + if !looked(shadow, *from, *to) { k[i].store(true, Ordering::Relaxed); } }); @@ -13324,7 +13714,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - buffer_not_resident(), + if wait_resident_uploads() { buffer_not_resident() } else { D3D12_HEAP_FLAG_NONE }, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, @@ -13332,7 +13722,9 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - buffer_resident(&self.device, b)?; + if wait_resident_uploads() { + buffer_resident(&self.device, b)?; + } b.Map(0, None, Some(&mut data)) }) }; @@ -13528,6 +13920,8 @@ struct Presenter { advisor: panel::Advisor, /// The F1 settings menu. menu: menu::Menu, + startup_textures: startup_textures::Loading, + loading_label: panel::LoadingLabel, /// The swap chain lets a frame be shown at once ([`tearing`]): its flags, kept for /// ResizeBuffers, which may not change them. tearing: bool, @@ -13845,6 +14239,9 @@ impl Meter { spans::line(frames); crate::shadow::back_line(frames); submit_split_line(frames); + early_refresh::line(frames); + refresh_work_line(frames); + waited_line(frames); fresh_open_line(frames); crate::mesh_rest::line(frames); crate::heap_marks::line(frames); @@ -13951,6 +14348,8 @@ impl Meter { #[cfg(feature = "diagnostics")] self.each.line(); crate::procmem::line(); + crate::memattrs::line(); + crate::resource::log_5s(); let table_slot_drops = crate::draw::take_table_slot_drops(); let table_slot_frames = std::mem::take(&mut self.table_slot_frames); let table_slot_drops_per_frame = table_slot_drops as f64 / table_slot_frames as f64; @@ -14270,6 +14669,10 @@ impl Meter { "CS_DefragHeap_ComputeRelocations since start" ); } + let causes = crate::draw::take_drop_causes(); + if causes.iter().any(|&n| n > 0) { + tracing::info!("{}", drop_causes_line(&causes, frames)); + } #[cfg(feature = "diagnostics")] { let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); @@ -14695,6 +15098,14 @@ impl Host { }; #[cfg(test)] present_seen::read(&self.device, list, &back); + if p.startup_textures.hold(video) { + // The title's frame and sampled-slot readbacks still run. Only + // the visible back buffer is replaced while uploads catch up. + crate::barstat::rb(list, &[transition(&back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + list.ClearRenderTargetView(self.rtv(Some(&back), None), &[0.0, 0.0, 0.0, 1.0], None); + crate::barstat::rb(list, &[transition(&back, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_DEST)]); + p.loading_label.draw(self, copy, &back, (width, height), format); + } p.panel.draw(self, copy, &back, (width, height), format); p.notice.draw(self, copy, &back, (width, height), format); p.advisor.draw(self, copy, &back, (width, height), format, p.notice.showing()); @@ -14959,6 +15370,8 @@ impl Host { notice: panel::Notice::new(), advisor: panel::Advisor::new(), menu: menu::Menu::new(), + startup_textures: Default::default(), + loading_label: Default::default(), tearing, presents_tearing: tearing, present_refused: false, @@ -16248,6 +16661,22 @@ mod trail { } } +#[cfg(test)] +mod waited_tests { + use super::{WAITED, waited_here}; + use std::sync::atomic::Ordering::Relaxed; + + /// A wait is counted for the kind of thread that waited. + #[test] + fn waits_are_counted_by_the_thread_that_waited() { + for (name, kind) in [("victory-submit", 0), ("victory-list-3", 1), ("victory-relay", 2), ("victory-wide-0", 3), ("victory-bury", 4), ("render", 5)] { + let before = WAITED[1][kind][0].load(Relaxed); + std::thread::Builder::new().name(name.into()).spawn(|| waited_here(1, 7)).unwrap().join().unwrap(); + assert!(WAITED[1][kind][0].load(Relaxed) > before, "{name}"); + } + } +} + #[cfg(test)] mod spare { use super::{Spare, make_or_free_and_retry}; @@ -16975,6 +17404,127 @@ mod refresh_tests { println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light()); } + /// `VICTORY_REFRESH_BESIDE`: copies refreshed beside the steps hold the + /// bytes from before a title write on their pages, never a mix, and the + /// next refresh those after it; shaders are given a copy only once its + /// refresh is done, and the steps' end leaves none going. No copy is + /// stale, as `VICTORY_REFRESH_CHECK=1` would look. + #[test] + fn refreshes_beside_keep_their_order() { + for view in [false, true] { + const LEN: usize = 8 * PAGE; + let region = title(LEN, view); + let elsewhere = title(PAGE, view); + // SAFETY (all writes and reads below): the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, LEN) }; + let data = memory(LEN); + let copy = Shadow::unbacked(region as u64, data, LEN as u64, false); + let held = |what: &str| { + let (title, ours) = unsafe { (std::slice::from_raw_parts(region as *const u8, LEN), std::slice::from_raw_parts(data, LEN)) }; + assert!(title == ours, "view {view}: {what}"); + }; + let _one = one_submission(); + let mut batch = Batch { aside_forced: true, ..Batch::default() }; + batch.add(©, region, LEN); + batch.flush(); + assert!(batch.aside.is_some(), "view {view}: left beside"); + // A write on other pages goes on beside them. + batch.title_written_at(elsewhere + 16, 16); + unsafe { std::ptr::write_bytes((elsewhere + 16) as *mut u8, 5, 16) }; + assert!(batch.aside.is_some(), "view {view}: not waited for by a write elsewhere"); + // A write on their pages waits for them first. + let at = region + 3 * PAGE + 10; + batch.title_written_at(at, 4); + assert!(batch.aside.is_none(), "view {view}: waited for by a write on their pages"); + held("as before the write"); + unsafe { std::ptr::write_bytes(at as *mut u8, 9, 4) }; + crate::watch::wrote(at, 4); + assert_eq!(unsafe { data.add(3 * PAGE + 10).read() }, 1, "view {view}: the bytes from before the write"); + // The next refresh takes the write. + batch.add(©, region, LEN); + batch.flush(); + batch.settle_aside(super::ASIDE_OTHER); + held("after the write"); + // Shaders are given the copy: its refresh is done first. + unsafe { std::ptr::write_bytes((region + 6 * PAGE) as *mut u8, 7, 100) }; + batch.add(©, region, LEN); + batch.flush(); + batch.flush_one(©); + assert!(batch.aside.is_none(), "view {view}: waited for by a shader write"); + held("before the shaders"); + // The last flush, as at the end of the steps. + unsafe { std::ptr::write_bytes((region + 7 * PAGE + 1) as *mut u8, 3, 8) }; + batch.add(©, region, LEN); + batch.flush(); + batch.settle_aside(super::ASIDE_OTHER); + held("at the end of the steps"); + batch.give_back(); + } + } + + /// `VICTORY_REFRESH_BESIDE` over many flushes: 48 copies of two pages, + /// title writes between the flushes, some on pages a pass beside is + /// reading, the others not. At every steps' end each copy holds title + /// memory: none stale. + #[test] + fn many_flushes_beside_leave_no_copy_stale() { + const COPIES: usize = 48; + const EACH: usize = 2 * PAGE; + let region = title(COPIES * EACH, false); + // SAFETY (all writes and reads below): the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, COPIES * EACH) }; + let copies: Vec<(Arc, *mut u8)> = (0..COPIES) + .map(|i| { + let data = memory(EACH); + (Shadow::unbacked((region + i * EACH) as u64, data, EACH as u64, false), data) + }) + .collect(); + let mut random = Random(0x5eed_1234_abcd_0001); + let _one = one_submission(); + let mut batch = Batch { aside_forced: true, ..Batch::default() }; + for round in 0..40u8 { + for _ in 0..6 { + // A third of the copies to a flush. + for (i, (copy, _)) in copies.iter().enumerate() { + if random.below(3) == 0 { + batch.add(copy, region + i * EACH, EACH); + } + } + batch.flush(); + for _ in 0..4 { + let at = region + random.below(COPIES * EACH - 64); + batch.title_written_at(at, 64); + unsafe { std::ptr::write_bytes(at as *mut u8, round, 64) }; + crate::watch::wrote(at, 64); + } + } + // The steps' end: all brought up to date, as the last flush does. + for (i, (copy, _)) in copies.iter().enumerate() { + batch.add(copy, region + i * EACH, EACH); + } + batch.flush(); + batch.settle_aside(super::ASIDE_OTHER); + for (i, (_, data)) in copies.iter().enumerate() { + let (title, ours) = unsafe { (std::slice::from_raw_parts((region + i * EACH) as *const u8, EACH), std::slice::from_raw_parts(*data, EACH)) }; + assert!(title == ours, "round {round}: copy {i} stale"); + } + } + batch.give_back(); + } + + #[test] + fn pages_beside_are_merged_and_met() { + let p = PAGE; + let pages = super::pages_of([(5 * p + 1, 6 * p), (p, 2 * p + 1), (2 * p + 5, 3 * p)].into_iter()); + assert_eq!(pages, [(1, 3), (5, 6)]); + assert!(super::pages_touch(&pages, 0, 2)); + assert!(super::pages_touch(&pages, 2, 3)); + assert!(!super::pages_touch(&pages, 3, 5)); + assert!(super::pages_touch(&pages, 5, 9)); + assert!(!super::pages_touch(&pages, 6, 9)); + assert!(!super::pages_touch(&[], 0, 9)); + } + /// A range nothing wrote is known to be as it was, at its ends too, and /// is so no more once something wrote it. #[test] diff --git a/crates/victory-gpu/src/host/early_refresh.rs b/crates/victory-gpu/src/host/early_refresh.rs new file mode 100644 index 0000000000..03d131cef5 --- /dev/null +++ b/crates/victory-gpu/src/host/early_refresh.rs @@ -0,0 +1,696 @@ +//! Refreshes at the title's submit (`VICTORY_REFRESH_AT_SUBMIT=1` or `=2`; off +//! by default; with `VICTORY_ASYNC_SUBMIT` and `VICTORY_THIN`). +//! +//! A submission waits in the line (`crate::queue::behind`) some ten deep +//! before the submitting thread prepares it, and refreshing the host copies +//! its lists read was the largest part of that preparing: 14.7 ms a frame in +//! the world, 41 ms where a new area streams in (`docs/refresh-ahead-study.md`). +//! From the title's submit on, the bytes those lists read are the ones the +//! console's card would read: the title writes nothing a submitted list reads +//! until a fence behind it is reached (`crate::queue::behind`'s text). So a +//! thread of ours, `victory-refresh-ahead`, takes each submission once its +//! lists are translated and brings their copies up to date, up to the first +//! step that writes title memory. The submission still asks and refreshes as +//! before, and finds those pages taken; what was written after this thread's +//! asking is copied again then. With `VICTORY_REFRESH_THREADS=` (2 to 8; +//! 1 by default) the copies of a submission are spread over `n` threads of +//! this module's own ([`spread`]). +//! +//! What it takes: copies that shaders were never said to write, write-watched +//! by the kernel (not guarded views), with no range shaders may be writing +//! (`Shadow::not_ahead`, `Shadow::update_ahead`); on the CPU's side alone with +//! `=1`, and copies in the card's memory too with `=2`. Of those it brings the +//! CPU's side up to date and notes what goes up, as the submission's refresh +//! does; what goes up still goes up from the submission (`Host::card_before`). +//! The rest is left to the submission. What the submitting thread writes into +//! title memory meanwhile (the title's buffer copies, landings) the kernel's +//! dirty bits see, so the submission copies it again: hence not with +//! `VICTORY_SAFE_COPY=0`, where the kernel's own copy writes it. +//! +//! Why the lists are there to read: a submission's host lists are taken out of +//! our lists when the line unfolds it (`behind::Job::unfold`, `crate::list::detach`). +//! The line claims the submission first ([`claim`]): from then on these threads +//! do not touch it, and if they are working on it the line waits until they +//! have stopped (they stop between copies). Until then the recordings, held +//! here, keep our lists, and nobody else changes their host lists. +//! +//! Why a copy is not written under shaders: a copy becomes one shaders write +//! only in `Shadow::gpu_writes`, and gets ranges shaders may be writing only in +//! `Shadow::writing`; both take the copy's `refreshing` lock, as a refresh +//! does. These threads look at the copy again under that lock. + +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::Relaxed}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; + +use super::{ByCopy, Step}; +use crate::list::thin::Recording; +use crate::shadow::{NotAhead, Shadow}; + +type Recordings = Arc<[Arc]>; + +/// 0: off; 1: copies on the CPU's side; 2: and in the card's memory. +fn mode() -> u8 { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| { + let asked = match std::env::var("VICTORY_REFRESH_AT_SUBMIT").ok().as_deref().map(str::trim) { + None | Some("" | "0") => 0, + Some("2") => 2, + Some(_) => 1, + }; + // (Our own copies into title memory made in the CPU, where the kernel's + // dirty bits see them, not by the kernel's copy: `VICTORY_SAFE_COPY=0`.) + let mode = if asked > 0 && crate::watch::light() && crate::safecopy::on() { asked } else { 0 }; + if mode > 0 { + tracing::info!( + mode, + threads = threads(), + "host copies refreshed at the title's submit by threads of ours (VICTORY_REFRESH_AT_SUBMIT: 1 the CPU's side, \ + 2 copies in the card's memory too; VICTORY_REFRESH_THREADS)" + ); + } + mode + }) +} + +/// Whether submissions are refreshed at the title's submit. +pub(crate) fn on() -> bool { + mode() > 0 +} + +/// Whether copies in the card's memory are refreshed too. +fn cards() -> bool { + mode() == 2 +} + +/// Whether the refreshes at the title's submit take guarded view memory too +/// (`VICTORY_REFRESH_GUARDED=1`; off by default). +/// +/// They were left out for a write of ours into title memory there (a title's +/// buffer copy at its preparing, a landing): it opens the block's guards +/// first, and a refresh beside it could guard the block again before the +/// bytes go in. That write is then a fault, which the guards' handler takes +/// first in the process, also inside `crate::safecopy`'s copies (its text): +/// it notes the block written and lets the copy go on, so the submission +/// copies the block again, as for a write of the title's. What is left is the +/// guarded memory's own: some 1,000 of the copies a submission refreshes in +/// play log 20261128-235457, and the two stale copies of play log +/// 20261128-232925 (windows that page mappings changed under). +pub(crate) fn guarded() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on() && crate::switch::on("VICTORY_REFRESH_GUARDED")) +} + +/// Whether the refreshes at the title's submit take windows of title memory +/// outside buffers too (`VICTORY_REFRESH_WINDOWS=1`; off by default). +/// +/// The three copies found stale (`VICTORY_REFRESH_CHECK`) in play logs +/// 20261128-232925 and 20261129-103901 were all such windows, 4 MB at +/// 0x98bc00000 and 0x98cc00000, two of them at 0x98beb0000; the last was +/// write-watched by the kernel and refreshed by a thread of this module. +/// Nothing found so far says why. Left to the submission, the warning's +/// `thread` and `copy_moved`/`title_moved` will say whether they are stale +/// there too (a fault of old) or only when refreshed here. +pub(crate) fn windows() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_REFRESH_WINDOWS")) +} + +/// Whether the walk goes over all of a submission's steps +/// (`VICTORY_REFRESH_WHOLE=1`; off by default: up to the first that writes +/// title memory). +/// +/// Its steps run once the line has claimed it, after these refreshes, and +/// what they write into title memory the kernel's dirty bits, the guards' +/// faults or the journal see (`crate::watch::wrote`, a submission's asking +/// that ends at a step of ours): the submission copies those pages again, +/// with the bytes after the step. At 23:56:40 in play log 20261128-235457 the +/// walk saw some 860 of the 10,273 refreshes a submission did (942 ms). +fn whole() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on() && crate::switch::on("VICTORY_REFRESH_WHOLE")) +} + +/// How many threads refresh a submission's copies (`VICTORY_REFRESH_THREADS`). +fn threads() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_REFRESH_THREADS").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, 8) + }) +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum State { + /// Not begun. + Waiting, + /// These threads are refreshing its copies. + Running, + /// Claimed by the line, or done: left alone from now on. + Done, +} + +/// A submission posted. +struct Entry { + recordings: Recordings, + state: Mutex, + moved: Condvar, + /// The line wants it: stop between copies. + stop: AtomicBool, +} + +/// Submissions posted, oldest first, for the thread. +static POSTED: Mutex>> = Mutex::new(VecDeque::new()); +static MORE: Condvar = Condvar::new(); +/// The same, by their recordings, for [`claim`]. +static BY_LISTS: Mutex>>> = Mutex::new(None); + +/// Since the last frame line: what the counters say ([`line`]). +const POSTS: usize = 0; +const BEGUN: usize = 1; +const LATE: usize = 2; +const STOPPED: usize = 3; +const COPIES: usize = 4; +const BYTES: usize = 5; +/// Microseconds from a submission's start to its end, on the thread that walks it. +const US: usize = 6; +const NOTHING: usize = 7; +const SKIP_WRITTEN: usize = 8; +const SKIP_BUSY: usize = 9; +const SKIP_CARD: usize = 10; +const SKIP_GUARDED: usize = 11; +const SKIP_UNWATCHED: usize = 12; +const SKIP_WINDOW: usize = 18; +/// Of those copied, in the card's memory. +const CARD_COPIES: usize = 13; +/// Microseconds summed over the threads: looking whether anything is new, +/// refreshing, and the longest refresh of one copy. +const US_NOTHING: usize = 14; +const US_UPDATE: usize = 15; +const US_LONGEST: usize = 16; +/// Microseconds walking the lists' steps. +const US_WALK: usize = 17; +static STATS: [AtomicU64; 19] = [const { AtomicU64::new(0) }; 19]; + +fn held(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn key(recordings: &Recordings) -> usize { + Arc::as_ptr(recordings).cast::>() as usize +} + +/// The title submitted `recordings` (in the line from now on). +pub(crate) fn post(recordings: &Recordings) { + if !on() || recordings.is_empty() { + return; + } + let entry = Arc::new(Entry { + recordings: recordings.clone(), + state: Mutex::new(State::Waiting), + moved: Condvar::new(), + stop: AtomicBool::new(false), + }); + held(&BY_LISTS).get_or_insert_with(HashMap::new).insert(key(recordings), entry.clone()); + held(&POSTED).push_back(entry); + STATS[POSTS].fetch_add(1, Relaxed); + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let spawned = std::thread::Builder::new().name("victory-refresh-ahead".into()).spawn(serve); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no thread to refresh at the title's submit"); + } + for i in 1..threads() { + let spawned = std::thread::Builder::new().name(format!("victory-refresh-ahead-{i}")).spawn(help); + if let Err(e) = spawned { + tracing::warn!(error = %e, "a thread less to refresh at the title's submit"); + } + } + }); + MORE.notify_one(); +} + +/// The line is about to take the host lists out of `recordings`: these threads +/// leave them alone from here on, and have stopped if they were at them. +pub(crate) fn claim(recordings: &Recordings) { + if !on() { + return; + } + let Some(entry) = held(&BY_LISTS).as_mut().and_then(|m| m.remove(&key(recordings))) else { + return; + }; + entry.stop.store(true, Relaxed); + let mut state = held(&entry.state); + if *state == State::Waiting { + STATS[LATE].fetch_add(1, Relaxed); + } + while *state == State::Running { + state = entry.moved.wait(state).unwrap_or_else(|e| e.into_inner()); + } + *state = State::Done; +} + +/// What the threads of this module do as a refresh holds a copy's lock. +fn as_ours() { + crate::cores::keep_helper_on_fast_cores("victory-refresh-ahead"); + // Its refreshes hold a copy's lock: never another thread's job meanwhile. + crate::shadow::alone(); +} + +fn serve() { + as_ours(); + loop { + let entry = { + let mut posted = held(&POSTED); + loop { + match posted.pop_front() { + Some(entry) => break entry, + None => posted = MORE.wait(posted).unwrap_or_else(|e| e.into_inner()), + } + } + }; + // Translated first (the line unfolds it only then, so it is not held + // up by this wait). + for recording in entry.recordings.iter() { + if entry.stop.load(Relaxed) { + break; + } + recording.wait(); + } + { + let mut state = held(&entry.state); + if *state != State::Waiting || entry.stop.load(Relaxed) { + continue; + } + *state = State::Running; + } + STATS[BEGUN].fetch_add(1, Relaxed); + let began = std::time::Instant::now(); + refresh(&entry); + STATS[US].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + *held(&entry.state) = State::Done; + entry.moved.notify_all(); + } +} + +/// Refreshes what the submission's lists refresh ahead of their first step +/// that writes title memory. +fn refresh(entry: &Arc) { + let walked = std::time::Instant::now(); + let mut found = Spans::default(); + for recording in entry.recordings.iter() { + // (The reference: the line has not unfolded the submission, as + // `claim` waits for these threads, so our list still holds its host + // list, and the recording keeps our list.) + let Some(list) = crate::list::host_list_held(recording.back()) else { + continue; + }; + if !found.walk(list.deferred().copies.iter(), whole()) { + break; + } + } + STATS[US_WALK].fetch_add(walked.elapsed().as_micros() as u64, Relaxed); + let (cards, stop) = (cards(), &entry.stop); + // (The host lists are not looked at from here on: the spans hold the copies.) + spread(found.spans.len(), |i| { + if stop.load(Relaxed) { + STATS[STOPPED].fetch_add(1, Relaxed); + return false; + } + let (shadow, from, to) = &found.spans[i]; + one(shadow, *from, *to, cards); + true + }); +} + +/// One copy's refresh at the title's submit, counted. +fn one(shadow: &Shadow, from: usize, to: usize, cards: bool) { + if let Some(why) = shadow.not_ahead(cards) { + STATS[match why { + NotAhead::Written => SKIP_WRITTEN, + NotAhead::Card => SKIP_CARD, + NotAhead::Guarded => SKIP_GUARDED, + NotAhead::Unwatched => SKIP_UNWATCHED, + NotAhead::Window => SKIP_WINDOW, + }] + .fetch_add(1, Relaxed); + return; + } + let looked = std::time::Instant::now(); + let same = shadow.nothing_new(from, to - from); + STATS[US_NOTHING].fetch_add(looked.elapsed().as_micros() as u64, Relaxed); + if same { + STATS[NOTHING].fetch_add(1, Relaxed); + return; + } + let began = std::time::Instant::now(); + let done = shadow.update_ahead(from, to - from, cards); + let us = began.elapsed().as_micros() as u64; + STATS[US_UPDATE].fetch_add(us, Relaxed); + STATS[US_LONGEST].fetch_max(us, Relaxed); + match done { + Some(bytes) => { + STATS[COPIES].fetch_add(1, Relaxed); + STATS[BYTES].fetch_add(bytes as u64, Relaxed); + if shadow.carded() { + STATS[CARD_COPIES].fetch_add(1, Relaxed); + } + } + None => { + STATS[SKIP_BUSY].fetch_add(1, Relaxed); + } + } +} + +/// Work for the helpers ([`spread`]): numbers below `n` not taken yet. +struct Shares { + n: usize, + next: AtomicUsize, + /// Helpers at it (the caller waits for none to be). + at: Mutex, + left: Condvar, + /// The caller's: called only by a helper counted in `at`, and the + /// caller returns when none is ([`spread_with`]). + work: *const (dyn Fn(usize) -> bool + Sync + 'static), +} + +// SAFETY: `work` is `Sync` and lives until no helper may call it. +unsafe impl Send for Shares {} +unsafe impl Sync for Shares {} + +impl Shares { + /// Takes numbers until there are none, or `work` says to stop. + fn take(&self) { + loop { + let i = self.next.fetch_add(1, Relaxed); + // SAFETY: see `work`. + if i >= self.n || !unsafe { (*self.work)(i) } { + // (Nobody takes another after a stop.) + self.next.fetch_max(self.n, Relaxed); + return; + } + } + } +} + +/// The shares the helpers are given, and its number (a helper takes each +/// once). +static GIVEN: Mutex<(u64, Option>)> = Mutex::new((0, None)); +static GIVEN_MOVED: Condvar = Condvar::new(); + +/// Runs `work` for each number below `n` on this thread and the helpers +/// (`VICTORY_REFRESH_THREADS`), and returns when all of it is done: none of +/// them is at it any more. `work` says whether to go on. +fn spread(n: usize, work: impl Fn(usize) -> bool + Sync) { + spread_with(threads(), n, work); +} + +/// [`spread`] with `threads` threads in all. +fn spread_with(threads: usize, n: usize, work: impl Fn(usize) -> bool + Sync) { + if threads < 2 || n < 2 { + (0..n).take_while(|&i| work(i)).for_each(drop); + return; + } + let work: &(dyn Fn(usize) -> bool + Sync) = &work; + // SAFETY (of the lifetime): the helpers call `work` only while counted in + // `at`, and this call returns when none is and none can take a number. + let work: *const (dyn Fn(usize) -> bool + Sync + 'static) = unsafe { std::mem::transmute(work as *const (dyn Fn(usize) -> bool + Sync + '_)) }; + let shares = Arc::new(Shares { + n, + next: AtomicUsize::new(0), + at: Mutex::new(0), + left: Condvar::new(), + work, + }); + { + let mut given = held(&GIVEN); + given.0 += 1; + given.1 = Some(shares.clone()); + } + GIVEN_MOVED.notify_all(); + shares.take(); + // No helper takes these shares from here on; then wait for those at them. + held(&GIVEN).1 = None; + let mut at = held(&shares.at); + while *at > 0 { + at = shares.left.wait(at).unwrap_or_else(|e| e.into_inner()); + } +} + +/// A helper of [`spread`]. +fn help() { + as_ours(); + let mut seen = 0; + loop { + let shares = { + let mut given = held(&GIVEN); + loop { + if given.0 != seen + && let Some(shares) = given.1.clone() + { + seen = given.0; + // Counted at under `GIVEN`'s lock, which `spread` takes to + // give it back: it then waits for this helper. + *held(&shares.at) += 1; + break shares; + } + given = GIVEN_MOVED.wait(given).unwrap_or_else(|e| e.into_inner()); + } + }; + shares.take(); + let mut at = held(&shares.at); + *at -= 1; + if *at == 0 { + shares.left.notify_all(); + } + } +} + +/// The refreshes of a submission's steps, per copy the span of them (as +/// `Batch::add` merges them), in the order the copies first come. +#[derive(Default)] +struct Spans { + spans: Vec<(Arc, usize, usize)>, + at: ByCopy, +} + +impl Spans { + /// Adds the refreshes of `steps` up to the first that writes title memory + /// (a copy into it, work of ours, a copy at its place), or all of them + /// with `whole` ([`whole`]): whether the walk goes on to the next list. + fn walk<'a>(&mut self, steps: impl Iterator, whole: bool) -> bool { + for step in steps { + match step { + Step::Refresh(shadow, address, len) => { + let (from, to) = (*address, address + len); + match self.at.get(&(Arc::as_ptr(shadow) as usize)) { + Some(&i) => { + let span = &mut self.spans[i]; + (span.1, span.2) = (span.1.min(from), span.2.max(to)); + } + None => { + self.at.insert(Arc::as_ptr(shadow) as usize, self.spans.len()); + self.spans.push((shadow.clone(), from, to)); + } + } + } + Step::Copy(..) | Step::Run(_) | Step::Placed(_) if !whole => return false, + _ => {} + } + } + true + } +} + +/// For the frame-rate line. +pub(crate) fn line(frames: f64) { + if !on() { + return; + } + let longest = STATS[US_LONGEST].swap(0, Relaxed) as f64 / 1000.0; + let s: [f64; 19] = std::array::from_fn(|i| STATS[i].swap(0, Relaxed) as f64 / frames); + tracing::info!( + "host copies refreshed at the title's submit per frame (VICTORY_REFRESH_AT_SUBMIT={}, {} threads): {:.1} submissions \ + posted, {:.1} begun, {:.1} reached by the line before they were begun, {:.1} stopped by it midway; {:.0} copies \ + refreshed ({:.0} of them in the card's memory), {:.1} MB, {:.1} ms from a submission's start to its end ({:.1} walking \ + its steps; on all threads {:.1} looking whether anything is new, {:.1} refreshing, the longest refresh {:.1} ms); {:.0} \ + found with nothing new; left to the submission: {:.0} written by shaders, {:.0} in the card's memory, {:.0} guarded \ + views, {:.0} not write-watched, {:.0} windows outside buffers (VICTORY_REFRESH_WINDOWS=1 takes them), {:.0} busy or found so under their lock", + mode(), + threads(), + s[POSTS], + s[BEGUN], + s[LATE], + s[STOPPED], + s[COPIES], + s[CARD_COPIES], + s[BYTES] / 1048576.0, + s[US] / 1000.0, + s[US_WALK] / 1000.0, + s[US_NOTHING] / 1000.0, + s[US_UPDATE] / 1000.0, + longest, + s[NOTHING], + s[SKIP_WRITTEN], + s[SKIP_CARD], + s[SKIP_GUARDED], + s[SKIP_UNWATCHED], + s[SKIP_WINDOW], + s[SKIP_BUSY], + ); +} + +#[cfg(test)] +mod tests { + use super::{Spans, Step}; + use crate::shadow::{NotAhead, Shadow}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + + const PAGE: usize = 64 << 10; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// Memory of the test's own (never given back: copies of it stay in the + /// journal), write-watched or not. + fn memory(len: usize, watched: bool) -> *mut u8 { + let flags = MEM_RESERVE | MEM_COMMIT | if watched { MEM_WRITE_WATCH } else { 0 }; + // SAFETY: a plain allocation. + let at: *mut u8 = unsafe { VirtualAlloc(std::ptr::null(), len, flags, PAGE_READWRITE).cast() }; + assert!(!at.is_null()); + at + } + + fn byte(at: *mut u8, i: usize) -> u8 { + // SAFETY: the test's own memory. + unsafe { at.add(i).read_volatile() } + } + + fn write(at: *mut u8, i: usize, v: u8) { + // SAFETY: the test's own memory. + unsafe { at.add(i).write_volatile(v) }; + } + + /// What the title writes after a refresh at its submit is still copied by + /// the submission's own refresh. + #[test] + fn what_is_written_after_a_refresh_at_submit_is_copied_at_the_submission() { + let (len, title) = (4 * PAGE, memory(4 * PAGE, true)); + let copy = Shadow::unbacked(title as u64, memory(len, false), len as u64, false); + let data = copy.card_data().cast_mut(); + // Once by the submission: the copy is known write-watched from then on. + copy.update(title as usize, len); + assert_eq!(copy.not_ahead(false), None); + write(title, PAGE + 7, 5); + assert!(copy.update_ahead(title as usize, len, false).is_some_and(|n| n > 0)); + assert_eq!(byte(data, PAGE + 7), 5, "taken at the title's submit"); + write(title, PAGE + 7, 6); + write(title, 3 * PAGE + 9, 8); + copy.update(title as usize, len); + assert_eq!(byte(data, PAGE + 7), 6, "written again after it: the submission takes it"); + assert_eq!(byte(data, 3 * PAGE + 9), 8); + } + + /// A copy shaders may be writing, one in the card's memory (but with + /// `=2`), or one not write-watched is left to the submission. + #[test] + fn copies_shaders_write_and_card_copies_are_left_to_the_submission() { + let (len, title) = (2 * PAGE, memory(2 * PAGE, true)); + let copy = Shadow::unbacked(title as u64, memory(len, false), len as u64, false); + copy.update(title as usize, len); + copy.writing(title as usize + 64, 64); + write(title, 8, 1); + assert_eq!(copy.update_ahead(title as usize, len, true), None, "a range shaders may be writing"); + + let (len, title) = (2 * PAGE, memory(2 * PAGE, true)); + let card = Shadow::unbacked(title as u64, memory(len, false), len as u64, true); + card.update(title as usize, len); + assert_eq!(card.not_ahead(false), Some(NotAhead::Card)); + assert_eq!(card.update_ahead(title as usize, len, false), None, "in the card's memory"); + + let (len, title) = (PAGE, memory(PAGE, false)); + let plain = Shadow::unbacked(title as u64, memory(len, false), len as u64, false); + plain.update(title as usize, len); + assert_eq!(plain.not_ahead(true), Some(NotAhead::Unwatched)); + } + + /// With `=2` a copy in the card's memory is brought up to date on its CPU + /// side, and what changed is noted to go up from the submission. + #[test] + fn a_card_copy_refreshed_at_submit_notes_what_goes_up() { + let (len, title) = (2 * PAGE, memory(2 * PAGE, true)); + let card = Shadow::unbacked(title as u64, memory(len, false), len as u64, true); + let data = card.card_data().cast_mut(); + card.update(title as usize, len); + card.take_dirty(); + assert_eq!(card.not_ahead(true), None); + write(title, PAGE + 3, 9); + assert!(card.update_ahead(title as usize, len, true).is_some_and(|n| n > 0)); + assert_eq!(byte(data, PAGE + 3), 9); + let dirty = card.take_dirty(); + assert!(dirty.iter().any(|&(a, b)| a <= PAGE + 3 && PAGE + 3 < b), "{dirty:?}"); + } + + /// A snapshot taken for shader writes counts as memory that only serves + /// to compare (other tests may take theirs meanwhile: at least ours). + #[test] + fn a_snapshot_counts_in_the_live_bytes() { + let (len, title) = (3 * PAGE, memory(3 * PAGE, true)); + let copy = Shadow::unbacked(title as u64, memory(len, false), len as u64, false); + copy.update(title as usize, len); + copy.writing(title as usize + 64, 64); + let live = crate::shadow::live_bytes(); + assert!(live.ram_compare >= len as u64, "{live:?}"); + assert!(live.ram >= live.ram_compare && live.copies >= 1, "{live:?}"); + } + + /// The walk takes the refreshes before the first step that writes title + /// memory, merged per copy, and none after it. + #[test] + fn the_walk_ends_at_the_first_step_that_writes_title_memory() { + let copy = |at: usize| Shadow::unbacked(at as u64, memory(PAGE, false), PAGE as u64, false); + let (a, b, c) = (copy(0x10_0000), copy(0x20_0000), copy(0x30_0000)); + let steps = [ + Step::Refresh(a.clone(), 0x10_0100, 16), + Step::Refresh(b.clone(), 0x20_0000, 64), + Step::Refresh(a.clone(), 0x10_0040, 8), + Step::Copy(0x40_0000, 0x50_0000, 4), + Step::Refresh(c.clone(), 0x30_0000, 64), + ]; + let mut found = Spans::default(); + assert!(!found.walk(steps[..].iter(), false), "it ends at the copy"); + let spans: Vec<(*const Shadow, usize, usize)> = found.spans.iter().map(|s| (Arc::as_ptr(&s.0), s.1, s.2)).collect(); + assert_eq!(spans, [(Arc::as_ptr(&a), 0x10_0040, 0x10_0110), (Arc::as_ptr(&b), 0x20_0000, 0x20_0040)]); + let mut all = Spans::default(); + assert!(all.walk(steps[4..].iter(), false), "nothing that writes"); + assert_eq!(all.spans.len(), 1); + // Whole: past the copy, and on to the next list. + let mut whole = Spans::default(); + assert!(whole.walk(steps[..].iter(), true)); + let spans: Vec<*const Shadow> = whole.spans.iter().map(|s| Arc::as_ptr(&s.0)).collect(); + assert_eq!(spans, [Arc::as_ptr(&a), Arc::as_ptr(&b), Arc::as_ptr(&c)]); + } + + /// The helpers and the caller take each number once, none after a stop, + /// and the call returns when all of them are done. + #[test] + fn spread_takes_each_number_once_and_stops() { + for _ in 0..3 { + std::thread::spawn(super::help); + } + for n in [0, 1, 2, 7, 500] { + let seen: Vec = (0..n).map(|_| AtomicUsize::new(0)).collect(); + super::spread_with(4, n, |i| { + seen[i].fetch_add(1, Relaxed); + true + }); + assert!(seen.iter().all(|s| s.load(Relaxed) == 1), "{n}"); + } + let done = AtomicUsize::new(0); + super::spread_with(4, 1000, |i| { + done.fetch_add(1, Relaxed); + i < 10 + }); + // A stop is seen by each thread at its next number at the latest. + assert!(done.load(Relaxed) <= 11 + 4, "{}", done.load(Relaxed)); + } +} diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs index a82eff241a..f50eb650f0 100644 --- a/crates/victory-gpu/src/host/panel.rs +++ b/crates/victory-gpu/src/host/panel.rs @@ -609,6 +609,30 @@ pub(super) struct Notice { done: bool, } +/// Small static label for the startup texture loading screen. +#[derive(Default)] +pub(super) struct LoadingLabel(Option); + +impl LoadingLabel { + pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) { + const TEXT: &str = "LOADING SCENE TEXTURES"; + let shape = Shape { columns: TEXT.len() as u32, lines: 1, graphs: 0 }; + let scale = scale(height); + if self.0.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + self.0 = Buffers::new(host, shape, format, scale); + if let Some(buffers) = &mut self.0 { + buffers.write(&[TEXT.to_owned()], &[]); + } + } + if let Some(buffers) = &mut self.0 { + let (w, h) = size(shape, scale); + list.keep(&buffers.card); + list.keep(&buffers.uploads[buffers.turn].0); + buffers.copy(&list.list, back, (width.saturating_sub(w) / 2, height.saturating_sub(h) / 2), (width, height)); + } + } +} + impl Notice { pub(super) fn new() -> Notice { // The first start of a new victory.exe says first that it restarts by itself (menu.rs). diff --git a/crates/victory-gpu/src/host/startup_textures.rs b/crates/victory-gpu/src/host/startup_textures.rs new file mode 100644 index 0000000000..905e6e3bcf --- /dev/null +++ b/crates/victory-gpu/src/host/startup_textures.rs @@ -0,0 +1,119 @@ +//! Hide the first busy scene while its texture queue is making progress. +//! Real presents continue so the title and sampled-slot readbacks can advance. + +use std::time::{Duration, Instant}; + +const SCENE_DRAWS: u64 = 128; +const READY_DUE: u64 = 128; +const NO_PROGRESS: Duration = Duration::from_secs(3); +const LIMIT: Duration = Duration::from_secs(10); + +#[derive(Default)] +pub(super) struct Loading { + previous_draws: u64, + phase: Phase, +} + +#[derive(Default)] +enum Phase { + #[default] + Waiting, + Holding { + began: Instant, + progressed: Instant, + best_due: u64, + uploads: u64, + }, + Finished, +} + +impl Loading { + pub(super) fn hold(&mut self, video: bool) -> bool { + use std::sync::atomic::Ordering::Relaxed; + if !crate::asked_for!("VICTORY_STARTUP_TEXTURE_WAIT") + || matches!(self.phase, Phase::Finished) + || crate::streamline::framegen_live() + { + return false; + } + self.step( + Instant::now(), + crate::draw::drawn(), + crate::draw::HEAP_TEXTURES_QUEUE[1].load(Relaxed), + crate::draw::HEAP_TEXTURES.load(Relaxed), + video, + ) + } + + fn step(&mut self, now: Instant, drawn: u64, due: u64, uploaded: u64, video: bool) -> bool { + let draws = drawn.saturating_sub(std::mem::replace(&mut self.previous_draws, drawn)); + if video { + return false; + } + match &mut self.phase { + Phase::Waiting if draws >= SCENE_DRAWS => { + if due <= READY_DUE { + self.phase = Phase::Finished; + tracing::info!(due, draws, "startup textures: first scene shown immediately"); + return false; + } + self.phase = Phase::Holding { began: now, progressed: now, best_due: due, uploads: uploaded }; + tracing::info!(due, draws, "startup textures: showing loading screen"); + true + } + Phase::Holding { began, progressed, best_due, uploads } => { + if due < *best_due || uploaded > *uploads { + *progressed = now; + *best_due = (*best_due).min(due); + *uploads = uploaded; + } + let elapsed = now.saturating_duration_since(*began); + let reason = if due <= READY_DUE { + "queue below the startup threshold" + } else if elapsed >= LIMIT { + "maximum wait reached" + } else if now.saturating_duration_since(*progressed) >= NO_PROGRESS { + "texture uploads stopped progressing" + } else { + return true; + }; + tracing::info!(due, waited_ms = elapsed.as_millis() as u64, reason, "startup textures: showing scene"); + self.phase = Phase::Finished; + false + } + _ => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waits_for_scene_textures_then_releases_once() { + let start = Instant::now(); + let mut loading = Loading::default(); + assert!(!loading.step(start, 10, 8_000, 0, false)); + assert!(!loading.step(start, 400, 8_000, 0, true)); + assert!(loading.step(start, 600, 8_000, 0, false)); + assert!(loading.step(start + Duration::from_secs(2), 800, 5_000, 1, false)); + assert!(!loading.step(start + Duration::from_secs(2), 1_000, 100, 2, false)); + assert!(!loading.step(start + Duration::from_secs(2), 1_200, 8_000, 2, false)); + } + + #[test] + fn releases_a_stalled_or_continuously_refilled_queue() { + let start = Instant::now(); + let mut stalled = Loading::default(); + assert!(stalled.step(start, 200, 8_000, 0, false)); + assert!(!stalled.step(start + NO_PROGRESS, 400, 8_000, 0, false)); + + let mut refilled = Loading::default(); + assert!(refilled.step(start, 200, 8_000, 0, false)); + for seconds in 1..10 { + assert!(refilled.step(start + Duration::from_secs(seconds), 200, 8_000, seconds, false)); + } + assert!(!refilled.step(start + LIMIT, 200, 8_000, 10, false)); + } +} diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 5d5673be22..d5690e6c1f 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -115,7 +115,10 @@ pub(crate) mod stat { pub(crate) const HAD_BYTES: usize = 24; /// Jobs. pub(crate) const JOBS: usize = 25; - pub(crate) const COUNT: usize = 26; + /// Of the rest: letting go of what finished submissions held + /// (`crate::host::bury`), on this thread. + pub(crate) const BURY: usize = 26; + pub(crate) const COUNT: usize = 27; } static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT]; @@ -156,7 +159,7 @@ pub(crate) fn log(frames: f64) { looking through copies in the PC's memory {:.2} ms beside them and {:.2} ms more; merging what was fetched {:.2} ms \ ({:.2} ms on all threads, {:.0} jobs), merging the others {:.2} ms ({:.2} on all threads); of the threads' time \ {:.2} ms waiting for the title's bytes going in, {:.2} ms opening or noting guards; then ranges done with {:.2} ms, \ - read-backs and lists {:.2}, the title told {:.2}, the rest {:.2}", + read-backs and lists {:.2}, the title told {:.2}, the rest {:.2} (of it letting go of what finished submissions held {:.2}; VICTORY_BURY_ASIDE=1 does that on a thread of its own)", u8::from(on()), threads(), ms(stat::GATHER), @@ -173,6 +176,7 @@ pub(crate) fn log(frames: f64) { ms(stat::READ_BACKS), ms(stat::TOLD), ms(stat::REST), + ms(stat::BURY), ); tracing::info!( "landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \ diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index b78808abaf..7cb2c31726 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -110,6 +110,8 @@ mod pool; #[cfg(all(windows, feature = "diagnostics"))] mod popwatch; #[cfg(windows)] +pub mod memattrs; +#[cfg(windows)] pub mod procmem; #[cfg(windows)] mod primitive; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 25790e328a..6e57fcd4d2 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -272,7 +272,7 @@ pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { /// ([`crate::indirect::merge`]), and for calls that only change the binding /// ([`with_binding`]). #[cfg(windows)] -fn host_list_held<'a>(this: This) -> Option<&'a crate::host::HostList> { +pub(crate) fn host_list_held<'a>(this: This) -> Option<&'a crate::host::HostList> { if this.is_null() { return None; } diff --git a/crates/victory-gpu/src/memattrs.rs b/crates/victory-gpu/src/memattrs.rs new file mode 100644 index 0000000000..96cda4a846 --- /dev/null +++ b/crates/victory-gpu/src/memattrs.rs @@ -0,0 +1,493 @@ +//! What the title's memory is asked to be, and what the CPU does with it +//! after the GPU first saw it (`VICTORY_MEM_ATTRS=1`; off by default). +//! +//! Every title allocation is served as cacheable CPU read-write memory +//! (`victory-hle`'s `xmem.rs`: the memory-type attributes of `XMemAlloc` +//! and the write-combined/uncached bits of `XMemVirtualAlloc` are dropped), +//! so every block is write-watched, refreshed and held as a host copy alike. +//! Run K (docs/test-results-2026-11-29.md) froze on refresh copies on the +//! submitting thread while the PC paged. A block the CPU never writes after +//! its first upload could skip all three; this measures which attribute +//! classes are such blocks, before anything is skipped. +//! +//! Each allocation the runtime serves paints its address range with a class: +//! the `XMemAlloc`/`XMemAllocDefault` attribute fields (alignment, memory +//! type, page size, 32-bit), or `XMemVirtualAlloc`'s protection (host and +//! `PAGE_GRAPHICS_*` bits), page size and commit state. A later allocation +//! over part of a range (a commit into a reservation, a block of the title's +//! allocator inside its pool) repaints that part; a free clears it. Host +//! copies (`crate::shadow::Shadow`) take the class at their first byte, and +//! their refreshes count under it: the first refresh that copies anything is +//! the first upload, every later one is CPU writes since. +//! +//! The table is logged every five seconds with the memory line, and once at +//! exit: `mem attrs (...)` lines, one per class, largest live first. +//! +//! shortcut: a copy is counted under the class at its start, though a window +//! (4 MiB) can cross several; per-page classes if a mixed window matters. +//! shortcut: a copy's first refresh counts whole as the first upload, so a +//! copy made again over memory the CPU wrote in between hides those writes +//! there (compare "first upload" with "live": far more means copies are +//! remade), and a first refresh of only part of a copy counts the rest's +//! later first copy as CPU writes (the safe side for a skip). + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + +/// Classes kept: 0 is memory no allocation of ours painted, the last one +/// every class past the others. +const CLASSES: usize = 64; +const OTHERS: u8 = CLASSES as u8 - 1; + +/// Set in a key from `XMemVirtualAlloc`. +const VIRTUAL: u64 = 1 << 63; +/// The `XALLOC_ATTRIBUTES` fields kept: page size (2 bits at 14), alignment +/// (log2, 5 bits at 24), memory type (4 bits at 29), 32-bit address (bit 33). +const ALLOC_FIELDS: u64 = 3 << 14 | 0x1f << 24 | 0xf << 29 | 1 << 33; + +/// What is counted per class. +#[derive(Clone, Copy)] +pub(crate) enum Stat { + /// Allocations painted (made since the start). + Calls, + /// Bytes of title memory painted now. + Live, + /// Bytes of host copies alive. + Copies, + /// Bytes copied by copies' first refresh. + First, + /// Bytes copied by later refreshes: the CPU wrote them since. + Later, + /// Bytes refreshed on the submitting thread (first or later). + Submit, +} +const STATS: usize = 6; + +/// Whether the table is kept (`VICTORY_MEM_ATTRS=1`). +pub fn on() -> bool { + crate::asked_for!("VICTORY_MEM_ATTRS") +} + +/// The key of `XMemAlloc` `attributes`: its fields that say what the memory +/// is, without the allocator id and the rest; for Direct3D's allocations +/// (allocator id 128) its object type and id too, which tell a static +/// resource from a dynamic, staging or tiled one (GDKX "Direct3D 12 +/// XMemAlloc object types"). +pub fn alloc_key(attributes: u64) -> u64 { + let d3d = attributes & D3D_ID_MASK == D3D_ID; + attributes & (ALLOC_FIELDS | if d3d { D3D_ID_MASK | 0x3fff } else { 0 }) +} + +/// `XALLOC_ATTRIBUTES.AllocatorId` (8 bits at 16) of Direct3D. +const D3D_ID_MASK: u64 = 0xff << 16; +const D3D_ID: u64 = 128 << 16; + +/// The key of an `XMemVirtualAlloc`: its `protect` as asked, the page size +/// from its `kind` (2 MiB, 64 KiB, else 4 KiB), whether it commits (else a +/// placeholder with 64 KiB pages, else a reservation), and 32-bit. +pub fn virtual_key(protect: u32, pages_2m: bool, pages_64k: bool, committed: bool, low: bool) -> u64 { + let pages = if pages_64k { 2 } else { u64::from(pages_2m) }; + let state = if committed { 0 } else if pages_64k { 2 } else { 1 }; + VIRTUAL | u64::from(low) << 44 | state << 42 | pages << 40 | u64::from(protect) +} + +/// The title's `VirtualProtect` set `protect` on `[at, at + len)`. Pages mapped +/// by `XMemMapPhysicalPages` take their reservation's protection (GDKX docs), +/// and a test at 77427629 (PR #2334) found 71 % of host copies under a +/// `PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS` placeholder: what the title asks of +/// such memory shows here. +pub fn protected(at: usize, len: usize, protect: u32) { + allocated(at, len, VIRTUAL | 3 << 42 | 3 << 40 | u64::from(protect)); +} + +/// A key as words. +pub(crate) fn describe(key: u64) -> String { + if key & VIRTUAL == 0 { + // XALLOC_MEMTYPE 0x0-0xC and XALLOC_PAGESIZE 0-2 (GDKX `xalloc_attributes`). + const TYPES: [&str; 13] = [ + "heap cacheable", + "graphics write-combined", + "graphics write-combined GPU read-only", + "graphics cacheable", + "graphics cacheable noncoherent GPU read-only", + "command buffer write-combined", + "command buffer cacheable", + "physical cacheable", + "physical write-combined", + "physical uncached", + "graphics GPU uncached", + "graphics shader noncoherent", + "graphics executable write-combined", + ]; + // Direct3D's GPU object types 0-24 (GDKX "Direct3D 12 XMemAlloc object types"). + const OBJECTS: [&str; 25] = [ + "unspecified", + "command buffer", + "writeback", + "ring temporary", + "resource", + "dynamic resource", + "staging resource", + "multimedia local", + "multimedia local pinned", + "multimedia local CPU access", + "multimedia local CPU access pinned", + "multimedia staging", + "multimedia staging pinned", + "multimedia invisible", + "multimedia invisible pinned", + "shader", + "page directory entries", + "page table entries", + "unmap info", + "presentable", + "cached garlic resource", + "system heap", + "tiled resource", + "low 4 GB cached coherent", + "low 4 GB write-combined", + ]; + let kind = (key >> 29 & 0xf) as usize; + let object = (key & 0x3fff) as usize; + let d3d = if key & D3D_ID_MASK == D3D_ID { + format!(" D3D object {object} ({})", OBJECTS.get(object).unwrap_or(&"CPU object")) + } else { + String::new() + }; + return format!( + "XMemAlloc type {kind} ({}) page {} align {}{}{d3d}", + TYPES.get(kind).unwrap_or(&"?"), + ["4K", "64K", "2M", "?"][(key >> 14 & 3) as usize], + 1u64 << (key >> 24 & 0x1f), + if key & 1 << 33 != 0 { " 32-bit" } else { "" } + ); + } + let protect = key as u32; + format!( + "XMemVirtualAlloc protect {protect:#x} (host {:#x}{}{}{}, graphics {:#x}) pages {} {}{}", + protect & 0xff, + if protect & 0x100 != 0 { " guard" } else { "" }, + if protect & 0x200 != 0 { " nocache" } else { "" }, + if protect & 0x400 != 0 { " writecombine" } else { "" }, + protect & !0x7ff, + ["4K", "2M", "64K", "as before"][(key >> 40 & 3) as usize], + ["committed", "reserved", "placeholder", "set by VirtualProtect"][(key >> 42 & 3) as usize], + if key >> 44 & 1 != 0 { " 32-bit" } else { "" } + ) +} + +#[derive(Default)] +struct Map { + /// Painted ranges: start to (end, class); none overlap. + ranges: BTreeMap, + /// The key of class `i + 1`. + keys: Vec, +} + +pub(crate) struct Table { + map: Mutex>, + stats: [[AtomicU64; STATS]; CLASSES], +} + +impl Table { + const fn new() -> Table { + Table { map: Mutex::new(None), stats: [const { [const { AtomicU64::new(0) }; STATS] }; CLASSES] } + } + + fn add(&self, class: u8, stat: Stat, n: u64) { + self.stats[class as usize][stat as usize].fetch_add(n, Relaxed); + } + + fn sub(&self, class: u8, stat: Stat, n: u64) { + let _ = self.stats[class as usize][stat as usize].fetch_update(Relaxed, Relaxed, |v| Some(v.saturating_sub(n))); + } + + #[cfg(test)] + fn get(&self, class: u8, stat: Stat) -> u64 { + self.stats[class as usize][stat as usize].load(Relaxed) + } + + /// Clears `[at, end)` of paint, keeping what lies around it. + fn erase(&self, map: &mut Map, at: usize, end: usize) { + let hit: Vec<(usize, usize, u8)> = + map.ranges.range(..end).rev().take_while(|(_, (e, _))| *e > at).map(|(&s, &(e, c))| (s, e, c)).collect(); + for (s, e, c) in hit { + map.ranges.remove(&s); + self.sub(c, Stat::Live, (e.min(end) - s.max(at)) as u64); + if s < at { + map.ranges.insert(s, (at, c)); + } + if e > end { + map.ranges.insert(end, (e, c)); + } + } + } + + /// An allocation of `[at, at + len)` with `key`. The same range painted + /// again (a hook's block from `XMemAllocDefault`, an `XMemAllocDefault` + /// block from `XMemVirtualAlloc`) is one allocation, of the last key. + pub(crate) fn allocated(&self, at: usize, len: usize, key: u64) { + if len == 0 { + return; + } + let end = at.saturating_add(len); + let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(Map::default); + let class = match map.keys.iter().position(|&k| k == key) { + Some(i) => i as u8 + 1, + None if map.keys.len() + 1 < OTHERS as usize => { + map.keys.push(key); + map.keys.len() as u8 + } + None => OTHERS, + }; + if let Some(&(e, c)) = map.ranges.get(&at) + && e == end + { + self.sub(c, Stat::Calls, 1); + } + self.erase(map, at, end); + map.ranges.insert(at, (end, class)); + self.add(class, Stat::Live, len as u64); + self.add(class, Stat::Calls, 1); + } + + /// A refresh of a copy of `class` copied `n` bytes; `uploaded` is the + /// copy's own flag of a refresh that copied something before. + fn refreshed(&self, class: u8, uploaded: &AtomicBool, n: usize) { + if n != 0 { + let first = !uploaded.swap(true, Relaxed); + self.add(class, if first { Stat::First } else { Stat::Later }, n as u64); + } + } + + pub(crate) fn freed(&self, at: usize, len: usize) { + let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + self.erase(map, at, at.saturating_add(len)); + } + } + + /// The block painted from `at` on, whatever its length, is freed. + fn freed_block(&self, at: usize) { + let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() + && let Some(&(end, _)) = map.ranges.get(&at) + { + self.erase(map, at, end); + } + } + + pub(crate) fn class_at(&self, at: usize) -> u8 { + let map = self.map.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref() + .and_then(|m| m.ranges.range(..=at).next_back()) + .filter(|(_, (e, _))| *e > at) + .map_or(0, |(_, &(_, c))| c) + } + + /// The table's rows: class, its words, its counts; largest live first, + /// classes that never counted anything left out. + pub(crate) fn rows(&self) -> Vec<(u8, String, [u64; STATS])> { + let keys = self.map.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|m| m.keys.clone()).unwrap_or_default(); + let mut rows: Vec<_> = (0..CLASSES as u8) + .map(|c| { + let stats = self.stats[c as usize].each_ref().map(|s| s.load(Relaxed)); + let words = match c { + 0 => "not allocated through XMem (no class)".to_owned(), + OTHERS => "every class past the 62nd".to_owned(), + c => keys.get(c as usize - 1).map_or_else(String::new, |&k| describe(k)), + }; + (c, words, stats) + }) + .filter(|(_, _, s)| s.iter().any(|&n| n != 0)) + .collect(); + rows.sort_by_key(|r| std::cmp::Reverse(r.2[Stat::Live as usize])); + rows + } +} + +static TABLE: Table = Table::new(); + +/// The runtime gave the title `[at, at + len)` as `key` says. +pub fn allocated(at: usize, len: usize, key: u64) { + if on() { + TABLE.allocated(at, len, key); + } +} + +/// `[at, at + len)` is the title's no more. +pub fn freed(at: usize, len: usize) { + if on() { + TABLE.freed(at, len); + } +} + +/// A block of the title's allocator (`XMemFree`, which gives no length) is +/// freed: the range painted from `at` is cleared. +/// +/// shortcut: a block the title's own allocator cut from its pool leaves a +/// hole of no class in the pool once freed; repaint the pool's class if +/// such holes count. +pub fn freed_block(at: usize) { + if on() { + TABLE.freed_block(at); + } +} + +/// A host copy of `len` bytes from `start` was made: its class (0 when off). +pub(crate) fn copy_made(start: usize, len: u64) -> u8 { + if !on() { + return 0; + } + let class = TABLE.class_at(start); + TABLE.add(class, Stat::Copies, len); + class +} + +/// A host copy [`copy_made`] counted is gone. +pub(crate) fn copy_gone(class: u8, len: u64) { + if on() { + TABLE.sub(class, Stat::Copies, len); + } +} + +/// See [`Table::refreshed`]. +pub(crate) fn refreshed(class: u8, uploaded: &AtomicBool, n: usize) { + if on() { + TABLE.refreshed(class, uploaded, n); + } +} + +/// The submitting thread refreshed `n` bytes of a copy of `class`. +pub(crate) fn submitted(class: u8, n: usize) { + if n != 0 && on() { + TABLE.add(class, Stat::Submit, n as u64); + } +} + +fn log(when: &str) { + let mb = |b: u64| b as f64 / (1 << 20) as f64; + for (class, words, s) in TABLE.rows() { + tracing::info!( + "mem attrs ({when}): class {class} {words}: calls {}, live {:.1} MB, host copies {:.1} MB, first upload {:.1} MB, \ + CPU-written after upload {:.1} MB, refreshed on the submitting thread {:.1} MB", + s[Stat::Calls as usize], + mb(s[Stat::Live as usize]), + mb(s[Stat::Copies as usize]), + mb(s[Stat::First as usize]), + mb(s[Stat::Later as usize]), + mb(s[Stat::Submit as usize]), + ); + } +} + +/// With the five-second memory line. +pub(crate) fn line() { + if on() { + log("5s"); + } +} + +/// Once, as the process ends. +pub fn log_at_exit() { + static ONCE: std::sync::Once = std::sync::Once::new(); + if on() { + ONCE.call_once(|| log("exit")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_keep_the_attribute_fields_and_say_them() { + // Alignment 2^16, memory type 3, 2 MiB pages, 32-bit, and an allocator id in the low bits. + let attributes = 16 << 24 | 3 << 29 | 2 << 14 | 1 << 33 | 0x7f; + let key = alloc_key(attributes); + assert_eq!(key, attributes & !0x7f); + assert_eq!(describe(key), "XMemAlloc type 3 (graphics cacheable) page 2M align 65536 32-bit"); + assert_eq!(describe(alloc_key(0)), "XMemAlloc type 0 (heap cacheable) page 4K align 1"); + assert_eq!( + describe(alloc_key(2 << 29 | 1 << 14)), + "XMemAlloc type 2 (graphics write-combined GPU read-only) page 64K align 1" + ); + + let wc_gpu_ro = 0x04 | 0x400 | 0x1000; + let v = virtual_key(wc_gpu_ro, false, true, false, false); + assert_ne!(v, alloc_key(u64::MAX), "the two kinds never share a key"); + assert_eq!( + describe(v), + "XMemVirtualAlloc protect 0x1404 (host 0x4 writecombine, graphics 0x1000) pages 64K placeholder" + ); + assert_eq!( + describe(virtual_key(0x204, true, false, true, true)), + "XMemVirtualAlloc protect 0x204 (host 0x4 nocache, graphics 0x0) pages 2M committed 32-bit" + ); + assert_ne!(virtual_key(4, false, false, true, false), virtual_key(4, false, false, false, false)); + } + + /// Direct3D's allocations keep their object type, others do not. + #[test] + fn d3d_allocations_keep_their_object_type() { + let dynamic = 128 << 16 | 5 | 1 << 29; + assert_eq!(alloc_key(dynamic), dynamic); + assert_eq!(describe(alloc_key(dynamic)), "XMemAlloc type 1 (graphics write-combined) page 4K align 1 D3D object 5 (dynamic resource)"); + assert_ne!(alloc_key(dynamic), alloc_key(128 << 16 | 4 | 1 << 29), "static and dynamic resources apart"); + assert_eq!(alloc_key(7 << 16 | 5 | 1 << 29), 1 << 29, "another allocator: no object type"); + } + + /// `VirtualProtect` over part of a placeholder moves those bytes to a + /// class of their own, said as such. + #[test] + fn a_protection_set_later_repaints_its_range() { + let t = Table::new(); + t.allocated(0x100000, 0x40000, virtual_key(0x801, false, true, false, false)); + let placeholder = t.class_at(0x100000); + let key = VIRTUAL | 3 << 42 | 3 << 40 | 0x2004; + t.allocated(0x110000, 0x10000, key); + let set = t.class_at(0x110000); + assert_ne!(set, placeholder); + assert_eq!((t.get(placeholder, Stat::Live), t.get(set, Stat::Live)), (0x30000, 0x10000)); + assert_eq!(describe(key), "XMemVirtualAlloc protect 0x2004 (host 0x4, graphics 0x2000) pages as before set by VirtualProtect"); + } + + #[test] + fn paint_accumulates_by_class() { + let t = Table::new(); + let (reserve, commit, block) = (virtual_key(1, false, false, false, false), virtual_key(4, false, false, true, false), alloc_key(2 << 29)); + t.allocated(0x10000, 0x10000, reserve); + t.allocated(0x14000, 0x4000, commit); + let (r, c) = (t.class_at(0x10000), t.class_at(0x14000)); + assert_ne!(r, c); + assert_eq!(t.class_at(0x18000), r, "the reservation goes on past the commit"); + assert_eq!(t.class_at(0x20000), 0, "past the end"); + assert_eq!((t.get(r, Stat::Live), t.get(c, Stat::Live)), (0xc000, 0x4000)); + + // The same range again with another key: one allocation, re-keyed. + t.allocated(0x14000, 0x4000, block); + let b = t.class_at(0x14000); + assert_eq!((t.get(c, Stat::Calls), t.get(c, Stat::Live)), (0, 0)); + assert_eq!((t.get(b, Stat::Calls), t.get(b, Stat::Live)), (1, 0x4000)); + + // Refreshes: the first is the upload, the rest CPU writes. + let uploaded = AtomicBool::new(false); + for n in [0, 0x4000, 0x1000] { + t.refreshed(b, &uploaded, n); + } + assert_eq!((t.get(b, Stat::First), t.get(b, Stat::Later)), (0x4000, 0x1000)); + + // A free of part of the reservation, then of all of it. + t.freed(0x10000, 0x2000); + assert_eq!(t.get(r, Stat::Live), 0xa000); + assert_eq!(t.class_at(0x11000), 0); + t.freed_block(0x14000); + assert_eq!(t.get(b, Stat::Live), 0); + t.freed(0x10000, 0x10000); + assert_eq!((t.get(r, Stat::Live), t.get(b, Stat::Live)), (0, 0)); + let rows = t.rows(); + assert!(rows.iter().any(|row| row.0 == b && row.2[Stat::Later as usize] == 0x1000), "counts outlive the memory"); + } +} diff --git a/crates/victory-gpu/src/memguard.rs b/crates/victory-gpu/src/memguard.rs index 4fcca52578..aa0bda1296 100644 --- a/crates/victory-gpu/src/memguard.rs +++ b/crates/victory-gpu/src/memguard.rs @@ -157,16 +157,11 @@ pub(crate) fn take_deferred() -> bool { /// Whether a compile on this thread was refused since [`take_deferred`] /// (looked at, not taken). +#[cfg(test)] pub(crate) fn deferred() -> bool { DEFERRED.get() } -/// The error a refused compile gives: what the driver itself gives when it -/// finds no memory. -pub(crate) fn refusal() -> windows::core::Error { - windows::core::Error::from(windows::Win32::Foundation::E_OUTOFMEMORY) -} - #[cfg(test)] mod tests { use super::{Figures, Floors, Verdict, decide, floors_of}; @@ -236,4 +231,4 @@ mod tests { assert!(super::take_deferred(), "refused: told"); assert!(!super::take_deferred(), "and taken"); } -} \ No newline at end of file +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index fd41ce0f85..cc5f5067f3 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -604,6 +604,15 @@ pub(crate) fn presented() { make::presented(); } +/// Why [`host_pipeline`] gave nothing for `this` (one of `draw::WHY_*`). +#[cfg(windows)] +pub(crate) fn why_no_host(this: This) -> u8 { + if this.is_null() { + return crate::draw::WHY_NULL; + } + make::why(&pipeline(this).host) +} + /// Host pipelines queued and not made yet. #[cfg(windows)] pub(crate) fn making() -> u64 { diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 4419b6e431..2ec5551332 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -15,6 +15,7 @@ use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::core::PCSTR; +use super::library::BuildError; use super::{Shader, Translated}; use crate::host::host; @@ -686,11 +687,12 @@ impl HostPipeline { ); let pso = match made { Ok(pso) => pso, - Err(e) => { + Err(BuildError::Deferred) => return None, + Err(BuildError::Driver(e)) => { let dxils: Vec<&[u8]> = stages.iter().filter_map(|(s, _)| s.translated()).map(|t| t.host.dxil.as_slice()).collect(); super::refused::failed("compute", shaders, &e, &dxils); // SAFETY: as above. - super::refused::retry(shaders, &dxils, || unsafe { host.device.CreateComputePipelineState(&desc) })? + super::refused::retry(&name, shaders, &dxils, || unsafe { host.device.CreateComputePipelineState(&desc) })? } }; tracing::info!(?shaders, "host pipeline"); @@ -771,7 +773,8 @@ impl HostPipeline { ); let pso = match mesh_pipeline(&host.device, &root, ms, ps, g, depth_bounds, &name) { Ok(pso) => pso, - Err(e) => { + Err(BuildError::Deferred) => return None, + Err(BuildError::Driver(e)) => { let dxils: Vec<&[u8]> = stages.iter().filter_map(|(s, _)| s.translated()).map(|t| t.host.dxil.as_slice()).collect(); super::refused::failed("mesh", shaders, &e, &dxils); return None; @@ -840,7 +843,7 @@ impl HostPipeline { }; // A pipeline with the geometry stage has a name of its own in the // library; the others keep theirs. - let name = |gs: Option<&Vec>| match gs { + let pipeline_name = |gs: Option<&Vec>| match gs { Some(gs) => super::library::name( "graphics rectangles", &root_blob, @@ -866,25 +869,28 @@ impl HostPipeline { || unsafe { host.device.CreateGraphicsPipelineState(desc) }, ) }; - let mut made = make(&desc, &name(rect_gs.as_ref())); - if made.is_err() && rect_gs.is_some() && !crate::memguard::deferred() { + let mut name = pipeline_name(rect_gs.as_ref()); + let mut made = make(&desc, &name); + if matches!(&made, Err(BuildError::Driver(_))) && rect_gs.is_some() { // The host refused the geometry stage: once more without it. tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); host.log_messages(); desc.GS = D3D12_SHADER_BYTECODE::default(); rect_gs = None; - made = make(&desc, &name(None)); + name = pipeline_name(None); + made = make(&desc, &name); } let pso = match made { Ok(pso) => pso, - Err(e) => { + Err(BuildError::Deferred) => return None, + Err(BuildError::Driver(e)) => { let dxils: Vec<&[u8]> = stages.iter().filter_map(|(s, _)| s.translated()).map(|t| t.host.dxil.as_slice()).collect(); super::refused::failed("graphics", shaders, &e, &dxils); if depth_bounds { return None; } // SAFETY: as above. - super::refused::retry(shaders, &dxils, || unsafe { host.device.CreateGraphicsPipelineState(&desc) })? + super::refused::retry(&name, shaders, &dxils, || unsafe { host.device.CreateGraphicsPipelineState(&desc) })? } }; tracing::info!(?shaders, "host pipeline"); @@ -949,7 +955,7 @@ fn stream_pipeline( device: &ID3D12Device, stream: &mut S, name: &str, -) -> windows::core::Result { +) -> Result { use windows::core::Interface; let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), @@ -974,7 +980,7 @@ fn graphics_depth_bounds_pipeline( d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth: D3D12_DEPTH_STENCIL_DESC1, name: &str, -) -> windows::core::Result { +) -> Result { use windows::core::Interface; #[repr(C)] struct Stream { @@ -1047,7 +1053,7 @@ fn mesh_pipeline( g: &GraphicsState, depth_bounds: bool, name: &str, -) -> windows::core::Result { +) -> Result { use windows::core::Interface; #[repr(C)] struct Stream { diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 8792742c9b..31d0f3dccb 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -814,13 +814,27 @@ fn never_load() -> bool { *ON.get_or_init(|| std::env::var("VICTORY_LIBRARY_LOADS").is_ok_and(|v| v.trim() == "never")) } +/// The maker retries a deferred build later. A driver error is a completed +/// attempt, even if its HRESULT also indicates a shortage of memory. +#[derive(Debug)] +pub(crate) enum BuildError { + Deferred, + Driver(windows::core::Error), +} + +impl From for BuildError { + fn from(error: windows::core::Error) -> Self { + Self::Driver(error) + } +} + /// The pipeline named `name`: loaded from the library by `load` if it is /// there with the same description, else made by `create` and stored. pub(crate) fn pipeline( name: &str, load: impl Fn(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result, create: impl FnOnce() -> windows::core::Result, -) -> windows::core::Result { +) -> Result { let wide = HSTRING::from(name); let Some(library) = library().filter(|_| !STATIC_SAMPLERS.get()) else { // The driver's compiler takes gigabytes for a big program, and where @@ -828,10 +842,10 @@ pub(crate) fn pipeline( // short (`crate::compilemem`); the maker is told, and makes the // pipeline again later. let Some(_permit) = crate::compilemem::begin(name) else { - return Err(crate::memguard::refusal()); + return Err(BuildError::Deferred); }; MADE.fetch_add(1, Ordering::Relaxed); - return create(); + return create().map_err(BuildError::Driver); }; let began = std::time::Instant::now(); let (loaded, named, held, during_save) = if never_load() { @@ -890,7 +904,7 @@ pub(crate) fn pipeline( // Compiled outside any lock: compiles take up to seconds. let pso = { let Some(_permit) = crate::compilemem::begin(name) else { - return Err(crate::memguard::refusal()); + return Err(BuildError::Deferred); }; let _call = call("make", name); create()? diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index ef3117d9ce..a0573d5e53 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -492,6 +492,20 @@ pub(crate) fn missing(p: &Pending) -> Option { } } +/// Why `p` has no host pipeline (one of `draw::WHY_*`): left out, still +/// being made, a shader that does not translate, or refused by the host. +pub(crate) fn why(p: &Pending) -> u8 { + use crate::draw::{WHY_LEFT_OUT, WHY_MAKING, WHY_REFUSED, WHY_UNTRANSLATED}; + if p.left_out.is_some() { + return WHY_LEFT_OUT; + } + match p.made.get() { + None => WHY_MAKING, + Some(_) if p.shaders.iter().any(|s| matches!(s.translated.get(), Some(None))) => WHY_UNTRANSLATED, + Some(_) => WHY_REFUSED, + } +} + /// The hashes of the shaders `p` is made of. pub(crate) fn hashes(p: &Pending) -> String { let hashes: Vec<&str> = p.shaders.iter().map(|s| s.hash.as_str()).collect(); diff --git a/crates/victory-gpu/src/pipeline/refused.rs b/crates/victory-gpu/src/pipeline/refused.rs index 1622e6192e..2284cf0b43 100644 --- a/crates/victory-gpu/src/pipeline/refused.rs +++ b/crates/victory-gpu/src/pipeline/refused.rs @@ -250,6 +250,8 @@ pub(crate) fn failed( first }); if first { + let memory = (error.code() == windows::Win32::Foundation::E_OUTOFMEMORY) + .then(crate::memguard::figures_now).flatten(); tracing::warn!( key, stage, @@ -257,6 +259,8 @@ pub(crate) fn failed( removed = removed.map(|r| format!("{r:#010x}")), messages, lacks = lacks.join(", "), + free_physical_mib = memory.map(|m| m.free_physical >> 20), + free_commit_mib = memory.map(|m| m.free_commit >> 20), reason, error = %error, "host pipeline failed (logged once per key)" @@ -280,6 +284,7 @@ fn retried(shaders: &[std::sync::Arc], made: &windows::core::Result], code: &[&[u8]], create: impl FnOnce() -> windows::core::Result, @@ -287,6 +292,7 @@ pub(crate) fn retry( if !retry_on() || !lacks(code).is_empty() { return None; } + let _permit = crate::compilemem::begin(name)?; let made = create(); retried(shaders, &made); made.ok() diff --git a/crates/victory-gpu/src/procmem.rs b/crates/victory-gpu/src/procmem.rs index 1821a89f25..e753531050 100644 --- a/crates/victory-gpu/src/procmem.rs +++ b/crates/victory-gpu/src/procmem.rs @@ -1,5 +1,6 @@ -//! What holds the process's memory, said in the log every five seconds, in -//! every build. +//! What holds the process's memory, logged in every build. The system +//! counters are sampled every five seconds. On small hosts under memory +//! pressure, the full address-space walk runs at most every fifteen seconds. //! //! `copystat`'s memory lines (diagnostics builds) sort the process's memory //! by what the layer's own counters say. This looks at the address space @@ -197,16 +198,28 @@ fn on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_PROCESS_MEMORY").is_none_or(|v| v != "0")) } +fn census_due(last: Option, now: u64, memory_tight: bool) -> bool { + !memory_tight || last.is_none_or(|last| now.saturating_sub(last) >= 15_000) +} + /// Starts the line on a thread of its own; called with the frame-rate /// line's five-second part. A walk still running when the next is due is /// not doubled. pub(crate) fn line() { static WALKING: AtomicBool = AtomicBool::new(false); - if !on() || WALKING.swap(true, Relaxed) { + static LAST_CENSUS: AtomicU64 = AtomicU64::new(u64::MAX); + if !tracing::event_enabled!(tracing::Level::INFO) || !on() || WALKING.swap(true, Relaxed) { return; } let started = std::thread::Builder::new().name("victory-process-memory".into()).spawn(|| { - log(); + let last = LAST_CENSUS.load(Relaxed); + let now = crate::host::now_ms(); + let memory_tight = crate::residency::small_host_ram() && crate::residency::pressured(); + if census_due((last != u64::MAX).then_some(last), now, memory_tight) { + LAST_CENSUS.store(now, Relaxed); + log(); + } + log_beside(); WALKING.store(false, Relaxed); }); if started.is_err() { @@ -232,7 +245,13 @@ fn log() { let mapped_other = census.mapped[1].saturating_sub(library); // Ours, in the process's own commit. The texture staging and the upload // buffers are the card driver's (system memory it shares with the card). - let ours = shader_bytes + translated_bytes + copies[1] + heap[1]; + // Lazy CPU mirrors (`VICTORY_CARD_CPU_LAZY`) are counted whole with the + // copies: only their committed part is commit. + let lazy = [ + crate::shadow::lazy_mirror::RESERVED.load(Relaxed), + crate::shadow::lazy_mirror::COMMITTED.load(Relaxed), + ]; + let ours = shader_bytes + translated_bytes + copies[1].saturating_sub(lazy[0].saturating_sub(lazy[1])) + heap[1]; let found = census.private[0] + census.mapped[0] + ours; let seen = census.private[0] + census.private[1] + census.mapped[0] + mapped_other; let heaps = if std::env::var_os("VICTORY_PROCESS_HEAPS").is_some_and(|v| v != "0") { @@ -258,7 +277,7 @@ fn log() { reserved), at host addresses {} MB private (the layer's heap, stacks, the driver) and {} MB mapped (without the \ pipeline library's file, {} MB), images {} MB; the PC has {} MB free | held by us, in the process: shader \ containers {} ({} MB), translated shaders {} ({} MB host code), host copies of title memory {} ({} MB), XMem \ - heap blocks {} ({} MB); the pipeline library file {} MB, last save {} MB, {} MB let go from memory | in the \ + heap blocks {} ({} MB), lazy CPU mirrors {} MB reserved and {} MB committed; the pipeline library file {} MB, last save {} MB, {} MB let go from memory | in the \ PC's memory shared with the card: staging of textures {} MB, upload buffers held by lists {} ({} MB) | named \ {} MB, unnamed {} MB of the private bytes; largest at host addresses: {}{heaps}", mb(private), @@ -283,6 +302,8 @@ fn log() { mb(copies[1]), heap[0], mb(heap[1]), + mb(lazy[0]), + mb(lazy[1]), mb(library), mb(saved), mb(trimmed), @@ -295,10 +316,106 @@ fn log() { ); } +/// What the title asked of `XMemVirtualAlloc` since the start, in bytes: +/// committed (at once, or into a reservation), placeholders (64 KiB page +/// reservations its physical pages are mapped into later: no commit of +/// their own) and other reservations. Its frees go to Windows without us, +/// so these only grow. (Run 2026-11-29 11:08: 16,594 MB in 256 calls and +/// 16,384 MB in one were placeholders; some 2.7 GB was committed at once.) +static TITLE_VIRTUAL: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// `XMemVirtualAlloc` gave the title `size` bytes: committed, or a +/// placeholder reservation, or another reservation. +pub fn title_virtual_asked(committed: bool, placeholder: bool, size: u64) { + let kind = if committed { + 0 + } else if placeholder { + 1 + } else { + 2 + }; + TITLE_VIRTUAL[kind].fetch_add(size, Relaxed); +} + +/// Page faults a second from two readings of the process's count +/// (`(ms, count)`), 0 without an earlier one. +fn faults_per_second(before: Option<(u64, u32)>, now: (u64, u32)) -> u64 { + match before { + Some((ms, count)) if now.0 > ms => u64::from(now.1.wrapping_sub(count)) * 1000 / (now.0 - ms), + _ => 0, + } +} + +/// Beside the census: what the system says of the process and the PC, and +/// the card's two memory groups. D3D12 resources count in the private bytes +/// wherever they are (run 2026-11-29 11:08: 18 GB private with the card's +/// memory and the PC's memory it uses in it), and the title's physical pages +/// are sections, in the PC's commit but not in the private bytes. +fn log_beside() { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, PROCESS_MEMORY_COUNTERS, + PROCESS_MEMORY_COUNTERS_EX2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut c = PROCESS_MEMORY_COUNTERS_EX2 { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure, which the call reads `cb` of. + if unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), (&raw mut c).cast::(), c.cb) } == 0 { + return; + } + let mut p = PERFORMANCE_INFORMATION { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: a sized structure. + let pc = unsafe { K32GetPerformanceInfo(&mut p, p.cb) } != 0; + let pages = |n: usize| if pc { (n as u64 * p.PageSize as u64) >> 20 } else { 0 }; + let now = (crate::host::now_ms(), c.PageFaultCount); + let faults = faults_per_second(LAST.lock().unwrap_or_else(|e| e.into_inner()).replace(now), now); + let card = crate::host::host().and_then(|h| h.video_memory()).unwrap_or_default(); + let asked = TITLE_VIRTUAL.each_ref().map(|v| v.load(Relaxed) >> 20); + // `crate::shadow::live_bytes()` (host copies' RAM, of it what only compares, their card sides) + // has its own line, "host copies of title memory now"; `live_copies` is in the line above. + tracing::info!( + "process memory beside the census: {} MB of sections shared (the title's physical pages among them), \ + {} MB of the working set private, {faults} page faults a second (soft and hard); the PC: {} of {} MB \ + committed, {} of {} MB of physical memory free; the card's memory in use {} MB and the PC's memory \ + the card uses {} MB (both in the private bytes); the title asked since the start {} MB committed, {} MB \ + of placeholders, {} MB reserved", + c.SharedCommitUsage >> 20, + c.PrivateWorkingSetSize >> 20, + pages(p.CommitTotal), + pages(p.CommitLimit), + pages(p.PhysicalAvailable), + pages(p.PhysicalTotal), + card[1] >> 20, + card[3] >> 20, + asked[0], + asked[1], + asked[2], + ); +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn only_a_small_host_under_pressure_limits_the_memory_census() { + assert!(census_due(None, 5_000, true)); + assert!(!census_due(Some(5_000), 10_000, true)); + assert!(!census_due(Some(5_000), 19_999, true)); + assert!(census_due(Some(5_000), 20_000, true)); + assert!(census_due(Some(5_000), 10_000, false)); + } + + #[test] + fn page_faults_a_second() { + assert_eq!(faults_per_second(None, (5_000, 900)), 0); + assert_eq!(faults_per_second(Some((0, 100)), (5_000, 600)), 100); + // The count wraps at 32 bits. + assert_eq!(faults_per_second(Some((0, u32::MAX - 99)), (1_000, 400)), 500); + // No time gone: nothing said. + assert_eq!(faults_per_second(Some((5_000, 100)), (5_000, 600)), 0); + } + fn region(base: usize, size: u64, kind: Kind) -> Region { Region { base, size, kind } } @@ -343,4 +460,4 @@ mod tests { assert!(c.regions > 10); drop(big); } -} \ No newline at end of file +} diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index aa077839d5..0d7fe1d70f 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -74,6 +74,9 @@ pub(super) trait Work: Send { { vec![self] } + /// Just before a folded one is unfolded, outside the line's lock: what + /// works on it beside the line lets go of it. + fn claim(&self) {} /// Waits until a folded one is free to go. fn settle(_: &Self::Ask) {} /// Takes `next`, what its queue was given behind it, along to be done with @@ -438,6 +441,9 @@ impl Lane { // Its parts take its place: behind everything before it, before // everything after it (they share its number; the first of them // is found first). + // (Not under the line's lock: it may wait for a refresh at the + // title's submit to stop.) + entry.what.claim(); let mut state = self.lock(); state.running = None; let at = state.items.iter().position(|e| e.number > entry.number).unwrap_or(state.items.len()); @@ -460,6 +466,9 @@ impl Lane { // (Back where it was: parts of one submission share a number.) if next.what.folded() { let free = next.what.ask().is_none_or(|ask| W::met(&ask)); + if free { + next.what.claim(); + } let mut state = self.lock(); if free { Self::unfold(&mut state, at, next); @@ -558,6 +567,12 @@ impl Work for Job { matches!(self, Job::Lists(..)) } + fn claim(&self) { + if let Job::Lists(_, recordings) = self { + crate::host::early_refresh::claim(recordings); + } + } + fn unfold(self) -> Vec { let Job::Lists(queue, recordings) = self else { return vec![self]; @@ -935,6 +950,8 @@ pub(super) fn submit(this: This, lists: &[This]) { if recordings.is_empty() { return; } + // Its copies refreshed while it waits in the line (`VICTORY_REFRESH_AT_SUBMIT`). + crate::host::early_refresh::post(&recordings); let before = QUEUED.fetch_add(1, Relaxed); STATS[DEPTH].fetch_add(before, Relaxed); STATS[DEEPEST].fetch_max(before + 1, Relaxed); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 3424581e1a..2ae458555a 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1383,6 +1383,9 @@ struct Hosted { refused: std::sync::atomic::AtomicBool, /// Its host copy was let go as idle once. gone: std::sync::atomic::AtomicBool, + /// When it was last let go (`crate::host::now_ms`, 0: never), for + /// [`BACK_SOON`]. + gone_at: std::sync::atomic::AtomicU64, /// A texture of [`PLACED_TEXTURES`]. placed: std::sync::atomic::AtomicBool, /// The lowest level a view asked for since it had no host copy @@ -1553,6 +1556,24 @@ pub(crate) fn want_level(this: This, first: u32) { pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; +/// Since the start: host copies of textures the title fills made again +/// within [`BACK_SOON_MS`] of being let go as idle, and their bytes. Many +/// of them: the sweep lets go what draws read again at once, and the card +/// does the uploads twice (the 23:29 run of 2026-11-28). +#[cfg(windows)] +pub(crate) static BACK_SOON: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What counts as soon for [`BACK_SOON`], in milliseconds. +#[cfg(any(windows, test))] +const BACK_SOON_MS: u64 = 10_000; + +/// Whether a copy let go at `gone_at` (0: never) and made again at `now` +/// (both `crate::host::now_ms`) came back soon. +#[cfg(any(windows, test))] +fn back_soon(gone_at: u64, now: u64) -> bool { + gone_at != 0 && now.saturating_sub(gone_at) < BACK_SOON_MS +} + /// Title textures the host renders to or writes ([`fills`] false), since the /// start: made, and released by the title. For the memory line: if the title /// goes on making them and releases few, the host copies the sweep never lets @@ -1965,6 +1986,10 @@ fn hosted(this: This, make: bool) -> Option { if r.host.gone.load(Relaxed) { KINDS[4].fetch_add(1, Relaxed); KINDS[5].fetch_add(host.bytes, Relaxed); + if back_soon(r.host.gone_at.load(Relaxed), crate::host::now_ms()) { + BACK_SOON[0].fetch_add(1, Relaxed); + BACK_SOON[1].fetch_add(host.bytes, Relaxed); + } } KINDS[6].fetch_add(1, Relaxed); *made = Some((std::sync::Arc::new(host), None)); @@ -2497,6 +2522,37 @@ pub(crate) fn room_terms(memory: Option<[u64; 4]>) -> Option<[u64; 8]> { ) } +/// Every five seconds, beside the room line: what the card's use is made +/// of, how many copies the sweep let go came back soon, and how many of +/// [`crate::texture::unchanged`]'s answers the write watch gave alone. +#[cfg(windows)] +pub(crate) fn log_5s() { + use std::sync::atomic::Ordering::Relaxed; + let Some([_, used, ..]) = crate::host::host().and_then(|h| h.video_memory()) else { + return; + }; + let mb = |bytes: u64| bytes >> 20; + let (textures, filled) = (HOST_TEXTURES[1].load(Relaxed), KINDS[1].load(Relaxed)); + let copies = crate::shadow::live_span_bytes(); + tracing::info!( + "the card's use: {} MB in all; host textures alive {} MB, of them {} MB the title fills and {} MB others \ + (render targets and the like); card copies of title buffers {} MB; the rest {} MB (DLSS, frame generation, \ + heaps, the driver's) | since the start {} host copies let go as idle, {} of them made again within 10 s ({} \ + MB) | asking whether a host copy holds what memory holds: {} answered by the write watch, {} read and hashed", + mb(used), + mb(textures), + mb(filled), + mb(textures.saturating_sub(filled)), + mb(copies), + mb(used.saturating_sub(textures + copies)), + KINDS[2].load(Relaxed), + BACK_SOON[0].load(Relaxed), + mb(BACK_SOON[1].load(Relaxed)), + crate::texture::SAME_ASKED[0].load(Relaxed), + crate::texture::SAME_ASKED[1].load(Relaxed), + ); +} + /// [`room`] as it was at most a tenth of a second ago, for a question /// asked of many textures a frame ([`room`] asks the system each time). #[cfg(windows)] @@ -2566,7 +2622,69 @@ pub(crate) fn room_line(budget: u64) -> u64 { None }; let framegen_reserve = std::env::var_os("VICTORY_FRAMEGEN_ROOM_RESERVE").is_some(); - room_line_for(budget, percent, framegen_reserve, crate::streamline::framegen_available()) + let line = room_line_for(budget, percent, framegen_reserve, crate::streamline::framegen_available()); + line_with_margin(budget, line, room_margin()) +} + +/// `line`, or under a margin the budget less `margin` if that is higher. +#[cfg(any(windows, test))] +fn line_with_margin(budget: u64, line: u64, margin: Option) -> u64 { + margin.map_or(line, |margin| line.max(budget.saturating_sub(margin))) +} + +/// `VICTORY_TEXTURE_ROOM_MARGIN_MB` (256 to 4096; unset: off): new textures +/// picked by index wait once the card's use is that many MB under its +/// budget, never under the line without it ([`line_with_margin`]), and idle +/// ones make way for them ([`keep_with_margin`]), from the first frame +/// frame generation shows on for the rest of the run (its 1.5 to 2 GB are +/// then in the card's use). +/// +/// The launcher's 80 % leaves frame generation's memory free a second time +/// while it runs (2026-11-28 23:07 run, RTX 5060 8 GB, Series S: 5,106 MB in +/// use against a line of 4,970 MB, the idle textures let go after 1.5 s). A +/// share that followed frame generation (88 % while it showed frames, 80 % +/// when not: 23:29 run) let the line fall 570 MB under what was in use when +/// it paused, everything idle went and came back with the next draws, and +/// the device was lost: a margin in MB does not move with it. +/// shortcut: turned on once for the run; frame generation switched off in the +/// menu and on again asks its memory back on top of the textures. +#[cfg(windows)] +fn room_margin() -> Option { + use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; + static MARGIN: std::sync::OnceLock> = std::sync::OnceLock::new(); + static SEEN: AtomicBool = AtomicBool::new(false); + let margin = (*MARGIN.get_or_init(|| { + let mb = std::env::var("VICTORY_TEXTURE_ROOM_MARGIN_MB").ok()?; + mb.trim().parse::().ok().map(|mb| mb.clamp(256, 4096) << 20) + }))?; + if !SEEN.load(Relaxed) { + if crate::streamline::shown_per_frame() <= 1 { + return None; + } + SEEN.store(true, Relaxed); + } + Some(margin) +} + +/// The idle sweep's rule under [`room_margin`], with `used` of `budget` in +/// use and the queue's `line`: none go while `used` is 2 % of the budget +/// under the line or more; above that those idle 5 s go, down to 5 % under +/// the line, so that textures idle for seconds make way for those the title +/// asks for now (kept up to half the margin under the budget, textures idle +/// for minutes held the room while thousands waited: 23:54 run, 84 of 95 +/// records with no room); those idle 1.5 s only within a quarter of the +/// margin of the budget. +#[cfg(any(windows, test))] +fn keep_with_margin(budget: u64, used: u64, line: u64, margin: u64) -> (u64, u64) { + let step = budget / 100; + let most = used.saturating_sub(line.saturating_sub(5 * step)); + if used < line.saturating_sub(2 * step) { + (600_000, u64::MAX) + } else if used < budget.saturating_sub(margin / 4) { + (5_000, most) + } else { + (1_500, most) + } } #[cfg(any(windows, test))] @@ -2961,7 +3079,10 @@ pub(crate) fn let_go_idle() { + crate::shadow::card_room_kept() + targets_room_kept(memory); let line = room_line(budget).saturating_sub(face_headroom_bytes()); - crate::host::vram_keep_below(budget, used, line) + match room_margin() { + Some(margin) => keep_with_margin(budget, used, line, margin), + None => crate::host::vram_keep_below(budget, used, line), + } } _ => (crate::host::vram_idle_ms(memory), u64::MAX), }; @@ -3027,6 +3148,7 @@ pub(crate) fn let_go_idle() { }; if let Some((host, _)) = gone { r.host.gone.store(true, Relaxed); + r.host.gone_at.store(crate::host::now_ms().max(1), Relaxed); KINDS[2].fetch_add(1, Relaxed); KINDS[3].fetch_add(host.bytes, Relaxed); STREAMED_OUT[0].fetch_add(1, Relaxed); @@ -3153,6 +3275,7 @@ pub(crate) fn let_go_idle() { }; if let Some((host, _)) = gone { r.host.gone.store(true, Relaxed); + r.host.gone_at.store(crate::host::now_ms().max(1), Relaxed); KINDS[2].fetch_add(1, Relaxed); KINDS[3].fetch_add(host.bytes, Relaxed); went += 1; @@ -3380,6 +3503,32 @@ pub(crate) fn slot_evict_on() -> bool { slot_evict_settings().is_some() } +/// `VICTORY_COLD_EVICT_S=` (off by default; needs +/// `VICTORY_SAMPLED_MARKS=1`): [`slot_evict`] also lets go of textures only +/// shaders pick by index, as `VICTORY_SAMPLED_EVICT=1` does, but only those +/// no shader marked for that long (10 to 110 s: the ring's two minutes) +/// instead of its 4-15 s idle time. Run H (v2026.11.29.01, RTX 5060 8 GB, +/// 2026-11-29): with `SAMPLED_EVICT=0` slot eviction let go of 0 textures in +/// 12 minutes, every slotted one being picked by index, while ~930 MB of +/// them were marked by no shader and the queue had no room from the first +/// minute on; `SAMPLED_EVICT=1` was turned off for foliage that flickered, +/// sampled now and then and let go between. +#[cfg(windows)] +pub(crate) fn cold_evict_ms() -> Option { + static MS: std::sync::OnceLock> = std::sync::OnceLock::new(); + *MS.get_or_init(|| { + cold_evict_ms_from(std::env::var("VICTORY_COLD_EVICT_S").ok().as_deref()) + .filter(|_| victory_shader::emit::sampled_marks_on()) + }) +} + +/// [`cold_evict_ms`]'s reading of its switch's value. +#[cfg_attr(not(windows), allow(dead_code))] +fn cold_evict_ms_from(v: Option<&str>) -> Option { + let s = v?.trim().parse::().ok().filter(|&s| s > 0)?; + Some(s.clamp(10, 110) * 1000) +} + /// How many bytes over `percent` of `budget` the card's `used` is. #[cfg_attr(not(windows), allow(dead_code))] fn excess(budget: u64, used: u64, percent: u64) -> u64 { @@ -3477,7 +3626,8 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64, flush: u8) -> while ring.len() > 120 { ring.pop_front(); } - frame_at(&ring, now_ms.saturating_sub(evict_idle_ms)) + let cold = cold_evict_ms().and_then(|ms| frame_at(&ring, now_ms.saturating_sub(ms))); + frame_at(&ring, now_ms.saturating_sub(evict_idle_ms)).map(|at| (at, cold)) }; // (After the ring above, which a flush reads with the switch off too.) // A flush needs neither the switch nor the card's numbers. @@ -3506,7 +3656,7 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64, flush: u8) -> return (0, 0); } // Not yet a frame `evict_idle_ms` back: nothing is known idle by its slots. - let Some(cutoff) = cutoff else { + let Some((cutoff, cold_cutoff)) = cutoff else { return (0, 0); }; // Held to the end: a texture leaves the table before it is freed, under @@ -3541,7 +3691,7 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64, flush: u8) -> if copies.is_empty() { return (0, 0); } - let (slots, kept, blocked, cold) = crate::descriptor::evictable_slots(&raws, frame, cutoff); + let (slots, kept, blocked, cold) = crate::descriptor::evictable_slots(&raws, frame, cutoff, cold_cutoff); SLOT_STATE[3].store(raws.len() as u64, Relaxed); SLOT_STATE[2].store(blocked, Relaxed); SLOT_STATE[1].store(kept, Relaxed); @@ -3585,6 +3735,7 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64, flush: u8) -> }; if gone.is_some() { r.host.gone.store(true, Relaxed); + r.host.gone_at.store(crate::host::now_ms().max(1), Relaxed); } Some(gone) } @@ -4375,6 +4526,7 @@ fn hand_out_resource( used: std::sync::atomic::AtomicU64::new(0), refused: std::sync::atomic::AtomicBool::new(false), gone: std::sync::atomic::AtomicBool::new(false), + gone_at: std::sync::atomic::AtomicU64::new(0), placed: std::sync::atomic::AtomicBool::new(false), wanted: std::sync::atomic::AtomicU32::new(u32::MAX), grown: std::sync::atomic::AtomicBool::new(false), @@ -5169,6 +5321,16 @@ mod tests { assert!(slot_evict_text([0, 0, 0, 1, 0, 30, 0, 0], [0, 0, 0, 0]).is_some_and(|t| t.contains("Evicting: no"))); } + #[test] + fn cold_eviction_reads_seconds_within_the_ring() { + assert_eq!(super::cold_evict_ms_from(None), None); + assert_eq!(super::cold_evict_ms_from(Some("0")), None); + assert_eq!(super::cold_evict_ms_from(Some("x")), None); + assert_eq!(super::cold_evict_ms_from(Some("45")), Some(45_000)); + assert_eq!(super::cold_evict_ms_from(Some("3")), Some(10_000)); + assert_eq!(super::cold_evict_ms_from(Some("600")), Some(110_000)); + } + /// Between the lines nothing starts; over the high one eviction starts /// and takes the excess over the low one, a capped step at a time, until /// the card is under the low one. @@ -6652,6 +6814,56 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB); } + /// `VICTORY_TEXTURE_ROOM_MARGIN_MB`: new textures stop that far under + /// the budget but never under the line without it, and idle ones make + /// way for them (RTX 5060 8 GB runs of 2026-11-28: 23:07, 23:29, 23:54). + #[test] + fn room_margin_under_the_budget() { + const MIB: u64 = 1 << 20; + const MARGIN: u64 = 1024 * MIB; + let eighty = |budget: u64| budget / 100 * 80; + // Off: the line as it is. + assert_eq!(line_with_margin(6213 * MIB, eighty(6213 * MIB), None), eighty(6213 * MIB)); + // On: the budget less the margin, over the 80 % share. + assert_eq!(line_with_margin(6213 * MIB, eighty(6213 * MIB), Some(MARGIN)), 5189 * MIB); + assert_eq!(line_with_margin(6265 * MIB, eighty(6265 * MIB), Some(MARGIN)), 5241 * MIB); + // never under it: 1,280 MB of 6,265 would be 4,985 MB (23:54 run) + assert_eq!(line_with_margin(6265 * MIB, eighty(6265 * MIB), Some(1280 * MIB)), eighty(6265 * MIB)); + assert_eq!(line_with_margin(512 * MIB, eighty(512 * MIB), Some(MARGIN)), eighty(512 * MIB)); + + // Idle textures, around the queue's line. + let keep = |budget: u64, used: u64| { + let line = line_with_margin(budget, eighty(budget), Some(MARGIN)); + keep_with_margin(budget, used, line, MARGIN) + }; + // 23:54, 5,864 MB of 6,265 with thousands waiting: those idle 5 s go, + // down to 5 % under the line; + let line = 5241 * MIB; + assert_eq!(keep(6265 * MIB, 5864 * MIB), (5_000, 5864 * MIB - (line - 6265 * MIB / 100 * 5))); + // a scene that ran well at 5,800 MB of 6,333 (23:33-23:36): 5 s; + assert_eq!(keep(6333 * MIB, 5800 * MIB).0, 5_000); + // 23:37, 6,116 MB of 6,452: still 5 s; + assert_eq!(keep(6452 * MIB, 6116 * MIB).0, 5_000); + // within a quarter of the margin of the budget, or past it (23:41, + // 6,986 of 6,481): 1.5 s; + assert_eq!(keep(6481 * MIB, 6986 * MIB).0, 1_500); + assert_eq!(keep(6481 * MIB, 6300 * MIB).0, 1_500); + // 2 % under the line or more: none go. + assert_eq!(keep(6333 * MIB, 5100 * MIB), (600_000, u64::MAX)); + } + + /// A copy made again within 10 s of being let go counts as back soon; + /// one never let go, or let go longer ago, does not. + #[test] + fn copies_made_again_soon_after_they_went() { + assert!(!back_soon(0, 5_000)); + assert!(back_soon(1_000, 1_000)); + assert!(back_soon(1_000, 10_999)); + assert!(!back_soon(1_000, 11_000)); + // (A clock read before the stamp: soon.) + assert!(back_soon(2_000, 1_000)); + } + /// The texture queue's line: the budget less 768 MiB or 5 %, never under /// 90 % of it. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0c572f4ee7..94b0248520 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -73,6 +73,16 @@ pub(crate) struct Shadow { /// go in under shader writes ([`Shadow::merge_under_writes`]), which /// takes `before`'s lock too. Taken ahead of that one. merging: RwLock<()>, + /// Held while the copy is refreshed ([`Shadow::update`]) and while + /// shaders are first said to write it ([`Shadow::gpu_writes`]): a refresh + /// at the title's submit (`crate::host::early_refresh`) runs beside the + /// submitting thread's, and must never be copying while the copy becomes + /// one that shaders write. + refreshing: Mutex<()>, + /// Refreshes at the title's submit of this copy so far, and whether the + /// last refresh was one (for `VICTORY_REFRESH_CHECK`'s word on it). + ahead_refreshes: AtomicU64, + last_ahead: std::sync::atomic::AtomicBool, /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot /// hold the copy's bytes as they are now, and whether the snapshot is /// counted in [`KEPT_BYTES`]. @@ -122,6 +132,10 @@ pub(crate) struct Shadow { before_me: Mutex>>, /// With [`grow`]: a longer window took this one's place ([`TAKEN_OVER`]). taken_over: std::sync::atomic::AtomicBool, + /// With `VICTORY_MEM_ATTRS=1`: the attribute class of the title memory + /// at `start` (`crate::memattrs`), and whether a refresh copied anything yet. + pub(crate) attr: u8, + uploaded: std::sync::atomic::AtomicBool, } /// From crossducking/RAZDA4A-XEN 76b58130 via vix0e0e/VIctory-LITE e66dcc25 @@ -142,6 +156,13 @@ impl CardCpu { fn allocate(size: u64) -> Option<(Self, *mut u8)> { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + if Self::private_enabled() + && lazy_mirror::on() + && let Some(data) = usize::try_from(size).ok().and_then(lazy_mirror::reserve) + { + PRIVATE_CPU_BYTES.fetch_add(size, Ordering::Relaxed); + return Some((Self::Private { address: data as usize, size }, data)); + } if Self::private_enabled() { // SAFETY: fresh, zero-filled process pages owned until this mirror drops. let data = unsafe { VirtualAlloc(std::ptr::null(), usize::try_from(size).ok()?, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; @@ -163,6 +184,8 @@ impl Drop for CardCpu { fn drop(&mut self) { if let Self::Private { address, size } = self { use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; + // Out of the lazy table first: no fault may commit into it once released. + lazy_mirror::forget(*address); // SAFETY: the base of this mirror's VirtualAlloc reservation, released once. unsafe { VirtualFree(*address as *mut _, 0, MEM_RELEASE) }; PRIVATE_CPU_BYTES.fetch_sub(*size, Ordering::Relaxed); @@ -2529,10 +2552,23 @@ fn workers() -> &'static Workers { workers } +thread_local! { + /// This thread does its own work only ([`alone`]). + static ALONE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// From here on [`wide`] work asked on this thread is done on it, and it never +/// takes other threads' jobs: a refresh at the title's submit holds a copy's +/// lock while it refreshes, and a job of the submission's waiting for that +/// lock would wait for itself. +pub(crate) fn alone() { + ALONE.set(true); +} + /// Runs `jobs` on the kept threads and on this one, and returns when all /// of them are done. The jobs copy and compare memory; they do not panic. fn wide(jobs: Vec) { - if jobs.len() < 2 { + if jobs.len() < 2 || ALONE.get() { for job in jobs { job(); } @@ -2629,6 +2665,15 @@ pub(crate) fn copy_beside(copies: Vec<(usize, usize, usize)>) -> Beside { Beside(Some(queued(copy_jobs(copies, false), 0))) } +/// [`wide_run`] without the wait: `jobs` begun on the kept threads, done +/// when the result is dropped (`crate::host`'s `VICTORY_REFRESH_BESIDE`). +pub(crate) fn run_beside(jobs: Vec>) -> Beside { + if jobs.is_empty() { + return Beside(None); + } + Beside(Some(queued(jobs, 0))) +} + /// [`wide`], for the host's own work on host copies (a submission's /// refreshes, the merge of what shaders wrote to card copies). pub(crate) fn wide_run(jobs: Vec>) { @@ -3540,6 +3585,22 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { /// The kernel's page. const KERNEL_PAGE: usize = 4096; +/// Why a refresh at the title's submit leaves a copy to the submission +/// ([`Shadow::not_ahead`]). +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum NotAhead { + /// Shaders write it (or the card reads title memory itself). + Written, + /// In the card's memory. + Card, + /// Guarded view memory. + Guarded, + /// Not write-watched, or not known yet. + Unwatched, + /// A window of title memory outside buffers. + Window, +} + /// Whether a refresh looks if what counts as written is only what a landing /// put there, and then sends nothing of it up (`VICTORY_LAND_ECHO=0`: it copies /// and sends it, as before). @@ -4484,6 +4545,76 @@ mod merge_tests { /// snapshot still holds) and the bytes of title memory they copy. static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// For `VICTORY_REFRESH_CHECK` ([`Shadow::refresh_check`]): the refreshes in a +/// row that found a block of a copy differing from title memory, the block +/// found so again with `before` before, of the same copy or not, and whether +/// the copy's bytes there moved since. +/// +/// Copies can overlap at the same address: a new copy starts its own count. +/// And a copy whose bytes moved was brought up to date by the refresh: title +/// memory was written again between it and the look (in play log +/// 20261129-150547, 65 warnings of one 50 MB copy, every one with the copy +/// and title memory moved, as the intro's transitions rewrote it). A block +/// that stays stale keeps its bytes while title memory has others. +fn mismatches_in_a_row(before: u32, same_copy: bool, copy_moved: bool) -> u32 { + if same_copy && !copy_moved { before.saturating_add(1) } else { 1 } +} + +#[cfg(test)] +mod mismatch_tests { + use super::mismatches_in_a_row as next; + + /// Only a block whose copy holds still while title memory differs counts + /// up to the warning; another copy, or one the refresh moved, starts over. + #[test] + fn only_a_copy_that_holds_still_counts_up() { + assert_eq!(next(next(next(0, true, false), true, false), true, false), 3); + assert_eq!(next(2, true, true), 1, "the refresh took new bytes: a write after it"); + assert_eq!(next(2, false, false), 1, "another copy at the same address"); + } +} + +/// Bytes of the snapshots copies in the PC's memory hold now (the copy's +/// bytes from before shaders write it, to compare with once they have). +static SNAPSHOT_BYTES: AtomicU64 = AtomicU64::new(0); + +/// The memory host copies of title memory take, in bytes ([`live_bytes`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct LiveBytes { + /// Host copies alive. + pub(crate) copies: u64, + /// In the PC's memory: the copies' own bytes (for copies in the card's + /// memory, their CPU side), but windows mapped from the card. + pub(crate) ram: u64, + /// Of the PC's memory, what only serves to compare: snapshots in use, + /// and the snapshot buffers kept for reuse. + pub(crate) ram_compare: u64, + /// In the card's memory: copies' card sides (and windows and + /// write-combined copies mapped from it). + pub(crate) card: u64, + /// Of the card's memory, what only serves to compare: the hashes of + /// pieces of copies there. + pub(crate) card_compare: u64, +} + +/// The memory host copies of title memory take now: in the PC's memory, +/// on the card, and of each what only serves to compare. Counters, and one +/// short lock over the snapshot buffers kept. +/// +/// shortcut: a write-combined copy mapped from the card (`VICTORY_WC_BAR`) +/// counts in `ram` as well as in `card`; a counter of its own if they matter. +pub(crate) fn live_bytes() -> LiveBytes { + let pool: u64 = POOL.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|v| v.capacity() as u64).sum(); + let ram_compare = SNAPSHOT_BYTES.load(Ordering::Relaxed) + pool; + LiveBytes { + copies: LIVE[0].load(Ordering::Relaxed), + ram: LIVE[1].load(Ordering::Relaxed).saturating_sub(WINDOW_MAPPED_BYTES.load(Ordering::Relaxed)) + ram_compare, + ram_compare, + card: CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed), + card_compare: CARD_BYTES[1].load(Ordering::Relaxed), + } +} + impl Drop for Shadow { fn drop(&mut self) { if self.place.is_some() { @@ -4493,6 +4624,10 @@ impl Drop for Shadow { } LIVE[0].fetch_sub(1, Ordering::Relaxed); LIVE[1].fetch_sub(self.len, Ordering::Relaxed); + crate::memattrs::copy_gone(self.attr, self.len); + if self.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { + SNAPSHOT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 { KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); } @@ -5183,6 +5318,7 @@ impl Shadow { // title wrote there. LIVE[0].fetch_sub(1, Ordering::Relaxed); LIVE[1].fetch_sub(len, Ordering::Relaxed); + crate::memattrs::copy_gone(shadow.attr, len); *shadow.watched.get_mut() = NOT_WATCHED; shadow.window = window; shadow.place = Some((placed.heap, placed.bias)); @@ -5273,6 +5409,9 @@ impl Shadow { flights: Mutex::default(), before: Mutex::default(), merging: RwLock::default(), + refreshing: Mutex::new(()), + ahead_refreshes: AtomicU64::new(0), + last_ahead: std::sync::atomic::AtomicBool::new(false), kept: Mutex::default(), used: AtomicU64::new(crate::host::moment()), frames: Default::default(), @@ -5291,6 +5430,8 @@ impl Shadow { place: None, before_me: Mutex::default(), taken_over: Default::default(), + attr: crate::memattrs::copy_made(start as usize, len), + uploaded: Default::default(), } } @@ -5325,6 +5466,9 @@ impl Shadow { list.note_batch_write(address, len); return; } + // Not while a refresh at the title's submit copies into it: from here + // on none does. + let _refreshing = crate::host::early_refresh::on().then(|| self.refreshing.lock().unwrap_or_else(|e| e.into_inner())); // Write-combined title memory, which the title's CPU does not read // (`VICTORY_WC_NO_BACK`, and always for `VICTORY_WC_BAR`'s copies, // which the CPU would read through the bus): what shaders write stays @@ -5432,6 +5576,9 @@ impl Shadow { if self.place.is_some() { return; } + // Not while a refresh at the title's submit copies into it: it looks + // at the ranges shaders may be writing under this lock. + let _refreshing = crate::host::early_refresh::on().then(|| self.refreshing.lock().unwrap_or_else(|e| e.into_inner())); let range = (address, address + len); let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); // With the copy-back on its own thread: counted for this submission @@ -5478,6 +5625,9 @@ impl Shadow { BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); let total = self.len as usize; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + if before.is_none() { + SNAPSHOT_BYTES.fetch_add(self.len, Ordering::Relaxed); + } let snapshot = before.get_or_insert_with(|| pooled(total)); if keeps() { // Piece by piece, and only the pieces not known current. A @@ -5825,6 +5975,7 @@ impl Shadow { kept.0.clear(); } if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { + SNAPSHOT_BYTES.fetch_sub(self.len, Ordering::Relaxed); give_back(bytes); } } @@ -6195,6 +6346,74 @@ impl Shadow { if self.place.is_some() { return 0; } + // (Only with the switch: nothing else refreshes beside the submission.) + let _refreshing = crate::host::early_refresh::on().then(|| self.refreshing.lock().unwrap_or_else(|e| e.into_inner())); + self.last_ahead.store(false, Ordering::Relaxed); + self.update_held(address, len) + } + + /// [`Shadow::update`] at the title's submit (`crate::host::early_refresh`), + /// of a copy that shaders never write: `None` if another thread is + /// refreshing it, or it is not such a copy (any more): in the card's + /// memory, not write-watched by the kernel, written by shaders, or with + /// ranges shaders may be writing are left to the submission. + /// `cards`: copies in the card's memory too (`VICTORY_REFRESH_AT_SUBMIT=2`). + pub(crate) fn update_ahead(&self, address: usize, len: usize, cards: bool) -> Option { + let _refreshing = self.refreshing.try_lock().ok()?; + // (Looked at under the lock: `gpu_writes` and `writing` take it before + // they say so.) + if self.not_ahead(cards).is_some() || self.writes_pending() { + return None; + } + self.ahead_refreshes.fetch_add(1, Ordering::Relaxed); + self.last_ahead.store(true, Ordering::Relaxed); + Some(self.update_held(address, len)) + } + + /// Whether a refresh at the title's submit may take the copy: never + /// written by shaders, write-watched by the kernel, on the CPU's side alone + /// or, with `cards`, in the card's memory (whose CPU side it then brings up + /// to date, and notes to go up, as the submission's refresh does). Else + /// why not. + /// + /// Not guarded view memory: the submitting thread opens a block's guards + /// before it copies into title memory there, and a refresh beside it could + /// guard the block again in between and never hear of that copy. The + /// kernel's dirty bits see every write. + pub(crate) fn not_ahead(&self, cards: bool) -> Option { + if self.place.is_some() || self.written.load(Ordering::Relaxed) || self.changes_only.load(Ordering::Relaxed) { + return Some(NotAhead::Written); + } + if self.window && !crate::host::early_refresh::windows() { + return Some(NotAhead::Window); + } + if let Some(card) = &self.card { + if !cards || crate::host::upcheck::on() { + return Some(NotAhead::Card); + } + // Compared on the card (declared or looked at through views picked + // by index: `Host::card_before`), or landed in: what the card wrote + // comes back into its CPU side beside the submission. + if self.landing.load(Ordering::Acquire) || card.before.get().is_some() { + return Some(NotAhead::Written); + } + } + match self.watched.load(Ordering::Relaxed) { + 1 => None, + GUARDED if crate::host::early_refresh::guarded() => None, + GUARDED => Some(NotAhead::Guarded), + _ => Some(NotAhead::Unwatched), + } + } + + /// [`Shadow::update`] with `refreshing` held. + fn update_held(&self, address: usize, len: usize) -> usize { + let n = self.update_held_ranges(address, len); + crate::memattrs::refreshed(self.attr, &self.uploaded, n); + n + } + + fn update_held_ranges(&self, address: usize, len: usize) -> usize { let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { @@ -6441,8 +6660,16 @@ impl Shadow { return; } const SAMPLE: usize = 256; - // Blocks found differing: how many refreshes in a row. - static DIFFERING: Mutex>> = Mutex::new(None); + // Blocks found differing: how many refreshes in a row, and at the + // last of them the copy, and hashes of its sample and title memory's. + type Seen = (u32, u64, u64, u64); + static DIFFERING: Mutex>> = Mutex::new(None); + let hash = |bytes: &[u8]| { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut h); + h.finish() + }; static SAID: AtomicU64 = AtomicU64::new(0); let start = self.start as usize; let mut title = [0u8; SAMPLE]; @@ -6458,9 +6685,16 @@ impl Shadow { if copy == &title[..n] { map.remove(&at); } else { - let times = map.entry(at).or_insert(0); - *times += 1; - if *times == 3 { + let (copy_hash, title_hash) = (hash(copy), hash(&title[..n])); + let seen = map.entry(at).or_insert((0, self.id, copy_hash, title_hash)); + // Which side moved since the last refresh that found it so + // (of the same copy): the copy (something wrote it that is + // no refresh: the card, in place or through an undeclared + // view) or title memory (a write nothing told of). + let (same_copy, copy_moved, title_moved) = (seen.1 == self.id, seen.2 != copy_hash, seen.3 != title_hash); + let times = mismatches_in_a_row(seen.0, same_copy, copy_moved); + *seen = (times, self.id, copy_hash, title_hash); + if times == 3 { let said = SAID.fetch_add(1, Ordering::Relaxed) + 1; if said <= 64 || said.is_power_of_two() { tracing::warn!( @@ -6472,6 +6706,17 @@ impl Shadow { refreshed = format_args!("{from:#x}..{to:#x}"), on_the_card = self.card.is_some(), window = self.window, + // How it is watched (1 the kernel, 2 not, 3 + // guarded), and the refreshes at the title's + // submit: of it so far, whether this was one, + // and on which thread this one ran. + watched = self.watched.load(Ordering::Relaxed), + ahead_refreshes = self.ahead_refreshes.load(Ordering::Relaxed), + this_one_ahead = self.last_ahead.load(Ordering::Relaxed), + thread = std::thread::current().name().unwrap_or("?"), + same_copy, + copy_moved, + title_moved, "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)" ); } @@ -6747,6 +6992,9 @@ impl Shadow { crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a)); }); } else { + if self.card.is_some() { + lazy_mirror::before_kernel_write(at, to.saturating_sub(from)); + } crate::host::copy_mapped(at, from as *const u8, to - from, false); } // After the bytes are in: a snapshot taken meanwhile is not current. @@ -6886,6 +7134,9 @@ impl Shadow { let Some(card) = &self.card else { return false; }; + // Not while a refresh at the title's submit copies into it: a copy with + // its bytes from before is left to the submission from now on. + let _refreshing = crate::host::early_refresh::on().then(|| self.refreshing.lock().unwrap_or_else(|e| e.into_inner())); if card.before.get().is_some() { return false; } @@ -9878,3 +10129,219 @@ mod arena_card_tests { #[cfg(test)] mod file_backing_tests; + +/// CPU mirrors committed only where touched (`VICTORY_CARD_CPU_LAZY=1`; off +/// by default, and only with `VICTORY_CARD_CPU_HEAP=1`, whose mirrors the +/// card never reads). Run H (2026-11-29, `docs/ram-prive-2026-11-29.md`): +/// 21.2 GB private on a 16 GB PC, 1.14 GB of it the CPU sides of copies in +/// the card's memory, which hold the title's bytes again; and of windows, of +/// which these are many, 1,988 of 3,236 MB were ever copied (run of +/// `docs/unified-memory-audit.md`, U4). A mirror is reserved, and each 64 KiB +/// of it committed when it is first touched: by a fault our handler takes +/// (the first in the process once a mirror is made), or ahead of the +/// kernel's copies into it ([`Shadow::copy`]), which report a page that is +/// not there instead of faulting. A page committed so reads zeros, as a +/// fresh committed mirror's does, so nothing that reads it sees otherwise. +/// shortcut: what was committed stays so until the mirror goes; decommit +/// what was sent if this one shows a gain. +pub(crate) mod lazy_mirror { + use std::collections::BTreeMap; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + + /// What is committed at a time. + pub(crate) const GRAIN: usize = 64 << 10; + /// Each lazy mirror by its base: its end, and a bit per grain committed. + static MIRRORS: Mutex)>> = Mutex::new(BTreeMap::new()); + /// Whether a lazy mirror was ever made (the handler's and copies' quick no). + static ANY: AtomicBool = AtomicBool::new(false); + /// Of the lazy mirrors alive, the bytes reserved and committed. + pub(crate) static RESERVED: AtomicU64 = AtomicU64::new(0); + pub(crate) static COMMITTED: AtomicU64 = AtomicU64::new(0); + + pub(crate) fn on() -> bool { + crate::asked_for!("VICTORY_CARD_CPU_LAZY") + } + + /// Reserves a mirror of `size` bytes, committed only as it is touched. + pub(crate) fn reserve(size: usize) -> Option<*mut u8> { + use windows_sys::Win32::System::Memory::{MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + install(); + // SAFETY: a fresh reservation, ours until `forget` and its release. + let base = unsafe { VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_READWRITE) } as usize; + if base == 0 { + return None; + } + let grains = size.div_ceil(GRAIN); + MIRRORS.lock().unwrap_or_else(|e| e.into_inner()).insert(base, (base + size, vec![0; grains.div_ceil(64)])); + RESERVED.fetch_add(size as u64, Ordering::Relaxed); + ANY.store(true, Ordering::Release); + Some(base as *mut u8) + } + + /// Commits the grains of `[at, at + len)` (cut to its mirror's end): + /// `None` when `at` lies in no lazy mirror, else whether all of it is + /// committed now. + pub(crate) fn commit(at: usize, len: usize) -> Option { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, PAGE_READWRITE, VirtualAlloc}; + if !ANY.load(Ordering::Acquire) { + return None; + } + let mut map = MIRRORS.lock().unwrap_or_else(|e| e.into_inner()); + let (&base, (end, bits)) = map.range_mut(..=at).next_back()?; + if at >= *end { + return None; + } + let to = (at + len.max(1)).min(*end); + for g in (at - base) / GRAIN..=(to - 1 - base) / GRAIN { + if (bits[g / 64] >> (g % 64)) & 1 != 0 { + continue; + } + let from = base + g * GRAIN; + let n = GRAIN.min(*end - from); + // SAFETY: inside this mirror's reservation, which the lock keeps alive. + if unsafe { VirtualAlloc(from as *const _, n, MEM_COMMIT, PAGE_READWRITE) }.is_null() { + return Some(false); + } + bits[g / 64] |= 1 << (g % 64); + COMMITTED.fetch_add(n as u64, Ordering::Relaxed); + } + Some(true) + } + + /// Commits ahead of a write the kernel makes into `[at, at + len)`. + pub(crate) fn before_kernel_write(at: *mut u8, len: usize) { + if len != 0 { + commit(at as usize, len); + } + } + + /// The bytes committed of the lazy mirror at `base` (0: none there). + #[cfg(test)] + pub(crate) fn committed_of(base: usize) -> u64 { + let map = MIRRORS.lock().unwrap_or_else(|e| e.into_inner()); + map.get(&base).map_or(0, |(end, bits)| committed_bytes(base, *end, bits)) + } + + fn committed_bytes(base: usize, end: usize, bits: &[u64]) -> u64 { + (0..(end - base).div_ceil(GRAIN)) + .filter(|g| (bits[g / 64] >> (g % 64)) & 1 != 0) + .map(|g| GRAIN.min(end - base - g * GRAIN) as u64) + .sum() + } + + /// The mirror at `base` is about to be released. + pub(crate) fn forget(base: usize) { + if !ANY.load(Ordering::Acquire) { + return; + } + if let Some((end, bits)) = MIRRORS.lock().unwrap_or_else(|e| e.into_inner()).remove(&base) { + COMMITTED.fetch_sub(committed_bytes(base, end, &bits), Ordering::Relaxed); + RESERVED.fetch_sub((end - base) as u64, Ordering::Relaxed); + } + } + + fn install() { + use windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + // The guards' handler first, so ours goes in front of it: a fault on a + // mirror inside a safe copy must be committed, not sent to its failing exit. + let _ = crate::safecopy::on(); + // SAFETY: the handler only commits pages of the mirrors kept here. + unsafe { AddVectoredExceptionHandler(1, Some(on_fault)) }; + }); + } + + unsafe extern "system" fn on_fault(info: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 { + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH}; + // SAFETY: the system passes the exception being dispatched. + let r = unsafe { &*(*info).ExceptionRecord }; + // No allocation here, and only MIRRORS' lock, which no thread holds while touching a mirror: then VirtualAlloc(MEM_COMMIT) and return. + // (8: an execute fault, which no commit cures.) + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] == 8 { + return EXCEPTION_CONTINUE_SEARCH; + } + match commit(r.ExceptionInformation[1], 1) { + Some(true) => EXCEPTION_CONTINUE_EXECUTION, + _ => EXCEPTION_CONTINUE_SEARCH, + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn a_lazy_mirror_commits_only_the_grains_it_touches() { + let size = 4 * GRAIN + 4096; + let data = reserve(size).expect("reserve"); + let base = data as usize; + assert_eq!(committed_of(base), 0); + // SAFETY: inside the reservation; the handler commits the grain. + unsafe { data.add(2 * GRAIN + 5).write_volatile(7) }; + assert_eq!(committed_of(base), GRAIN as u64); + // SAFETY: as above; a grain never written reads zeros. + let read = |at: usize| unsafe { data.add(at).read_volatile() }; + assert_eq!(read(GRAIN / 2), 0); + assert_eq!(read(2 * GRAIN + 5), 7); + assert_eq!(committed_of(base), 2 * GRAIN as u64); + // Ahead of a kernel copy over the end: the short tail grain too. + assert_eq!(commit(base + 3 * GRAIN + 10, GRAIN + 100), Some(true)); + assert_eq!(committed_of(base), (3 * GRAIN + 4096) as u64, "grain 1 never touched"); + assert_eq!(commit(base + size, 1), None, "past the mirror"); + let mut copied = 0; + let src = [9u8; 64]; + // SAFETY: the kernel writes committed pages of our own process. + let ok = unsafe { + windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + data.add(3 * GRAIN) as *const _, + src.as_ptr().cast(), + src.len(), + &mut copied, + ) + }; + assert!(ok != 0 && copied == 64); + forget(base); + assert_eq!(committed_of(base), 0); + // SAFETY: the reservation, released once. + unsafe { windows_sys::Win32::System::Memory::VirtualFree(data.cast(), 0, windows_sys::Win32::System::Memory::MEM_RELEASE) }; + } + + /// As the kept threads' copies of a send read it (`copy_beside`): on + /// another thread, through `copy_snapshot` (its AVX2 path, 64 KiB and + /// up), from grains not committed yet and one written. + #[test] + fn another_thread_reads_a_lazy_mirror_through_copy_snapshot() { + let size = 4 * GRAIN; + let data = reserve(size).expect("reserve"); + let base = data as usize; + // SAFETY: inside the reservation; the handler commits the grain. + unsafe { data.add(GRAIN + 3).write_volatile(5) }; + let got = std::thread::spawn(move || { + let mut out = vec![1u8; 3 * GRAIN]; + // SAFETY: the mirror's first three grains and a buffer of theirs. + unsafe { super::super::copy_snapshot(base as *const u8, out.as_mut_ptr(), out.len()) }; + out + }) + .join() + .expect("the reading thread"); + assert!(got[..GRAIN].iter().all(|&b| b == 0), "never written: zeros"); + assert_eq!(got[GRAIN + 3], 5); + assert_eq!(got.iter().filter(|&&b| b != 0).count(), 1); + assert_eq!(committed_of(base), 3 * GRAIN as u64); + // A safe copy faulting on the last grain is committed, not failed: + // our handler is in front of the guards'. + let mut tail = [1u8; 256]; + // SAFETY: the mirror's last grain and a buffer of ours. + assert!(unsafe { crate::safecopy::copy(tail.as_mut_ptr(), (base + 3 * GRAIN) as *const u8, tail.len()) }); + assert!(tail.iter().all(|&b| b == 0)); + assert_eq!(committed_of(base), 4 * GRAIN as u64); + forget(base); + // SAFETY: the reservation, released once. + unsafe { windows_sys::Win32::System::Memory::VirtualFree(data.cast(), 0, windows_sys::Win32::System::Memory::MEM_RELEASE) }; + } + } +} diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 00b3c3ad7a..04638fb55a 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -952,9 +952,40 @@ pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { .filter(|(at, d)| address < **at + d.0) .map(|(at, d)| (*at, *d)) }; - if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit { + if let Some((at, (bytes, width, height, layers_levels, format, old))) = hit { + let block = |f: u32| crate::resource::element(crate::resource::pc_format(f)); + let reuse = reused(address - at, desc, (width, height, layers_levels), block(desc[8]), block(format)); + if reuse && reuse_on() { + // The memory holds another texture now: a view laid out as the + // copied one is no longer that texture (`host_written_like`). + let mut map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()); + if map.get(&at).is_some_and(|d| d.5 == old) { + map.remove(&at); + } + drop(map); + REUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { + if reuse { + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { + tracing::info!( + view_address = format_args!("{address:#x}"), + view_offset = address - at, + view_width = desc[4], + view_height = desc[6], + view_layers_levels = format_args!("{:#x}", desc[7]), + view_format = desc[8], + copied_address = format_args!("{at:#x}"), + copied_width = width, + copied_height = height, + copied_layers_levels = format_args!("{layers_levels:#x}"), + copied_format = format, + taken_back = reuse_on(), + so_far = REUSED.load(std::sync::atomic::Ordering::Relaxed), + "a placed texture view of another layout lies in the memory of a texture the host copied into: the memory holds another texture now, filled from title memory as it should be (VICTORY_HOST_WRITTEN_REUSE=1: the copied texture's address is forgotten)" + ); + } + } else if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { tracing::warn!( view_address = format_args!("{address:#x}"), view_offset = address - at, @@ -974,6 +1005,39 @@ pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { } } +/// `VICTORY_HOST_WRITTEN_REUSE=1` (off by default): a placed view whose +/// layout cannot be the copied texture's ([`reused`]) over the memory of a +/// texture the host copied into says the title gave that memory to another +/// texture: the copied texture's address is forgotten, so that a later view +/// laid out as it was reads its own memory, not the old copy +/// ([`host_written_like`]). Run of 2026-11-30 00:29 (37bce66): the two +/// "HERO LEAD" lines were a BC6H cubemap (512x512, 6 faces, 10 levels) where +/// a BC7 1024x1024 texture had been copied into, and a BC1 texture 20 KiB +/// into a BC3 one: other textures, which filling from the copy would show as +/// the old texels read in another format. Placed textures made for views +/// live for the run, so the copied texture is not released and its entry +/// stayed. +fn reuse_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HOST_WRITTEN_REUSE").is_some_and(|v| v == "1")) +} + +/// Since the start: views [`reused`] found over copied textures' memory. +pub(crate) static REUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a placed view `offset` bytes into a copied texture's memory, +/// with description words `desc` and bytes per block `view_block`, cannot +/// read that texture (laid out as `copied`: width, height, layers and +/// levels, and `copied_block`): another block size, another layer count, +/// or other dimensions at its start. A view of the same block size and +/// layers further in may be one of its levels, and is not taken for reuse. +fn reused(offset: u64, desc: &[u32; 14], copied: (u32, u32, u32), view_block: Option<(u64, u64)>, copied_block: Option<(u64, u64)>) -> bool { + let (width, height, layers_levels) = copied; + view_block != copied_block + || desc[7] & 0xFFFF != layers_levels & 0xFFFF + || offset == 0 && (desc[4], desc[6]) != (width, height) +} + /// Whether the host GPU wrote `resource` by a copy or resolve /// ([`host_written`]): its host copy cannot be made again from title /// memory. @@ -2662,12 +2726,65 @@ pub(crate) fn unchanged(resource: This, first: u32) -> bool { return false; } let size = layout.bytes_from(from) as usize; - with_read(size, |read| { + // Asked before the bytes are read: a write during or after the read is + // noted under a later asking. `None`: the memory is not write-watched + // (a view, say), and the bytes are read and hashed as before. + let asked = crate::watch::writes(memory as usize, memory as usize + size, false); + let key = (resource as usize, from, held, memory as usize, size); + let seen = SAME + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|map| map.get(&key.0)) + .filter(|s| s.0 == key) + .map(|s| s.1); + if let Some((_, pages)) = &asked + && unwritten_since(seen, pages) + { + SAME_ASKED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return true; + } + SAME_ASKED[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let same = with_read(size, |read| { if crate::host::read_there(memory, read) == 0 { return false; } digest(read) == held - }) + }); + let mut map = SAME.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + match asked.filter(|_| same) { + Some((now, _)) => { + // shortcut: entries of textures let go stay until the map is full. + if map.len() >= 1 << 16 { + map.clear(); + } + map.insert(key.0, (key, now)); + } + None => drop(map.remove(&key.0)), + } + same +} + +/// For [`unchanged`]: by title texture, what its host copy held (the +/// texture, first level, hash, memory and bytes) when its memory was found +/// to hold the same bytes, with the write-watch asking made before that +/// read. While no page of the memory has been noted written after that +/// asking, the memory holds them still: the read and the hash are left out +/// (959 ms of a 5-second line of the pass, on a list-translating thread: +/// the 23:54 run of 2026-11-28). +#[allow(clippy::type_complexity)] +static SAME: Mutex>> = Mutex::new(None); + +/// Since the start: [`unchanged`]'s answers given by the write watch +/// alone, and those read and hashed. +pub(crate) static SAME_ASKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether no page in `pages` (as [`crate::watch::writes`] lists them: +/// page, asking that last found it written) was written after the asking +/// `seen` (none: not known, so it may have been). +fn unwritten_since(seen: Option, pages: &[(usize, u64)]) -> bool { + seen.is_some_and(|at| pages.iter().all(|&(_, write)| write <= at)) } /// Where the levels from `first` on of a title texture are: address and @@ -3934,3 +4051,50 @@ mod alias_copy_tests { } } } + +#[cfg(test)] +mod same_tests { + use super::unwritten_since; + + /// The bytes found the same at an asking stay so while no page of them + /// is noted written after it; not known, they are read again. + #[test] + fn found_the_same_stays_so_until_a_page_is_written() { + // Never found the same: read. + assert!(!unwritten_since(None, &[])); + // Found the same at asking 7, nothing written since tracking began. + assert!(unwritten_since(Some(7), &[])); + // Pages written at or before 7 (7: reported by the asking made + // before that read, so the read had them). + assert!(unwritten_since(Some(7), &[(3, 2), (4, 7)])); + // A page written after it: read again. + assert!(!unwritten_since(Some(7), &[(3, 2), (4, 8)])); + } +} + +#[cfg(test)] +mod reuse_tests { + use super::reused; + + fn desc(width: u32, height: u32, layers_levels: u32) -> [u32; 14] { + let mut d = [0; 14]; + (d[4], d[6], d[7]) = (width, height, layers_levels); + d + } + + /// The two lines of the 2026-11-30 00:29 run are reuse; a view laid out + /// alike, of the same block size elsewhere, or one level further in, is not. + #[test] + fn another_layout_over_copied_memory_is_reuse() { + let bc7 = (1024, 1024, 0x90001); + // BC6H cubemap 512x512 (6 faces, 10 levels) at the BC7's start: 16-byte blocks both. + assert!(reused(0, &desc(512, 512, 0xa0006), bc7, Some((16, 4)), Some((16, 4)))); + // BC1 (8-byte blocks) 20 KiB into a BC3 (16). + assert!(reused(20480, &desc(1024, 1024, 0x90001), bc7, Some((8, 4)), Some((16, 4)))); + // Same layout, or the same block size read as another format: not reuse. + assert!(!reused(0, &desc(1024, 1024, 0x90001), bc7, Some((16, 4)), Some((16, 4)))); + assert!(!reused(0, &desc(1024, 1024, 0x60001), bc7, Some((16, 4)), Some((16, 4)))); + // A level further in (same block size and layers): not taken for reuse. + assert!(!reused(1 << 20, &desc(512, 512, 0x80001), bc7, Some((16, 4)), Some((16, 4)))); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 8153158420..a2a26d7e5f 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -3728,6 +3728,9 @@ pub fn title_memory_freed(at: usize, len: usize) { }; crate::shadow::write_combined_freed(at, len); crate::shadow::gpu_readonly_freed(at, ro_len); + if crate::memattrs::on() { + crate::memattrs::freed(at, if len != 0 { len } else { allocation_end(at, at).saturating_sub(at) }); + } // What is in place there (`crate::inplace`) is let go as well: the // tables forgot it only when the runtime mapped other pages, so after a // free a heap opened on the old memory still answered for the address. diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index efe32e264f..07b5e0e0d4 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -364,6 +364,8 @@ pub extern "system" fn OutputDebugStringW(text: *const u16) { /// the code and the caller, then exits on the host. pub extern "C" fn exit(code: i32) -> ! { tracing::warn!(code, from = %host::callers(), "title exits"); + #[cfg(windows)] + victory_gpu::memattrs::log_at_exit(); host::exit(code) } @@ -375,6 +377,8 @@ pub extern "C" fn exit(code: i32) -> ! { pub extern "system" fn ExitProcess(code: u32) -> ! { tracing::warn!(code, from = %host::callers(), "title calls ExitProcess"); #[cfg(windows)] + victory_gpu::memattrs::log_at_exit(); + #[cfg(windows)] victory_loader::exit_notices(); host::exit_process(code) } diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index f3c0bfe51d..852c07ae6f 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -882,6 +882,7 @@ pub(crate) fn end_title(why: &'static str, then: Box) { "{why}: suspending the title" ); victory_gpu::log_defrag_counters(); + victory_gpu::memattrs::log_at_exit(); // Whoever comes first (the routines or the deadline) runs `then`; the // other waits for it, so the process never ends halfway through. let then = std::sync::Arc::new(Mutex::new(Some(then))); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 6e8aae9b20..00e7da1d43 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -176,6 +176,13 @@ pub extern "system" fn XMemVirtualAlloc( if !base.is_null() { materialize_for(base as usize, size, Touch::TitleCall); } + let attr_key = victory_gpu::memattrs::virtual_key( + protect, + kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M, + kind & PAGES_64K == PAGES_64K, + kind & MEM_COMMIT != 0, + flags & ADDRESS_32BIT != 0, + ); let (lowest, highest) = address_range(flags); let mut requirements = MEM_ADDRESS_REQUIREMENTS { LowestStartingAddress: lowest as *mut c_void, @@ -328,6 +335,10 @@ pub extern "system" fn XMemVirtualAlloc( LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).push((at as usize, size)); } note_protection(asked, kind, flags, at as usize, size); + if !at.is_null() { + victory_gpu::memattrs::allocated(at as usize, size, attr_key); + victory_gpu::procmem::title_virtual_asked(kind & MEM_COMMIT != 0, kind & MEM_RESERVE_PLACEHOLDER != 0, size as u64); + } at } @@ -489,7 +500,11 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { hook => { // SAFETY: the title's own routine of this type. let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) }; - alloc(size, attributes) + let at = alloc(size, attributes); + if !at.is_null() { + victory_gpu::memattrs::allocated(at as usize, size, victory_gpu::memattrs::alloc_key(attributes)); + } + at } } } @@ -501,6 +516,7 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { hook => { // SAFETY: the title's own routine of this type. let free: FreeRoutine = unsafe { std::mem::transmute(hook) }; + victory_gpu::memattrs::freed_block(address as usize); free(address, attributes) } } @@ -510,6 +526,9 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { /// `XALLOC_MEMTYPE_HEAP_CACHEABLE`, every other type graphics or physical /// memory. const MEMORY_TYPE_SHIFT: u64 = 29; +const MEMORY_TYPE_MASK: u64 = 0xf; +const GRAPHICS_WRITECOMBINE_GPU_READONLY: u64 = 0x2; +const GRAPHICS_CACHEABLE_NONCOHERENT_GPU_READONLY: u64 = 0x4; /// `XALLOC_ATTRIBUTES.PageSize` (2 bits at 14): `XALLOC_PAGESIZE_2MB`. const PAGE_SIZE_SHIFT: u64 = 14; const PAGE_SIZE_2MB: u64 = 2; @@ -528,17 +547,27 @@ fn virtual_blocks() -> MutexGuard<'static, std::collections::HashSet> { /// [`XMemVirtualAlloc`]: graphics and physical memory types, and 32-bit /// addresses; heap memory comes from the host heap. fn virtual_block(attributes: u64) -> bool { - attributes >> MEMORY_TYPE_SHIFT & 0xf != 0 || attributes & ALLOC_32BIT != 0 + attributes >> MEMORY_TYPE_SHIFT & MEMORY_TYPE_MASK != 0 || attributes & ALLOC_32BIT != 0 } -/// A block of graphics (or physical, or 32-bit) memory: committed through -/// [`XMemVirtualAlloc`], so the GPU side tracks it as title memory and -/// watches its writes, at the asked alignment (a reservation is aligned to -/// 64 KiB, or to 2 MiB for more; none above 512 KiB is named) and in -/// 2 MiB pages if asked. -// shortcut: the cache attributes of the memory types (write-combined, -// uncached, GPU read-only, non-coherent, executable) are not applied: the -// block is cacheable read-write host memory, as `XMemVirtualAlloc`'s is. +/// The GPU read-only memory types in GDKX `XALLOC_ATTRIBUTES` still allow +/// CPU writes. Use the same GPU protection tracking as explicit virtual +/// allocations, so shader write declarations exclude these pages. +fn allocation_protection(attributes: u64) -> u32 { + let memory_type = (attributes >> MEMORY_TYPE_SHIFT) & MEMORY_TYPE_MASK; + match memory_type { + GRAPHICS_WRITECOMBINE_GPU_READONLY | GRAPHICS_CACHEABLE_NONCOHERENT_GPU_READONLY => { + PAGE_READWRITE | PAGE_GRAPHICS_READONLY + } + _ => PAGE_READWRITE, + } +} + +/// A block of graphics (or physical, or 32-bit) memory committed through +/// [`XMemVirtualAlloc`], aligned as requested and using 2 MiB pages if asked. +/// +/// Host memory stays CPU-writable and write-watched. The cache and execution +/// attributes of these types still use the host's normal allocation policy. fn virtual_alloc(size: usize, attributes: u64) -> *mut c_void { const ALLOCATION_GRANULARITY: usize = 64 << 10; let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f); @@ -558,9 +587,17 @@ fn virtual_alloc(size: usize, attributes: u64) -> *mut c_void { kind |= PAGES_2M; } let size = size.max(1); - let at = XMemVirtualAlloc(std::ptr::null_mut(), size, kind, flags, PAGE_READWRITE); + let at = XMemVirtualAlloc( + std::ptr::null_mut(), + size, + kind, + flags, + allocation_protection(attributes), + ); if !at.is_null() { virtual_blocks().insert(at as usize); + // The same range as `XMemVirtualAlloc`'s: re-keyed to the attributes. + victory_gpu::memattrs::allocated(at as usize, size, victory_gpu::memattrs::alloc_key(attributes)); } at } @@ -596,13 +633,15 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ victory_gpu::procmem::heap_block(layout.size(), true); // SAFETY: the block holds the alignment (at least the header) and then // `size` bytes. - unsafe { + let user = unsafe { let user = block.add(layout.align()); user.sub(HEADER) .cast::() .write(AllocHeader { layout, reservation }); - user.cast() - } + user + }; + victory_gpu::memattrs::allocated(user as usize, size, victory_gpu::memattrs::alloc_key(attributes)); + user.cast() } /// Frees what [`XMemAllocDefault`] returned: a reservation it made is @@ -623,6 +662,7 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, _attributes: u64) { let user = address.cast::(); let header = user.sub(HEADER).cast::().read(); victory_gpu::procmem::heap_block(header.layout.size(), false); + victory_gpu::memattrs::freed(user as usize, header.layout.size() - header.layout.align()); if header.reservation.is_null() { dealloc(user.sub(header.layout.align()), header.layout); } else { @@ -3575,6 +3615,7 @@ extern "system" fn title_virtual_protect(address: *const c_void, size: usize, pr let ok = unsafe { VirtualProtect(address, size, protect, old) }; if ok != 0 { note_gpu_protection(address as usize, size, protect); + victory_gpu::memattrs::protected(address as usize, size, protect); } ok } @@ -3828,7 +3869,13 @@ mod tests { }; // Write-combined, GPU uncached, physical uncached; 16 bytes, 512 // KiB and 64 KiB aligned; the last in 2 MiB pages. - for (memory_type, alignment, page_size) in [(0x1, 0x4, 0), (0xA, 0x13, 0), (0x9, 0x10, 2)] { + for (memory_type, alignment, page_size) in [ + (0x1, 0x4, 0), + (0x2, 0x4, 0), + (0x4, 0x4, 0), + (0xA, 0x13, 0), + (0x9, 0x10, 2), + ] { let attributes = memory_type << MEMORY_TYPE_SHIFT | alignment << ALIGNMENT_SHIFT | page_size << PAGE_SIZE_SHIFT; @@ -5467,6 +5514,21 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + #[test] + fn xmem_allocation_gpu_readonly_is_separate_from_cpu_protection() { + for memory_type in 0..=MEMORY_TYPE_MASK { + let attributes = (memory_type << MEMORY_TYPE_SHIFT) | ALLOC_32BIT | (2 << PAGE_SIZE_SHIFT); + let protection = allocation_protection(attributes); + assert_eq!(protection & HOST_PROTECTION, PAGE_READWRITE); + let expected = if matches!(memory_type, 0x2 | 0x4) { + GpuProtection::ReadOnly + } else { + GpuProtection::Clear + }; + assert_eq!(classify_gpu_protection(protection), expected, "memory type {memory_type:#x}"); + } + } + #[test] fn gpu_protection_page_alignment() { assert_eq!(page_aligned_range(0, 0x1000), None); diff --git a/docs/due-hot-first-ab-2026-11-30.md b/docs/due-hot-first-ab-2026-11-30.md new file mode 100644 index 0000000000..a26fc86309 --- /dev/null +++ b/docs/due-hot-first-ab-2026-11-30.md @@ -0,0 +1,143 @@ +# A/B of `VICTORY_DUE_HOT_FIRST` at 37bce66, and the GDKX contracts behind the next fixes (30/11/2026) + +RTX 5060 8 GB, Ryzen 5 9600X, 16 GB of RAM, Windows 11. Binary built from `37bce66c` exactly (PR #2334 head), in a +checkout of its own (`D:\VIctory-NVIDIA-ab37`). Preset of `docs/prompt-reprise-pr-2334.md` (`--series-s --res 1440 +--dlss quality --framegen 2 --fg-type auto --fps 1000`, `VICTORY_LOG=info`, `VICTORY_MEM_ATTRS=1`, +`VICTORY_SAMPLED_MARKS=1`, …), each run with its own `VICTORY_CACHE_DIR` and `VICTORY_DATA_DIR` copied from one +reference copy (4.79 GB cache, 111,951 files, and the saves), so every run starts from the same state. + +## Protocol + +Four runs planned, alternating: default (setting absent), `VICTORY_DUE_HOT_FIRST=0`, default, `=0`. Same save, then +the camera left still for 60 s in the world, so the same shot can be compared. The setting is checked in each log's +switch line. + +The pad replay from v2026.11.29.02 (`VICTORY_INPUT_REPLAY`, 1082df39) was not used: it is not in the PR, and in +replay the recorded readings replace the pad from the first frame, so the menus cannot be driven by hand while +loading times (several minutes) vary too much for a timed replay. + +## Run 1: default (30/11 00:29, log `victory-nvidia-play-20261129-232904-27812.log`) + +Closed by its window, 6 min 51 s. Free RAM at launch **4,060 MiB, with Firefox and Edge open** (the reference runs +had 8,419 and 9,034 MiB). `VICTORY_DUE_HOT_FIRST` absent, as the header shows. + +| Whole log, `scripts/bench.py` | Parent 4c20058 (22:50) | 37bce66 (23:00) | Run 1, 37bce66 | +|---|---:|---:|---:| +| fps p10 / median / p90 (world lines) | 4.7 / 13.2 / 16.2 | 2.3 / 8.3 / 11.3 | 0.7 / 13.7 / 16.7 | +| buffer copies, ms/frame (world) | 56.6 | 106.1 | 267.8 | +| submitting thread, ms/frame | 90.2 | 49.6 | 140.4 | +| card memory in use MB, mean / max | 4,699 / 6,239 | 3,159 / 5,924 | 5,094 / 6,694 | +| texture queue full (no room) | 40 / 54 | 13 / 32 | 50 / 69 | +| textures due, mean / max | 14,582 / 29,016 | 10,860 / 33,042 | 15,967 / 32,805 | +| stale copies / out of VRAM | 0 / 0 | 0 / 0 | 0 / 1 | + +On the whole of run 1: 30 "a texture picked by index changed after its upload with nothing to tell of it" (19 in +the first minute in the world), 6 "prelude upload left out", 2 "HERO LEAD" (below), and 12 "no shared buffer" +(0x8007000E, 5 to 6 MB each, all at 23:31:54) while RAM was short. + +**Limits.** One run of four. With 4 GB free the PC paged: copies cost 268 ms a frame and the p10 fell to 0.7 fps, so +this run measures paging more than the queue's order. The reference runs also had `VICTORY_STARTUP_TEXTURE_WAIT=1`, +this one does not. Nothing here supports or rules out an effect of `VICTORY_DUE_HOT_FIRST`. The three other runs +are still to play, with other programs closed. + +## Run 2: `VICTORY_DUE_HOT_FIRST=0` (00:46, log `victory-nvidia-play-20261129-234620-31988.log`) + +Free RAM 7,721 MiB, Edge open. 45 s window from the first line at 2,000 draws or more: + +| 45 s window | Run 1, default | Run 2, `=0` | 37bce66 (23:00) | 4c20058 (22:50) | +|---|---:|---:|---:|---:| +| fps p10 / median | 0.2 / 0.7 | 1.5 / 4.2 | 1.9 / 8.3 | 2.6 / 5.6 | +| copies, ms/frame | 1,344 | 173 | 105 | 85 | +| submitting thread / refreshes, ms/frame | 750 / 436 | 211 / 96 | 109 / 56 | 206 / 133 | +| textures due, mean | 14,060 | 19,931 | 27,960 | 27,844 | +| "changed after its upload", "prelude left out" | 0, 0 | 3, 0 | 0, 0 | 4, 1 | + +The spread from RAM and route is far larger than any effect of the setting: not conclusive. No visual note in the +same shot for these two runs. + +## `VICTORY_PORT_CONSTANTS=1` on the same binary (01:06, log `victory-nvidia-play-20261130-000621-18648.log`) + +Unattended: Enter sent to the window from 10 s after launch every 15 s until the title left its waiting screen, 60 s +in the world, closed by its window. Free RAM 8,237 MiB. 0 stale copies, 0 out of VRAM. `xmem::arrange()` gave the +2,944 pages of the 32-bit graphics heap their section's slices in address order (`not_fresh=0`), the 185 MB heap +opened in place, and the 174 MB title buffer in it lost its host copy: class 7 went from 174.1 MB of host copies and +26.4 GB refreshed on the submitting thread (run 2) to 0.1 MB and 0.1 MB; host copies in the PC's memory from about +4.2 GB to 3.2 GB; refreshes on all threads in the last lines from 77–89 to 56–60 ms a frame. The 45 s window at world +entry (streaming) does not show a gain yet: one short run. A first try with a single Enter at 10 s stayed on the +waiting screen for 12 minutes and was closed. + +### Longer unattended pair: the cost moves to the GPU (01:10 and 01:15) + +Logs `victory-nvidia-play-20261130-001036-22964.log` (without) and `...-001529-31428.log` (with), 180 s still in +the world each, closed by the window, 0 stale copies, free RAM 9,255 and 10,356 MiB. Steady state (60–180 s): fps +median 16.5 → **8.5**, CPU copies 96.3 → 23.6 ms, **GPU 3.0 → 50.0 ms**, "changed after its upload" 5 → 63. The +in-place heap is the PC's RAM, so the shaders reading the 174 MB buffer go over PCIe (about 10 GB/s against about +430 GB/s from VRAM on this card). **`VICTORY_PORT_CONSTANTS=1` is a regression as it is; do not turn it on.** It does +show that about three quarters of the steady-state copy time is this one heap. Next: keep the heap in place as a +source only, and carry the bytes the title wrote into the card copy with the GPU's copy engine. + +## `VICTORY_REFRESH_BESIDE=1` on the same binary (01:25, log `victory-nvidia-play-20261130-002539-20808.log`) + +Carrying the bytes into the card copy with the GPU's copy engine was dropped: the CPU side of a card copy is also the +reference of the three-way merge that lands what shaders wrote, and making the title's memory that reference would +let an old card value overwrite a fresh title write. `VICTORY_REFRESH_BESIDE=1` (already in the PR) keeps the copies +where they are and runs them on the kept threads, waited for only where order requires. + +Same protocol as the unattended pair, compared with its run without (`...-001036-22964.log`): 180 s still in the +world, closed by its window, 0 stale copies, 0 out of VRAM, 0 ERROR lines. + +| | Without | `VICTORY_REFRESH_BESIDE=1` | +|---|---:|---:| +| steady state (60–180 s): fps p10 / median / p90 | 6.5 / 16.5 / 17.6 | **16.7 / 17.5 / 18.8** | +| steady state: ms/frame mean | 172 | **57** | +| steady state: copies, submitting thread, refreshes (ms/frame) | 96.3, 79.2, 46.6 | 32.7, 55.1, 28.9 | +| steady state: "changed after its upload", queue full lines | 5, 195 | **150**, 342 | +| world entry (45 s): fps p10 / median, copies ms | 1.4 / 4.2, 155.7 | 0.6 / 3.6, 278.4 | + +The lows rise sharply in steady state (fewer long frames). World entry is not better in this single pair. Late +texture changes grow from 5 to 150: whether that is more frames uploading more, or the order of uploads against +refreshes running beside, is not established yet, and it is the first thing to check before recommending the switch. + +## A reproducible texture defect: a placed view over a copied texture ("HERO LEAD") + +Two lines of run 1: + +| | View | Texture the host copied into | +|---|---|---| +| 1 | BC6H (95), 512×512, 6 levels, at 0x638400000, offset 0 | BC7 (98), 1024×1024, 1,441,792 bytes copied, at 0x638400000 | +| 2 | BC1 sRGB (72), 1024×1024, at 0x706205000, offset 20,480 | BC3 sRGB (78), 1024×1024, at 0x706200000 | + +A first reading took this for a GPU copy the view never saw. It is not: both are **memory reused** by another +texture. Case 1 is a 6-face cube map with 10 levels at the start of a 1-face texture with 9 levels; case 2 has +8-byte blocks in a texture of 16-byte blocks. Views that *are* the copied texture are already served from it +(`texture_at`: same layout, or same size and block size through a GPU copy of the levels), and filling these two +from title memory is right; carrying the copy's bytes into them would show wrong texels. + +The real risk is elsewhere. Textures made for views live for the whole run, so the copied texture's address stays +in `HOST_WRITTEN_AT`. A **later** view with the old texture's layout at the same address (a streaming pool) would be +sent back to the old copy and show the wrong texture. `VICTORY_HOST_WRITTEN_REUSE=1` (off by default, branch +`claude/placed-view-copy`, 955c9633, `docs/placed-view-hero-lead.md`) forgets that address when a view of another +layout lands on it; the log then says "a placed texture view of another layout lies in the memory of a texture the +host copied into: the memory holds another texture now" at INFO, and HERO LEAD stays only for unclassified cases. + +The 30 "changed after its upload" are not this mechanism: they are writes by the title (19 when entering the world, +painted by another view within 4 to 17 frames; 11 on two 55 KiB textures rewritten every ~13 frames). The existing +`VICTORY_PAINTED_EVERY` addresses them and was not set; `=4` is the value to try. + +## GDKX contracts checked (Markdown docs of the user's GDKX kit, nothing copied into the repository) + +- **`XALLOC_ATTRIBUTES`**: ObjectType 14 bits, PageSize 2 (0 = 4 KB, 1 = 64 KB, 2 = 2 MB), AllocatorId 8, Alignment + 5 (log2), MemoryType 4, Address32BitMapping 1. MemoryType 0x2 and 0x4 are the GPU read-only types. Direct3D's + allocations carry AllocatorId 128 and an object type (resource, dynamic resource, staging, shader, tiled…), but + here Direct3D is ours, so no such allocation reaches XMem. +- **`XMemVirtualAlloc`**: `PAGE_GRAPHICS_NOACCESS` 0x800, `_READONLY` 0x1000, `_READWRITE` 0x2000, `_EXECUTE*` + 0x4000–0x10000, `_COHERENT` 0x20000, `_NOCACHE` 0x40000, beside the host protection bits. +- **`XMemMapPhysicalPages`**: the range must be reserved first with `MEM_RESERVE`, 64 KB or 2 MB pages and + `XMEM_MAPPABLE`. Pages take their reservation's protection, mappings of the same pages must agree on caching, and a + null page array decommits. In the game, the 185 MB below-4 GB graphics heap is one physical allocation mapped in an + order that is not the addresses' (3rd, 4th, 1st, 2nd part), which is why the in-place port refuses it. + `VICTORY_XMEM_ORDERED` (in progress) gives the pages their section offsets in address order at first map. +- **Sampler feedback**: `D3D12_SAMPLER_FEEDBACK_TIER_XS` (0, 0.9 = 90, 1.0 = 100, 1.x = 101 on Series consoles), + `CreateSamplerFeedbackUnorderedAccessView(X)`. We report tier 1.0 (`device.rs`), and in run 1 the game called no + method we leave unimplemented ("method not implemented" is logged once per slot, and appears nowhere). So sampler + feedback is not what keeps textures low or late in this scene. diff --git a/docs/gdkx-xmem-gpu-readonly.md b/docs/gdkx-xmem-gpu-readonly.md new file mode 100644 index 0000000000..33ff8f8b78 --- /dev/null +++ b/docs/gdkx-xmem-gpu-readonly.md @@ -0,0 +1,7 @@ +# Preserve GPU read-only XMem allocation types + +The GDKX `XALLOC_ATTRIBUTES` reference supplied for this work distinguishes the GPU access permissions of memory types from the CPU cache policy. `GRAPHICS_WRITECOMBINE_GPU_READONLY` (type 2) and `GRAPHICS_CACHEABLE_NONCOHERENT_GPU_READONLY` (type 4) can be written by the CPU and read by the GPU. + +The Windows default allocator now carries that GPU permission into the existing virtual allocation path. Windows still gives the title writable, write-watched CPU memory. The renderer can omit the read-only pages from the potential writes it tracks for shader UAV views. This avoids scheduling copy-back bookkeeping for those pages, including when a view spans both read-only and writable pages. Reprotection and release use the existing range cleanup. Custom allocator hooks and explicit GPU copy destinations keep their current handling. + +This patch does not change heap placement. The previous RTX 5060 bandwidth measurement motivates a future `GPU_UPLOAD` experiment, which also needs a way to handle mapping and protection changes. To isolate this change in play, compare with its parent using the same start and settings. Record whether types 2 and 4 actually back host copies, the `VICTORY_GPU_RO_SKIP` clipped bytes, submission time, and stale-copy warnings before claiming a gain. diff --git a/docs/placed-view-hero-lead.md b/docs/placed-view-hero-lead.md new file mode 100644 index 0000000000..36330d9a10 --- /dev/null +++ b/docs/placed-view-hero-lead.md @@ -0,0 +1,40 @@ +# « HERO LEAD » et « changed after its upload » dans la partie du 30/11/2026 à 00:29 (exe 37bce66) + +Log : `victory-nvidia-play-20261129-232904-27812.log` (chez l'utilisateur, hors du dépôt). + +## HERO LEAD : de la mémoire réutilisée, pas une copie manquée + +`texture::placed_in_host_written` (appelé par `resource::texture_at` quand une vue placée crée sa ressource) signale +une vue posée dans la mémoire d'une texture où l'hôte a copié (`HOST_WRITTEN_AT`). Les cas où la vue *est* la +texture copiée sont déjà traités avant ce point : +- même mise en page : `texture_at` rend la texture copiée (`host_written_like`, `VICTORY_PLACED_COPIED`) ; +- même taille et même taille de bloc, autre format : niveaux recopiés sur le GPU (`host_written_block_like`, `seed_later`). + +Les deux lignes de la partie ne sont ni l'un ni l'autre : +1. une cubemap BC6H 512×512, 6 faces, 10 niveaux, au début d'une BC7 1024×1024, 1 face, 9 niveaux : même bloc de + 16 octets, mais rien d'autre en commun ; +2. une BC1 (blocs de 8 octets) 20 Kio plus loin dans une BC3 (16 octets). + +Ce sont d'autres textures, posées dans une mémoire que le titre a réutilisée. Les remplir depuis la texture copiée +afficherait les anciens texels lus dans un autre format : le correctif proposé (copie GPU texture → buffer → +texture) serait faux ici, je ne l'ai pas fait. Les remplir depuis la mémoire du titre est juste, si le titre l'a +remplie lui-même. L'entrée reste dans `HOST_WRITTEN_AT` parce que les textures faites pour des vues vivent toute la +partie et ne passent jamais par `forget`. + +Le vrai risque est ailleurs : tant que l'entrée reste, une vue future de la même mise en page que l'ancienne +texture, à cette adresse (un pool de streaming à emplacements fixes), est renvoyée vers l'ancienne copie et montre +la mauvaise texture. `VICTORY_HOST_WRITTEN_REUSE=1` (éteint par défaut) oublie l'adresse dès qu'une vue d'une autre +mise en page la réutilise : autre taille de bloc, autre nombre de faces, ou d'autres dimensions au début. Une vue +plus loin, de même bloc et de mêmes faces, peut être un de ses niveaux : elle n'est pas prise pour une réutilisation. + +## Les 30 « changed after its upload » : le titre écrit sa mémoire, pas une copie GPU + +Une copie GPU va dans la texture hôte et ne touche jamais la mémoire du titre. Une seule relecture (`texback`) dans +la partie. Ces 30 lignes sont donc des écritures du titre (CPU ou DMA) dans la mémoire de textures déjà envoyées, +que la nouvelle vérification de la passe retrouve (empreinte de 48 Kio) : +- 19 à l'entrée dans le monde, 4 à 17 images après l'envoi, sur des textures dont les pages sont aussi montrées + ailleurs (`blocks_shown_elsewhere` jusqu'à 127) : le titre les peint par une autre vue ; +- 11 vers 23:34 sur deux textures de 55 Kio (0x95d580000, 0x95d600000), réécrites toutes les ~13 images. + +C'est le cas que `VICTORY_PAINTED_EVERY=` traite déjà (`draw.rs`), et il n'était pas réglé dans cette +partie. À essayer : `VICTORY_PAINTED_EVERY=4`. diff --git a/docs/ram-prive-2026-11-29.md b/docs/ram-prive-2026-11-29.md new file mode 100644 index 0000000000..80f2b5c0b6 --- /dev/null +++ b/docs/ram-prive-2026-11-29.md @@ -0,0 +1,105 @@ +# Le privé engagé de la partie H (29/11), et ce qu'on peut en reprendre + +Sources locales : le log de H (`victory-nvidia-play-20261129-115844-29880.log`, heures UTC), ses lignes +`process memory`, `process memory beside the census` et `host copies of title memory now` (`shadow::live_bytes`), +et le relevé `mem-watch.ps1` (`victory-mem-20261129-125843.csv`, heures locales, UTC+1). PC : 16 Go +de RAM (15 507 Mo vus), RTX 5060 8 Go, Series S, DLSS qualité, génération d'images x2. + +## Au fil de la partie + +| UTC | Privé | En mémoire | Titre (privé) | Hôte (privé) | Copies hôte (n / Mo) | VRAM utilisée | RAM utilisée par la carte | Engagé du PC | RAM libre | +|---|---|---|---|---|---|---|---|---|---| +| 12:06:18 | 7 968 | 3 588 | 3 106 | 4 603 | 3 / 178 | 1 358 | 650 | 36 920 / 53 765 | 702 | +| 12:07:26 | 18 659 | 5 599 | 3 211 | 15 230 | 5 548 / 4 337 | 5 570 | 5 164 | 46 734 | 311 | +| 12:09:40 | 19 358 | 7 218 | 3 224 | 15 857 | 5 182 / 4 140 | 5 217 | 5 183 | 46 911 | 593 | +| 12:12:54 | 19 679 | 4 821 | 3 224 | 16 329 | 5 249 / 4 165 | 5 502 | 5 330 | 47 736 | 494 | +| 12:15:01 | 19 851 | 7 339 | 3 224 | 16 336 | 5 123 / 3 854 | 5 861 | 4 996 | 46 852 | 293 | +| 12:18:23 | **21 156** | 5 546 | 3 224 | 17 610 | 5 387 / 4 220 | 6 354 | 5 442 | 48 721 | 299 | + +(Mo. « En mémoire » : le working set. Les deux colonnes de la carte sont, d'après le log, comptées dans le privé.) + +`mem-watch.ps1` : 160 relevés en jeu, **privé max 21 542 Mo** (13:18:00), **RAM libre min 152 Mo** (13:07:45). Le +privé fait +10,7 Go en 50 s à l'entrée dans le monde (12:06:18 → 12:07:26), puis monte encore de 2,5 Go en 11 min. + +## Où sont les 21,2 Go à la fin (12:18:23) + +| Poste | Go | RAM réelle ? | +|---|---|---| +| Mémoire de la carte utilisée (WDDM la compte dans l'engagé du processus) | 6,35 | non, sauf éviction | +| RAM du PC utilisée par la carte (ressources NON_LOCAL) | 5,44 | oui | +| — dont copies hôte lues par la carte dans la RAM (fenêtres et buffers) | ≈ 2,86 | oui | +| — dont **côté CPU des copies carte** (miroirs, `VICTORY_CARD_CPU_HEAP=0`) | **≈ 1,14** | oui | +| — dont staging des textures, uploads, le reste du pilote | ≈ 1,4 | oui | +| Engagé par le titre (adresses console) | 3,22 | oui, en partie | +| Shaders (conteneurs et traductions) | 0,32 | oui | +| Reste à adresses hôte : tas, piles, pilote, DLSS/FG | ≈ 5,8 | en partie | + +- Les copies : `host copies of title memory now: 5389 copies, 4004 MB in the PC's memory, 1140 MB on the card`. Les + 4 004 Mo comptent chaque copie une fois, par son côté CPU : les 1 140 Mo des copies carte ont donc aussi + 1 140 Mo de miroir dans la RAM, qui ne font que répéter la mémoire du titre. +- 0 Mo de snapshots ou de hashes de comparaison : ce n'est pas là. +- La croissance des 11 dernières minutes (+2,5 Go) est pour 0,8 Go la VRAM, 0,3 Go la RAM de la carte, et pour + ≈ 1,4 Go le « reste » (tas, pilote). À regarder avec `VICTORY_PROCESS_HEAPS=1`, qui ajoute à la ligne ce que + les tas gardent libre. +- Attention : le « unnamed 6038 MB » de la ligne `process memory` n'est pas un vrai poste : il soustrait du privé les + 7,3 Go de sections mappées du titre, qui ne sont pas du privé. +- L'engagé du PC est à 48,7 Go sur 53,8 : la limite est proche, et la RAM physique aussi (300 Mo libres). + +## Ce qui est fait sur cette branche : le miroir des copies carte + +Le miroir sert de référence (envois des seuls mots changés, fusions des écritures des shaders, vérification +`VICTORY_REFRESH_CHECK`) : on ne peut pas le supprimer sans revoir ces chemins. Deux réglages, éteints par défaut : + +1. **`VICTORY_CARD_CPU_HEAP=1`** (existait déjà, jamais mesuré en jeu) : le miroir passe d'un buffer D3D12 de RAM + partagée avec la carte à de la mémoire privée paginable (la carte lit le snapshot de l'envoi, pas le miroir). Il + faut `VICTORY_SEND_OWN` (actif par défaut et dans H) et pas `VICTORY_UPCOPY_CHECK=1`. Attendu : « PC's memory the card uses » + −≈ 1,1 Go ; le privé bouge peu, mais les pages jamais touchées ne prennent plus de RAM, et Windows peut sortir + les autres du working set sous pression. +2. **`VICTORY_CARD_CPU_LAZY=1`** (nouveau, avec le précédent) : le miroir est seulement réservé, et chaque bloc de + 64 Ko est engagé au premier accès (un gestionnaire d'exceptions vectorisé, placé en tête, engage la page et + relance l'accès ; les copies du noyau dans le miroir, `Shadow::copy`, engagent avant). Une page engagée ainsi + lit des zéros, comme un miroir neuf : rien ne change pour ceux qui le lisent. Attendu : privé −0,3 à 0,7 Go, + par analogie avec les fenêtres, dont 1 988 Mo sur 3 236 seulement avaient été copiés + (`docs/unified-memory-audit.md`, U4). La ligne `process memory` dit désormais + `lazy CPU mirrors X MB reserved and Y MB committed` : X − Y est le gain exact. + +Ce qui a été vérifié dans le code (tests `shadow::lazy_mirror::tests`) : + +- Les lectures et écritures du miroir passent par des memcpy utilisateur : envois (`send::take`, `copy_snapshot` sur + les threads gardés), `snapshot_private_ranges`, fusions de `land` (`safecopy`). Un test lit un miroir non engagé + depuis un autre thread avec `copy_snapshot`, et un autre avec `safecopy::copy` : il obtient des zéros, sans échec. + Notre gestionnaire est installé après celui des gardes (`watch`), donc il passe devant lui. +- La seule écriture du noyau dans le miroir est `Shadow::copy` (`copy_mapped`), et elle engage les pages avant. + Aucune lecture du noyau ou du pilote ne part du miroir : `write_mapped` part de `Vec`, et la carte ne lit que des + buffers d'upload. +- `VICTORY_REFRESH_CHECK=1` relit le miroir sur la plage qui vient d'être copiée, donc engagée : la comparaison + avec la mémoire du titre reste la même qu'avant. +- Le gestionnaire n'alloue rien. Il ne prend qu'un verrou, celui de la table des miroirs, qu'aucun thread ne tient + pendant qu'il touche un miroir. + +Limite (`shortcut:` dans le code) : ce qui est engagé le reste jusqu'à la fin de la copie. L'étape suivante, si le +gain se voit, est de décommiter ce qui est envoyé et n'a pas changé. + +## Les ≈ 2,9 Go de copies hôte lues dans la RAM + +Ce sont des buffers D3D12 que la carte lit : pas de réservation paresseuse possible, D3D12 les engage et les met à +zéro en entier. Les leviers existent déjà, tous éteints par défaut, aucun mesuré sur ce PC : + +- `VICTORY_WINDOW_KB=1024 VICTORY_WINDOW_TAILS=1` : déjà dans H. +- `VICTORY_INPLACE=1` : ouvrir les fenêtres sur la mémoire du titre elle-même, sans copie. C'est le seul qui + supprime ces Go. Risque connu (U5) : un `VirtualFree` du titre sur une fenêtre ouverte échoue (erreur 87). +- `VICTORY_CARD_WINDOWS_MB` / `VICTORY_WINDOWS_BAR_MB` : déplacent des fenêtres sur la carte. Sur 8 Go, c'est en + concurrence avec les textures (6,35 Go déjà utilisés) : à ne pas essayer en premier. + +## À mesurer (par le manager, avec l'accord de l'utilisateur) + +Mêmes réglages que H, une partie de 10 min, `mem-watch.ps1` lancé à côté, chacune comparée à H : + +| Partie | Réglages ajoutés | À regarder | Attendu | +|---|---|---|---| +| H1 | `VICTORY_CARD_CPU_HEAP=1` | « the PC's memory the card uses », working set, RAM libre min | −1,1 Go de RAM de la carte, privé ≈ égal | +| H2 | `VICTORY_CARD_CPU_HEAP=1 VICTORY_CARD_CPU_LAZY=1` | `lazy CPU mirrors … reserved and … committed`, privé max | privé −0,3 à 0,7 Go | +| H3 | H2 + `VICTORY_PROCESS_HEAPS=1` | « the process's heaps hold … free but kept » | dit ce qu'est le « reste » qui monte | + +Dans les trois : 0 copie périmée avec `VICTORY_REFRESH_CHECK=1` (déjà dans les réglages de H), et la ligne +`CPU mirrors in pageable process memory` présente (elle prouve que le chemin privé est pris). diff --git a/docs/refresh-ahead-study.md b/docs/refresh-ahead-study.md new file mode 100644 index 0000000000..cd80d5b1ff --- /dev/null +++ b/docs/refresh-ahead-study.md @@ -0,0 +1,273 @@ +# Taking work off the submitting thread: a study + +Study only, no production code. Base: `tools/bench-summary` (80efdb7) = release v2026.11.27.9 + `scripts/bench.py`. +Machine: Ryzen 5 9600X (6 cores / 12 threads), RTX 5060 8 GB, 16 GB, Windows 11. +Log: `victory-nvidia-play-20261128-021001-14692.log` (Series S, DLSS quality, frame generation x2, `VICTORY_TEXTURE_POOL=0`). + +## 0. In one paragraph + +The submitting thread (`VICTORY_ASYNC_SUBMIT`) is the frame: in the world it works 53 ms of a 56 ms frame, and +the card is busy 2.4 ms. The largest part is the **refreshes of buffer host copies** (14.7 ms in the world, 41 ms +in the new area at 02:17-02:18, up to 244 ms in one bad second). They already run on the kept helper threads, but +the thread waits for them inside the submission. Each submission waits about 10 deep in the line before our thread +prepares it, about a third of a frame. During that wait the bytes it reads are final, as the title sees it +(`queue/behind.rs:23-31`). **Recommendation: refresh at the title's submit, on helper threads, while the +submission waits in the line (`VICTORY_REFRESH_AT_SUBMIT=1`).** The submission then finds those pages already +taken and only does the cheap "nothing new" check. GPU detiling (#36) and copy-queue uploads (#60) target parts +that are small in this log. The no-op-check PRs (#318, #614, #126) and #501 cut parts that the recommendation +leaves in place, so they come first or alongside it. + +## 1. The submitting thread's path, today + +From the title's submit to the host's `ExecuteCommandLists`. The parts are the slots of `SPLIT` +(`crates/victory-gpu/src/host.rs:8258`). They are printed by `submit_split_line` (`host.rs:8319`) as +"preparing per frame, the submitting thread". All of them happen inside `Host::submit` (`host.rs:5954`), reached +from `send_late`/`execute_late` (`host.rs:5623`, `5653`) on the behind thread (`queue/behind.rs:267` `serve`). + +### 1.0 Before the submitting thread + +| Step | Where | Thread | Note | +|---|---|---|---| +| Title records lists | `list/thin.rs:699` `translate` | **`VICTORY_THIN` threads** (146-240 ms/frame summed over all threads) | `Step::Refresh` / `Step::GpuWrite` / `Step::Copy`… are pushed into the host list's `Deferred.copies` during translation (`host.rs:7600` `defer_refresh`, `7622` `defer_gpu_write`), under the list's `deferred` mutex (`host.rs:7532`). | +| Title submits | `queue/behind.rs:840` `submit` → `thin::submitted` (`list/thin.rs:332`) closes the lists, `LANE.push` | title thread | Returns at once. Median 10 submissions already in the line, at most 34 (log line `queue::behind`). | +| Heaps' records asked at the title's submit | `heap_marks` (`VICTORY_HEAP_SYNC_AT_SUBMIT=1`) | descriptor helper threads | 12-15 ms of work per frame done off the critical path. The thread waits 0.1-0.2 ms for it. **This is the pattern this study proposes for refreshes.** | +| Textures picked by index | the texture pass (`draw.rs`, `texture.rs`) | pass threads | 489 ms per 5 s in the world (about 5 ms per frame), 1.9 s per 5 s in the new area. Not on the submitting thread. | + +### 1.1 Inside `Host::submit` (in order) + +| # | Part (SPLIT slot) | Code | Depends on | Already on helpers | Locks | +|---|---|---|---|---|---| +| 11 | waiting for the submission lock | `host.rs:5961` | the previous submission's copy-back | — | `Host.submitted` (one submission at a time, from preparation to sending) | +| — | heaps' records begun first | `host.rs:5978` (`VICTORY_HEAP_SYNC_FIRST=1`), `descriptor.rs:265`/`334` | title heap pages at submit | yes: descriptor sync threads | descriptor heaps' own locks | +| 12 | planning steps done on the card | `host.rs:5987` `card_steps` (`host/card_steps.rs`) | flights' declared writes (`line().written`) | no | `line()` | +| 13 | waiting for flights | `host.rs:5991-6008` (`late_blocked` `host.rs:3202`, `relay_wait`, `settle`) | **fences**: flights whose writes this submission reads | the relay/land threads land them (`land.rs`) | `line()` + condvar | +| 14 | heaps' records and the sweep | `host.rs:6013-6079` (`sweep`) | nothing in the air | — | sweep's tables | +| 8, 0 | asking the write watch (finding what to ask, then asking) | `host.rs:6088-6103`: `Batch::copy_spans`, `watch::ask_once` (`watch.rs:543`) → `ask_ahead` (`watch.rs:328`) + `ask_rest` | **title memory at submit time** (kernel dirty bits, reset by the asking) | no (`VICTORY_ASK_EARLY` thread exists, `watch.rs:413`/`461`, off; #127 moves it beside part 12) | journal `RwLock` (`watch.rs:153`/`160`), `Asking::hold_all` (`watch.rs:237`) | +| 1 | title bytes under flights' writes | `host.rs:6104-6125`: `stale_under_flights` (`host.rs:3460`/`8793`), `settle_stale` (`host.rs:5918`) | flights' pending shader writes + title memory | no | `line()`, `Shadow.pending` | +| 2 | **the lists' steps**, which contain: | `host.rs:6128-6149` | | | | +| 2a | refreshes ahead of writes / in front | `Batch::refresh_front` `host.rs:8869`, `refresh_ahead` `host.rs:8953` | title memory at submit; journal | **yes**: `shadow::wide_each` (`shadow.rs:1775`) on `victory-wide-*` threads (`shadow.rs:1650`), 3/8 of logical CPUs = **4 threads here** (`shadow.rs:1641`); the submitting thread waits for the last one | `Workers.jobs` mutex; per copy `Shadow.pending`, `Shadow.copied` (held during the copy, `shadow.rs:4283` `copy_stale`), `Shadow.ranged`; journal read lock | +| 2b | `run_deferred`: Copy / Fill / Placed / Run / GpuWrite / Texture steps | `host.rs:8058` | title memory; a `Step::Copy` writes title memory (`copy_mapped` `host.rs:9126`) and flushes pending refreshes (`title_written`) | fills wide (`Batch::fill`), textures wide (`refresh_textures`) | `Deferred` mutex | +| 2c | flushes of refreshes (`flush_all` `host.rs:9050`, `flush_one` `host.rs:8817` before shader writes) | each copy: `Shadow::nothing_new` (`shadow.rs:4159`) then `Shadow::update` (`shadow.rs:4118`) → `update_free` → `watch::writes` → `copy_stale` → `take_all`/`take` (`shadow.rs:4460`) → `copy_mapped` (`ReadProcessMemory` or `safecopy`, `host.rs:9350`) | title memory at submit; journal numbers | wide from 4 copies; `flush_one` one at a time (0.5 ms, 186 a frame) | as 2a | +| 3 | snapshots | `shadow::take_snapshots` `shadow.rs:1806` (`VICTORY_WIDE_BACK=1`) | — | wide | `SNAPS` | +| 4 | copies in the card's memory | `host.rs:6168-6192`: `picked::declare`, `card_before` (`host.rs:4725`): `shadow::card_dirty` (`shadow.rs:677`), `send::take` (`host/send.rs:193`), records the upload list (28,000 ranges a frame in the world), `placed_copy` | CPU sides refreshed in 2 | no | `QUEUE_ORDER` (`host.rs:2949`, with the relay), `CARD_WORK` (`host.rs:2434`), per copy `card.dirty` | +| 15 | waiting for the heaps' records | `host.rs:6196-6203` `drop(heaps_synced)`, `descriptor::make_waiting` (`descriptor.rs:1526`) | the round begun above | yes | — | +| 5 | sending | `host.rs:6224-6243` `ExecuteCommandLists` + `Signal` | — | — | queue | + +### 1.2 Inputs the refreshes depend on + +- **Title memory as of the title's submit.** The behind module's doc (`queue/behind.rs:23-31`) states that the title + writes no memory a submitted list reads until a fence behind it is reached. Our fences are signalled only when the + flight has landed. So bytes read anywhere between the title's submit and our preparation are the bytes the + console's card would read. +- **Exceptions, written by us during preparation:** `Step::Copy` (title buffer copies done at preparation), `Step::Run` + (our steps) and landings of earlier flights. All of them tell the journal (`watch::wrote` `watch.rs:606`, + `ask_once_end`) or the kernel's dirty bits, so a later refresh copies those pages again. +- **Flights' pending shader writes** (`Shadow.pending`). The refresh copies around them (`shadow.rs:4128-4150`), and + `stale_under_flights` waits where the title also wrote them. + +## 2. Numbers (play log 2026-11-28 02:10, ms per frame, medians) + +Made by a scratch parser over the "preparing per frame", fps, behind, card-clock and texture lines (5 s windows). +"World" = fps lines with at least 2,000 draws (67 windows). "New area" = 02:17:00-02:19:00 (16 windows; 10 of them +have at least 2,000 draws). + +| | World | New area | New area, at least 2,000 draws | Worst window | +|---|---:|---:|---:|---:| +| fps | 17.8 | 8.9 | 7.4 | 1.5 | +| frame | 56.1 | 114 | 157 | — | +| **submitting thread, behind line** | **53.2** | **86.8** | **91.8** | 510 (02:17:58) | +| its submissions (sum of parts) | 51.9 | 85.8 | 89.9 | 500 | +| · asking the write watch | 4.2 | 4.0 | 4.5 | 5.8 | +| · title bytes under flights' writes | 3.7 | 2.2 | 1.8 | 18.0 | +| · **lists' steps** | **22.9** | **55.5** | **56.9** | 330 | +| ·· of which **refreshes** | **14.7** | **41.0** | **41.8** | 244 (02:17:52) | +| ·· of which copies and fills | 3.4 | 4.5 | 5.6 | — | +| ·· rest (step walk, placed, textures 0.9-1.8) | ~4.8 | ~10 | ~9.5 | — | +| · **copies in the card's memory** | **7.0** | **7.7** | **8.4** | 105 (02:17:52) | +| · sending | 1.5 | 1.4 | 1.6 | — | +| · planning steps on the card | 3.6 | 2.2 | 3.0 | 13.5 | +| · waiting for flights | 2.5 | 5.9 | 4.4 | 197 (02:17:58) | +| · heaps' records + sweep / at the end | 1.8 / 0.5 | 3.0 / 0.8 | 3.5 / 0.8 | — | +| refreshes: flushes / spans / known to copy nothing / wide | 36 / 6,286 / 5,292 / 5,586 | 42 / 6,405 / 5,373 / 5,755 | | | +| fps line "copies" (buffer refreshes + copies) | 17.7 ms, 39 MB | 46.2 ms, 68 MB | 48.1 ms, 78 MB | 293 ms, 115 MB | +| fps line "textures" (on the submitting thread) | 0.9 ms, 20 MB | 1.0 ms, 20 MB | 1.8 ms, 32 MB | — | +| texture refreshes, all threads | 6.8 | 7.7 | 12.1 | 73 | +| on the GPU | 2.4 | 5.8 | 4.5 | — | +| card idle behind us ("nothing of ours queued") | 11.9 | 75.7 | 100 | 672 | +| title threads waiting at presents | 7.4 | 37.8 | 24.9 | 846 | +| card copies sent up: MB / ranges | 21.7 / 28,156 | 20.0 / 7,477 | | | +| heaps' records (helper threads) | 15.2 | 20.4 | 28.6 | 42 | + +Reading: + +- The thread is the frame (53 of 56 ms). Each millisecond taken off it is close to a millisecond of frame time, + until the title's own threads become the limit (they wait 7 ms at presents, so there is room). +- **Refreshes are the part that grows in bad moments** (14.7 → 41 ms; MB 39 → 78). About 1,000 of 6,300 refresh + spans actually copy, about 40 KB each. The wall time is about 2.7 GB/s on 4 threads, so this is not memory + bandwidth: it is per-span and per-64 KiB-page overhead (kernel read, journal, locks, waking threads) plus the + wait for the slowest job. +- Copies in the card's memory: 7 ms steady, with spikes to 30-105 ms in the new area (first "before" twins and + new card buffers. "New card memory waited for until mapped" goes from about 100 to about 600 waits a second there). +- Waiting for flights has spikes to 60-197 ms in the new area: the relay waits for the card's copy-back. +- Textures are not the submitting thread's problem in this log (1-2 ms). Their cost is in the pass threads and in + card memory ("no room, new textures wait": 7.6 GB wanted against a 5.1 GB line). + +## 3. Options + +Gains are on the submitting thread, in the world / in the new area, estimated from the table above, not measured. + +### (a) Refresh ahead on helper threads, so the submit only consumes the result + +Two ways: + +**(a1) Continuous: refresh hot copies all the time.** The hot set would come from pages that submissions' askings +found written (`watch::note_hot`, as `VICTORY_ASK_EARLY` does for the asking alone). This would copy bytes while +the title is still writing them. The journal makes it correct by construction: the asking resets the dirty bit +before the read, so a write after it is copied again at submit. But it wastes work on pages that are written many +times a frame, and it competes with the title's threads. `VICTORY_ASK_EARLY` did exactly this for the asking alone +and was "none the cheaper" (run cpu-2, `watch.rs:398-400`). **Not recommended.** + +**(a2) At the title's submit, while the submission waits in the line. Recommended.** When the title submits, the +lists are closed. Once they are translated, their `Step::Refresh` spans are known and their bytes are final +(§1.2). The line holds about 10 submissions (≈ 15-20 ms of lead in the world). A helper walks each submission's +steps, as `refresh_ahead` does (`host.rs:8953`), up to its first step that writes title memory, and refreshes +those copies. Our thread then finds the pages taken: `nothing_new` answers yes from the journal, without copying. + +- Expected gain: most of the 14.7 / 41 ms of refreshes, minus the no-op checks that stay (≈ 2-4 ms, see (d1)) and + minus pages written between the ahead pass and our preparation (by our own `Step::Copy`, landings and `Step::Run`; + those are copied again). Estimate: **-6 to -10 ms in the world (≈ +12-20% fps), -20 to -30 ms in the new area**. + The ceiling is the helper pool: 4 threads now, and the submitting thread's own `wide_each` uses the same pool. +- Correctness risks, and how phase 1 closes them: + - *Stale bytes:* none if the submission still asks and checks at preparation as today. The ahead pass only moves + work earlier, and anything written after its asking is copied again. The journal numbers are monotonic + (`next_asking`), and a write noted during the ahead copy has a higher number (`watch.rs` `wrote`). + - *Torn bytes:* the same argument. A torn read is followed by a newer write mark, so the page is copied again. + - *Copies that shaders write* (`Shadow::written()`): an ahead copy could land in a range that a flight declared + just after the ahead pass looked at `pending`. **Phase 1 skips them**, and every copy with `pending` ranges. + - *Copies in the card's memory* (`carded()`): their CPU side is also written by landings (`land.rs`, `merging` + lock) and taken by `send::take`. **Phase 1 skips them**; phase 2 adds them, read-only ones first. + - *Two threads on one copy:* `copy_stale` holds `Shadow.copied` during its copy (`shadow.rs:4283` → + `take_all`), but the unwatched `copy()` path takes no lock. Phase 1 only takes watched copies (`watched` is + 1 or `GUARDED`), and a `refreshing` flag on the copy makes the ahead pass skip a busy copy. + - *The submission's standing asking:* the ahead pass must not call `ask_once`, `ask_ahead` or `ask_once_end`. + Those manage `Journal.kept`, which is the submitting thread's state. It goes through `Shadow::update` → + `watch::writes`, which answers from the standing asking or asks the kernel itself, as the title's own threads + already do. +- Size: ≈ 250-400 lines: a new file `host/early_refresh.rs`, a hook in `queue/behind.rs:840`, a flag on `Shadow`, + one log line and tests. +- PRs that go that way: **#127** (asking begun beside the planning; same idea, one step and no lead time); the + `VICTORY_HEAP_SYNC_AT_SUBMIT` heap marks (already merged; the same idea for the heaps' records, and it works: + 0.17 ms waited for 12-15 ms of work). + +### (b) GPU detiling / compare (#36), with the card about 90% idle + +- #36 (`VICTORY_GPU_DETILE`, +1,108 lines) detiles texture uploads on the card. **On this log the textures on the + submitting thread are 0.9-1.8 ms**, and texture refreshes on all threads are 7-12 ms, mostly in the pass + threads. Gain for the submitting thread: **≤ 1-2 ms**. It does help the pass threads and streaming, with less CPU + reading and detiling. +- Risk: it adds pooled card-resident linear UAV buffers (`SPARE_LINEAR`) on a card that is already past its line + ("7591 MB against a line of 5140 MB") with the pool off because of an out-of-memory crash. **Not now on this 8 GB + card.** Correctness: a byte-exact WARP test exists. +- GPU *compare* already exists for copies in the card's memory: 344 compare passes and about 200 hash passes a + frame. **#501** (`VICTORY_LAZY_COMPARE_MB`, `VICTORY_LAZY_NARROW`) narrows those passes and cuts "planning steps + done on the card" (7.4 → 1.7 ms on its author's machine; 3.6 ms here). Trade-off: a piece that shaders write for + the first time reaches title memory about 2 frames late. +- A GPU compare of *buffer* refreshes (send the whole page and let the card diff) would trade CPU time for + PCIe bytes. The CPU cost here is per span, not per byte, so it is not worth it before (a2). + +### (c) Copy-queue uploads (#60) + +- #60 (`VICTORY_UPLOAD_QUEUE=`) moves big snapshot uploads to a copy queue. Its own measurements found **no + frame-time gain** on two machines (281 → 278 ms; worse P99 on a 3070). +- On this log the card is not the limit. The cost of "copies in the card's memory" is **CPU time recording 28,000 + ranges** and taking bytes (2.2 ms `send::take`). A copy queue does not remove recording. **Low priority.** + +### (d) Other parts found in the code + +- **(d1) The no-op checks:** 5,300 of 6,300 spans a frame are "known to copy nothing" and are still each a job on + the wide pool, with per-item atomics and locks (`flush_all` `host.rs:9050`, `refresh_front` `host.rs:8869`). + **#318** (journal read guard per chunk, atomic fast paths), **#614** (the same, plus lock-free `copied`, refresh + spans merged on the THIN threads, AVX2 in `take`) and **#126** (`VICTORY_WIDE_CHUNK`, fewer wake-ups). All are off + by default, CPU-only, and leave the output unchanged by construction. They are complementary to (a2): (a2) moves + the copies away, and these make the checks that stay cheap. **#614 overlaps #318** (same `JournalRead` / + `pending_any`); test one of them, not both stacked. Gain: 2-5 ms in the world (guess). +- **(d2) More helper threads:** `wide_threads()` = 3/8 of 12 = 4 here (`shadow.rs:1641`). `VICTORY_WIDE_THREADS=6` + can be tried without code. (a2) also needs helpers, and the title waits 7 ms at presents, so there are free + cores. +- **(d3) Waiting for flights** (2.5 ms; spikes to 197 ms) and **title bytes under flights' writes** (3.7 ms): the + relay's copy-back. #501's `LAZY_NARROW` reduces how often flights block a submission. +- **(d4) The asking** (4.2 ms): **#127** (`VICTORY_ASK_FIRST`) overlaps it with the planning; (a2) also makes it + cheaper, because the kernel finds fewer dirty pages to reset (about 1.4 µs each). +- **(d5) Card memory creation on the critical path:** "new card memory waited for until it is mapped" (60,600 waits, + 8.6 s since the start, the longest 44 ms) and the spikes of copies in the card's memory in the new area. + Creating the "before" twins and upload buffers ahead, or on a helper, is a separate study. +- **(d6) Mapping-lock PRs #59 / #87:** they target lock waits in texture refreshes and streaming. Here the + submission-lock wait is 0.0 ms in the world and texture refreshes are small on this thread. #87 may help the + load spikes (its author measured 202 → 23 ms of lock wait in streaming). Its 8-stripe regression shows it is + sensitive to load. Worth one A/B in the new area, not a priority. +- **#623** (Linux-only, untested on Windows): its write-watch journal (`watch/pages.rs`) and copy + digest parts + touch the same paths as (a2) and (d1). It is too broad to stack with them; take its journal part on its own + only after (d1) is measured. + +## 4. Order and plan + +1. **No code: measure the existing switches and PRs** (sessions already running for them: combo-501-614-318, + threads-6-cores): + `VICTORY_WIDE_THREADS=6`; #614 (or #318) + #126; #501. Each is one A/B with `python -I scripts/bench.py --last 2`. +2. **(a2) `VICTORY_REFRESH_AT_SUBMIT=1`**, phase 1 (read-only, watched, not carded copies), on top of what step 1 + kept. +3. (a2) phase 2: read-only copies in the card's memory, then measure how many spans are left. +4. #127 if the asking is still ≥ 3 ms. +5. (d5) card memory creation off the critical path, for the new-area spikes. +6. #36 and #60 only on a card with room left in its memory, or once textures show up on this thread. + +### Plan for (a2): `VICTORY_REFRESH_AT_SUBMIT` (off by default) + +1. **Switch:** `fn refresh_at_submit() -> bool` in the new `crates/victory-gpu/src/host/early_refresh.rs`, read + with `crate::switch::on("VICTORY_REFRESH_AT_SUBMIT")`. Effective only with `VICTORY_ASYNC_SUBMIT`, + `VICTORY_THIN` and `watch::light()`. Unset: nothing new is called. +2. **Hook:** in `queue/behind.rs:840` `submit`, after `thin::submitted(lists)`, call + `early_refresh::post(recordings.clone(), seq)` (the `Arc<[Arc]>`). `seq` is a number of its own, given here in line order (not `host::STARTED`, `host.rs:6075`, which counts host submissions after `VICTORY_JOIN_PARTS` joins them). +3. **One thread, `victory-refresh-ahead`,** takes posted submissions oldest first. For each one: + - skip it if the behind thread has already taken it out of the line (a "taken" sequence the behind thread sets in `Lane::serve`, `queue/behind.rs:267`); + - `Recording::wait()` (`list/thin.rs:219`), then `back()` → the host list; + - under `deferred()` (`host.rs:7532`), collect `Step::Refresh` spans up to the first `Step::Copy`, `Step::Run` + or `Step::Placed`, as `refresh_ahead` does (`host.rs:8953`); release the lock; + - keep a copy only if it is `!written()`, `!carded()`, watched (1 or `GUARDED`), has no `pending` ranges and is + not `nothing_new` already; + - run `Shadow::update(from, len)` over them with `shadow::wide_each`. It is re-entrant: callers share the pool + and each waits for its own jobs (`shadow.rs:1713`). Before each copy, take its new `refreshing: AtomicBool` + with `swap(true)`; skip the copy if it was already set. +4. **On the submitting thread:** no change in phase 1. Its `nothing_new` answers yes for what was taken ahead. + Optionally take each copy's `refreshing` flag around `Batch::update` (`host.rs:8842`) as well, so that two + threads never copy the same copy at once. +5. **Counters** of its own (not `SPLIT` and not `PREPARING`, so the frame line stays comparable). One line per + frame: "refreshed at the title's submit per frame (VICTORY_REFRESH_AT_SUBMIT=1): N submissions, C copies, MB, + ms on helpers; skipped: begun already, written by shaders, in the card's memory, busy; S submissions reached too + late". +6. **Tests** (`shadow::tests`): + - a copy refreshed ahead, then title memory written, gets the new bytes at the submission's refresh; + - a copy with a pending range is not refreshed ahead; + - the walk stops at the first `Step::Copy`. + Then `cargo test -p victory-gpu --lib shadow:: watch:: host::` and `cargo xtask policy`. +7. **Correctness in the title:** one run with `VICTORY_REFRESH_AT_SUBMIT=1 VICTORY_REFRESH_CHECK=1`. + `refresh_check` (`shadow.rs:4232`) reports copies stale three refreshes in a row; expect none more than without + the switch. Look for texture or geometry flicker in the new area. +8. **Measure:** the same save and the same walk (world, then the new area), `VICTORY_TEXTURE_POOL=0` in both runs, + A = without the switch, B = with it, then `python -I scripts/bench.py --last 2`. Compare world fps, submitting + thread ms, end. In the "preparing per frame" line, expect *refreshes* to fall and *known to copy nothing* to rise + at equal draws. In the new line, check that "reached too late" stays small. Success: refreshes −5 ms or more in + the world, with no new stale lines. + +## Not covered by this study + +- Nothing was run: the game was not launched and no build was made. The gains are estimates from one log. +- The split of the refreshes' own time (kernel read, journal, locks, waking threads) needs a `diagnostics` build + (`copystat` `MoveUs`, `SLOW`); this log is from a release build. +- Whether the kernel's write watch marks pages written by our own `ReadProcessMemory` into title memory (copies at + their place, when no asking stands) is assumed from `copy_mapped`'s use of `watch::writing`. Test it before + phase 2. +- The host list's lifetime: the ahead thread reaches the host list through the recording while the behind thread may + already be preparing, sending or even landing it. The "taken" check and the walk of `deferred()` must happen under + one lock that the behind thread also takes before `send_late`, or the ahead pass must hold the list alive (the + list is reset only after its flight lands). Settle this before writing step 3. diff --git a/docs/refresh-cost-h.md b/docs/refresh-cost-h.md new file mode 100644 index 0000000000..e47706e098 --- /dev/null +++ b/docs/refresh-cost-h.md @@ -0,0 +1,53 @@ +# Pourquoi les remises à jour coûtent 3 fois plus en H qu'en G + +Partie G : log `20261129-113247-26028` (.03 + nos branches). Partie H : capture locale `victory-nvidia-play-20261129-115844-29880.log` +(v2026.11.29.01 + la PR). Moyennes sur les lignes du jeu (thread d'envoi au-dessus de 5 ms par image). + +| Par image | G | H | +|---|---|---| +| Thread d'envoi, ms | 45,3 | 95,8 | +| dont remises à jour (attente des passes) | 20,7 | 48,5 | +| dont copies dans la mémoire de la carte | 5,0 | 13,5 | +| Remises à jour vues / sans rien de neuf | 6 676 / 5 771 | 8 875 / 7 836 | +| Vérifications « rien de neuf », tous threads | 4,8 ms | **0,5 ms** | +| Vraies copies, tous threads | 1 020 en 36 ms | 1 145 en **144 ms** | +| Coût d'une vraie copie | 35 µs | **126 µs** | +| Octets copiés (ligne fps) | 40 Mo | **65 Mo** | +| Débit des copies | 1,63 Mo/ms | 1,32 Mo/ms | +| Copies hôte de la mémoire du titre | 4 314 | 5 163 | +| Fenêtres hors buffers laissées à la soumission | 979 | 2 445 | +| Privé moyen / RAM libre moyenne (`mem-watch.ps1`) | 13,4 Go / 1,8 Go | 18,5 Go / 0,7 Go | + +## Cause + +- **Ce n'est pas l'absence de #614.** Le chemin `nothing_new` de v2026.11.29.01 (`watch::nothing_new_single`, notes lues sans + verrou) est déjà dix fois moins cher que celui de G (0,5 contre 4,8 ms). `VICTORY_NEW_BATCH` (`nothing_new_all`) n'est mis + dans aucune des deux parties. +- **Ce sont les vraies copies : 4 fois plus de temps pour 12 % de copies en plus.** Deux causes s'additionnent : + 1. **+62 % d'octets (40 à 65 Mo par image)**, avec 850 copies hôte et 1 470 fenêtres de plus par image. H est la seule partie + avec `VICTORY_WINDOW_KB=1024 VICTORY_WINDOW_TAILS=1`, que `scripts/play-foxhound.ps1` de v2026.11.29.01 met d'office sur + un PC de 16 Go. Sur la grille de 1 Mo, la même mémoire se trouve dans plusieurs fenêtres, chacune remise à jour à part, et + une queue plus longue est un nouveau buffer rempli en entier (`shadow.rs`, `tails`, `fine`). + 2. **Un débit 19 % plus bas** : 5 Go de privé en plus pour le même working set (5,7 Go), et 0,7 Go de RAM libre. Les copies + touchent des pages sorties vers le fichier d'échange. Ce privé en plus ne vient pas des copies hôte (3,45 contre 3,48 Go) : + c'est le travail de l'agent RAM. +- **Le thread d'envoi fait lui-même la fin de chaque passe.** Dans `Batch::flush_all`, il attend les threads larges, et il + copie seul quand il reste moins de 4 copies. À 126 µs la copie, chaque passe pèse plus lourd. + +## Ce qu'il faut mesurer pour trancher entre 1 et 2 + +Une partie H avec `-More @{VICTORY_WINDOW_KB='4096'; VICTORY_WINDOW_TAILS='0'}`. Si « refreshes » revient vers 20 ms et la +ligne fps vers 40 Mo, la cause 1 domine. + +## Le correctif de ce côté + +`VICTORY_REFRESH_BESIDE=1` (éteint par défaut, `host.rs`) : les copies d'une passe partent sur les threads gardés, et le thread +d'envoi continue ses étapes. Il ne les attend qu'au moment où l'ordre l'exige : + +- avant d'écrire la mémoire du titre sur une page de 64 Kio que lit une copie en cours (copie du titre, `Placed`), et avant tout + `Run`, `Host` ou plan, dont on ne sait pas ce qu'ils lisent ; +- avant que des shaders reçoivent une copie en cours (`GpuWrite`) ; +- avant la passe suivante, et à la fin des étapes, avant les instantanés, les copies vers la carte et l'envoi des listes. + +Il reste toujours au plus une passe en cours. Ligne de log : `refreshes beside the submitting thread per frame +(VICTORY_REFRESH_BESIDE=1)`. diff --git a/docs/rt-partie-e.md b/docs/rt-partie-e.md new file mode 100644 index 0000000000..7cd8d2eb22 --- /dev/null +++ b/docs/rt-partie-e.md @@ -0,0 +1,119 @@ +# Partie E : les draws « ray-tracing builder off », ce qu'ils sont et ce qui manque à l'écran + +Log : `victory-nvidia-play-20261129-103901-3256.log` (perf/integration-4, Series S, RTX 5060 8 Go, +Ryzen 5 9600X). Sources : `crates/victory-gpu/src/pipeline.rs` (`Builder`), `pipeline/make.rs` +(`left_out`), `ambient.rs`, `docs/fork-ray-tracing.md`, `docs/findings.md`. + +## 1. Ce que sont ces passes, et ce qui manque à l'écran + +**Les 4 450 abandons par image ne sont pas des passes qui dessinent.** « ray-tracing builder off » +compte les dispatches compute du constructeur de structures du titre (`XboxBvhBuilder.dll`, +52 programmes). Ils déballent les structures statiques livrées avec les données et construisent +ou recalent les structures dynamiques, chaque image. Ils n'écrivent aucune image. Dans une +nouvelle zone, ils déballent les structures de cette zone : c'est pourquoi le compte monte (déjà +mesuré : 700 à 1 040 par image pendant les premières minutes, puis 180 à 280). + +Les passes qui lancent des rayons sont du compute ordinaire, traduit, et **elles tournent**. Sans +structures, chaque rayon rate. Résultat par effet : + +| Effet tracé par le titre | Ce que donne un rayon qui rate | À l'écran | +|---|---|---| +| Lumière indirecte (sondes d'écran, rebonds) | la lumière du ciel dehors, rien dedans | intérieurs et côtés à l'ombre noirs, **sauf la doublure `VICTORY_AMBIENT`** (le lanceur met 0.8), qui recalcule une estimation à partir de l'image | +| Reflets | le ciel (cube maps, `CS_RayMiss`) ; le screen-space réécrit ce qu'il trouve | reflets du ciel là où il n'y a rien à l'écran ; `VICTORY_AMBIENT_SPECULAR=1` (lanceur) les ramène à l'estimation | +| Ombres tracées des lampes et du soleil | rien ne bloque : éclairé | ombres manquantes, objets qui « flottent » ; c'est déjà la valeur neutre « pas d'ombre » | +| Occlusion tracée | rien ne bloque : AO = 1 | pas d'assombrissement des coins hors du pli de la doublure (`VICTORY_AMBIENT_SHADE`) | + +« pipeline left out on purpose » (4 à 5 par image, plus les ~790 indirects « left out ») : +`CS_RaytracingResolve` ombre les **impacts** des rayons. Sans structures il n'y a aucun impact. +Ces dispatches sont indirects, avec un nombre de groupes pris des impacts. Les laisser de côté +revient donc à les lancer avec zéro groupe : rien ne manque de leur fait. + +**Conclusion pour le point 1 :** aucune passe abandonnée ne laisse une texture vide « comme une +texture pas affichée ». Le repli « valeur neutre » demandé existe déjà de fait : un rayon qui rate +vaut « pas d'ombre » et « AO = 1 », et la lumière indirecte est remplacée par `ambient.rs`. Je +n'ai donc pas ajouté de remplissage : il écrirait ce qui est déjà là. + +Les objets et textures absents ont plus probablement une autre cause, visible dans ce log : +« textures picked by index: the card has no room for more; they wait », sur une carte de 8 Go +avec le pool coupé. C'est la file des textures (`resource.rs`, l'autre agent). + +## 2. Pourquoi le builder est coupé, et ce qu'il coûterait ici + +Il ne tourne qu'avec `VICTORY_BVH_BUILDER=1`. Le commentaire de `pipeline.rs` dit pourquoi : il +reste coupé tant qu'une partie n'a pas montré le constructeur entier et la mémoire du titre par +adresse marchant sur une carte. Ses étapes tournent toutes ou aucune. Une étape lancée sur ce +qu'une étape abandonnée n'a pas écrit écrase les objets voisins du titre (run 98 : le titre est +mort en une seconde). + +Ce qu'il a coûté quand on l'a mesuré (`docs/findings.md`, Ryzen 9 9950X3D 16 cœurs, RTX 5080 +16 Go) : +- 35 → 23,5 fps ; +- thread d'envoi de 26,5 à 44,4 ms par image ; +- les trois premières minutes à 1-4 fps ; +- une image **plus cassée** qu'avant (lumière brûlée, taches noires), parce que les structures + dynamiques se chevauchent. Ce trou, connu, est toujours ouvert. + +Sur une Radeon RX 7900 XTX, il coûtait ~40 ms de carte par image. + +Estimation ici : +- **CPU** : le surcoût est sur le thread d'envoi et l'atterrissage. Il passe déjà 54 ms : compter + 70 ms ou plus, et moins de cœurs pour les threads d'atterrissage. 18 fps deviendraient environ + 12. +- **VRAM** : la mémoire du titre par adresse tient 1,5 Go en 25 arènes, avec leurs copies hôtes, + sur une carte déjà à ~5,2 Go utilisés sur ~6,5 Go de budget. Gros risque de retrouver le + out-of-VRAM que `VICTORY_TEXTURE_POOL=0` avait fait disparaître. + +**Verdict : ne pas l'activer sur ce PC.** Il coûte cher, et l'image est pire tant que le +chevauchement des structures n'est pas réglé. Pour qui veut quand même essayer, la ligne est +`--set VICTORY_BVH_BUILDER=1`. La couche coupe alors la doublure `VICTORY_AMBIENT` (« off while the builder runs »). + +## 3. Les 146 « binding failed » + +Tous dans une seule minute (10:51:56 à 10:52:53, 6 lignes fps sur 164). Juste avant, deux +messages : « no free dynamic descriptor slots: a table is not made » (n=6), puis « a draw whose +descriptor table found no free slots is dropped ». + +La cause : le tas de vues de l'hôte est plafonné à 1 000 000 sur NVIDIA, alors que le titre en +déclare 1 245 184. Les tables refaites par draw prennent alors une zone fixe de 2^18 +(`descriptor::host::DYNAMIC`, 262 144 slots) dans les places du titre. Sur NVIDIA, +`VICTORY_DYNAMIC_SLOTS` ne s'applique pas (`dynamic_slots` rend `DYNAMIC` quand le plafond vaut +`PORTABLE_VIEWS`). Dans un endroit chargé, une image et la précédente ont tenu plus de 262 144 +slots. + +Corrigeable ? Pas sans risque : +- agrandir la zone dynamique prend des places au titre, dont la plus haute vue tourne autour de + 720 000, sur 737 855 restantes ; +- rendre les slots plus tôt touche au cycle de vie des listes. + +Pour 146 draws par image pendant une minute sur 75, je ne propose pas de correctif. Un réglage +`VICTORY_DYNAMIC_SLOTS` valable aussi sur NVIDIA (par exemple 280 000) serait un essai simple, +dans `descriptor/host.rs` : à décider. + +## 4. Ce que change la release v2026.11.29.01 (829188e9) + +Écrit au report sur `port/pipeline` (base 3e9a35f2). + +- **Le builder peut maintenant tourner sur NVIDIA.** Avant `b4e8a757`, trois de ses programmes + (wave64) ne se traduisaient pas sur des vagues de 32. Le builder restait donc coupé + (« missing=3 ») même avec `VICTORY_BVH_BUILDER=1`, et les mesures RTX 5080 de + `docs/findings.md` datent d'avant ce correctif. Le README de main le résume : les draws + abandonnés pour lui passent de milliers par image à un. +- **Le chevauchement des structures dynamiques**, qui rendait l'image pire avec le builder, est + traité par `801070ae` (#689). Les tailles compactées sont répondues à l'appel du builder + (`VICTORY_BVH_SIZE_ANSWER`, actif dès que le builder l'est). +- **Il reste optionnel** : `VICTORY_BVH_BUILDER=1`, éteint par défaut. + +Ce qui change dans mes conclusions : +- L'argument « l'image est pire avec le builder » n'est plus établi. Il date d'avant ces deux + correctifs. +- Le coût sur ce PC reste à mesurer. L'estimation du point 2 (thread d'envoi +15 à 20 ms, + ~1,5 Go de mémoire du titre par adresse sur une carte de 8 Go) n'a pas été remesurée sur + main. +- Verdict révisé : **une partie de test vaut la peine**, sur un trajet court, avec + `--set VICTORY_BVH_BUILDER=1`. À surveiller : out-of-VRAM, « submit thread ms/frame », et la + ligne des abandons par cause (« ray-tracing builder off » doit tomber vers 0). Si la VRAM + tient, l'image gagne les ombres tracées, la lumière indirecte et les reflets du titre, et la + doublure `VICTORY_AMBIENT` s'efface d'elle-même. +- Les zones dynamiques des tas de vues sont aussi revues sur main (`dynamic_slots_for`, + `unparked_room` dans `draw.rs`). La proposition du point 3 est donc caduque : il faut une + nouvelle partie pour voir s'il reste des « binding failed ». diff --git a/docs/rtx5060-texture-pass.md b/docs/rtx5060-texture-pass.md new file mode 100644 index 0000000000..37eb35655b --- /dev/null +++ b/docs/rtx5060-texture-pass.md @@ -0,0 +1,35 @@ +# Skip texture queue ordering after the frame budget runs out + +In [run H](test-results-2026-11-29.md), an RTX 5060 8 GB, Ryzen 5 9600X and 16 GB of RAM ran the Series S profile with DLSS Quality and 2× frame generation. The [texture analysis](textures-h-cause.md) recorded more than 12,000 due slots, frequent budget exhaustion at 8 ms and about 600 ms per five seconds spent before the texture loop preparing due slots. That preparation time covers all passes. The portion that can be saved remains to be measured in game. + +When the frame has already spent its full texture-pass budget, the flat queue still processes remaps and publishes completed uploads. The pass then returns before collecting and ordering the due slots. The decision uses the largest budget the next pass could receive, including catch-up when VRAM and RAM allow it. A pass for a synchronous bake keeps its separate budget. The existing fast path for the indexed queue is preserved. + +## Hardware validation + +Compare this change with `faa1d7cf` using the same save, route and Series S, DLSS Quality and 2× frame generation settings. Use `VICTORY_TEXSPK_PASS_MS=8` for both runs and retain the 1 MiB copy windows from run H. Compare the time spent preparing the texture queue over the same stretch, the pending texture count, FPS p10 and any visible texture delays. A useful run should also record VRAM warnings and stale copies with `VICTORY_REFRESH_CHECK=1`. Run J recorded twelve stale-copy warnings with 4 MiB copy windows, so that setting would make this comparison harder to interpret. + +## RTX 5060 startup test on `0ec72538` + +The player reported several freezes at startup and a missing reflection in eyeglasses. The process closed through its window after about 4 min 22 s. Windows had 4,585 MiB of available physical memory before launch. At frame six, VIctory reported 934 MiB free and about 38 GiB of commit headroom, with 10 MiB of texture staging. The external sampler later recorded 22 MiB free and a peak of 20,609 MiB of private memory. These figures point to severe physical memory pressure early in the run. The low staging use at frame six gives little reason to lower the texture upload budget to address that startup spike. + +The log contained 77 Streamline warnings about a frame interval over 100 ms, 142 notices about textures uploaded again after changing, and a final summary with zero failed host pipelines and zero untranslated shaders. These events do not identify the pass that draws the eyeglass reflection. This run used the default Series S path with the ray-tracing builder off. Compare the same camera and lighting before changing the renderer, and check whether the lens surface is present and only the reflected image is missing. The default reflection estimate is off because earlier play tests showed colour artifacts. + +The launcher inherited `RUST_LOG=warn`, so the run has no FPS, texture queue timing or page-fault counters suitable for comparison. Use `--set VICTORY_LOG=info` for the next measured run and confirm an INFO row is present before starting the route. Record free physical memory before launch, startup time to the same scene, page faults per second, and the `ms taking the slots due` field once gameplay begins. A fresh game uses a different starting scene from run H and needs its own baseline. + +## RTX 5070 community report + +On an RTX 5070 12 GB with 32 GB of RAM, the [community test](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2334#issuecomment-7256031163) reported one compute `0x8007000e` in the cumulative pipeline summary, zero untranslated shaders, and no stale-copy or out-of-VRAM messages. The excerpt includes about 1,750 MiB of free physical RAM, more than 20 GiB of system commit headroom, and substantial texture queue lock waits and paging activity. The summary alone cannot tell whether Direct3D refused the pipeline or the compile guard deferred it before the driver ran. The two previously used the same HRESULT inside the pipeline builder. + +The builder now distinguishes a deferred compile from a driver error. The normal pending queue already retries deferred compiles. Optional diagnostic retries also go through the compile guard. A real driver allocation error retains its HRESULT and now logs available physical memory and commit when Windows can provide them. To identify a repeat, capture the first `host pipeline failed (logged once per key)` line with its shader key and the surrounding `memory guard` and `process memory` records. Keep raw captures outside the repository. + +## RTX 5060 follow-up on `e86a8429` + +The player reported smoother play and difficult transitions during the opening cinematic, and showed multicoloured patches on reflective surfaces. The capture's title bar matches a 2.0 FPS sample at 15:08:30 UTC by both frame time (495.6 ms) and draw count (3,882 per frame). At that sample, 21,251 of 24,086 texture slots were due. The queue accounted for 6,490 MB against a 5,885 MB admission threshold and held back new textures. Free physical RAM was about 626 MB. The frame-preparation sample spent 324.3 ms on title-memory copies and 2.5 ms on texture work. The nearby warnings included one skipped early upload after a texture changed. + +The session closed normally with zero failed host pipelines, zero untranslated shaders and no out-of-VRAM messages. After the capture, 65 stale-copy warning lines appeared, all for the same 50 MiB GPU copy guarded by the CPU. The ordinary submission refresh reported the mismatches. The earlier speculative pass was counted once for this copy, and the log does not establish that it caused the mismatch. The diagnostic now starts a fresh streak when a different overlapping copy owns the address. This does not resolve the observed same-copy mismatches. + +The log confirms that the opaque and transparent reflection miss passes were skipped. It does not identify the pass responsible for the coloured patches. The existing optional **Reflection Estimate** now keeps the miss pass for the layers it can use, with the acceleration-structure builder off. Its default remains off. Test `VICTORY_RAYMISS_KEEP=1` first, on its own and from the same camera and lighting. It restores the game's sky fallback for these reflections and can introduce bright grain on grazing surfaces. Test the estimate separately and check both the glass and the surrounding opaque surfaces for colour artifacts. + +During pressure on a small host, the full address-space census now starts at most once per 15 seconds. The five-second page-fault and memory counters continue. Each full census took around 0.5–0.6 seconds in the capture window and already ran on a background thread. The main transition cost recorded in that window was the game's memory copies. For the next measured intro, isolate guarded copies with `VICTORY_REFRESH_GUARDED=0` and keep the stale check enabled. Try `VICTORY_DSTORAGE_WORKERS=6` separately from this change. The capture used 12 workers, so compare transition frame times as well as total load time. + +For textures, test `VICTORY_DUE_HOT_FIRST=1` separately with the existing shader sample marks. In that mode the queue now classifies each fresh slot only once per pass. Keep the 8 ms texture pass and flat queue for this comparison. If admission remains the limit, a separate `VICTORY_COLD_EVICT_S=60` run can show whether eviction of long-unused indexed textures reduces the wait. Compare the pending count and the time for visible textures to appear, and check for flicker as evicted textures return. diff --git a/docs/startup-texture-wait.md b/docs/startup-texture-wait.md new file mode 100644 index 0000000000..a4b7a67e45 --- /dev/null +++ b/docs/startup-texture-wait.md @@ -0,0 +1,11 @@ +# Adaptive texture wait on the first scene + +Run with `--set VICTORY_STARTUP_TEXTURE_WAIT=1` and frame generation off. The first busy 3D frame starts the loading screen if more than 128 indexed texture slots are due. The title keeps presenting behind the screen so it can discover resources and submit uploads. Video presents bypass the screen. + +The screen releases when the latest texture pass reports at most 128 due slots, when no upload or queue progress is observed for three seconds, or after a ten-second safety limit. The queue includes descriptor slots that may share a texture. Its count does not prove residency of the textures visible in the first shot. The title and its audio can advance while the screen is shown. + +## November 29 local trial + +The trial used a local release based on `v2026.11.29.02` (`1082df39`), an RTX 5060 with 8 GB VRAM, 16 GB system RAM, Series S, 1440p, DLSS Quality, and frame generation off. The screen began with 881 due slots. Uploads continued while new slots arrived. The safety limit released the screen after 10.024 seconds with 14,774 still due. The session later stopped on `0x8007000E` while closing a D3D12 command list. This run exercised the loading screen and its fallback. Whether it improves the opening frames remains unverified. + +The log messages beginning with `startup textures:` record the initial queue size, the wait and its release reason. Compare the first visible frame and its texture issues on a matched route before changing the defaults. diff --git a/docs/test-plan-2026-11-28.md b/docs/test-plan-2026-11-28.md new file mode 100644 index 0000000000..57f87a651b --- /dev/null +++ b/docs/test-plan-2026-11-28.md @@ -0,0 +1,63 @@ +# Plan de test : multithreading, textures et VRAM (RTX 5060 8 Go, Ryzen 5 9600X) + +Six parties de 8 minutes, **même sauvegarde, même trajet** à chaque fois : environ 3 minutes en jeu dans une +zone déjà chargée, puis l'arrivée dans une nouvelle zone. Chaque partie ajoute **une seule** chose à la +précédente, ce qui permet de savoir ce qui a fait gagner ou perdre. Les mêmes options pour toutes : +`--series-s --dlss quality --framegen 2`. + +## Les exes + +| Nom | Chemin | Contenu | +|---|---|---| +| base | `D:\VIctory-NVIDIA-base10\target\release\victory.exe` | `main` 8fc2254 = release v2026.11.27.10, rien de plus | +| int2 | `D:\VIctory-NVIDIA\.claude\worktrees\perf-combo-1-2d9d39\target-int2\release\victory.exe` | `perf/integration-2` : .10 + #614 (toujours actif) + #501 (éteint) + pool coupé sur 8 Go (actif tout seul) + `VICTORY_SUBMIT_PRIORITY` (éteint) + `VICTORY_REFRESH_AT_SUBMIT` (éteint) | + +## Les parties + +| # | Nom | Exe | Ajouté par rapport à la précédente | Ce qu'on mesure | +|---|---|---|---|---| +| 1 | `base` | base | `VICTORY_TEXTURE_POOL=0` | La référence (.10, pool coupé) | +| 2 | `pr614` | int2 | #614 et pool coupé automatiquement | Le gain de #614 (remises à jour sans verrou) | +| 3 | `helper` | int2 | `VICTORY_HELPER_PRIORITY=on` | Les traducteurs repassent sous le thread d'envoi | +| 4 | `lazy501` | int2 | `VICTORY_LAZY_COMPARE_MB=64 VICTORY_LAZY_NARROW=1` | #501 (copies comparées là où elles ont été écrites) | +| 5 | `ahead` | int2 | `VICTORY_REFRESH_AT_SUBMIT=1 VICTORY_REFRESH_CHECK=1` | Les remises à jour faites pendant l'attente dans la file | +| 6 | `submitprio` | int2 | `VICTORY_SUBMIT_PRIORITY=2` | Le thread d'envoi en priorité « highest » | + +La commande (une fenêtre PowerShell, depuis le checkout des [outils de benchmark](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2571)) : + +```powershell +$base = 'D:\VIctory-NVIDIA-base10\target\release\victory.exe' +$int2 = 'D:\VIctory-NVIDIA\.claude\worktrees\perf-combo-1-2d9d39\target-int2\release\victory.exe' +$h = 'VICTORY_HELPER_PRIORITY=on'; $l = 'VICTORY_LAZY_COMPARE_MB=64 VICTORY_LAZY_NARROW=1'; $a = 'VICTORY_REFRESH_AT_SUBMIT=1 VICTORY_REFRESH_CHECK=1' +$jeu = 'C:\Jeu\game.exe' +.\scripts\bench-run.ps1 -Exe $int2 -Game $jeu -Minutes 8 -Variants ` + "base@$base=VICTORY_TEXTURE_POOL=0", 'pr614=', "helper=$h", "lazy501=$h $l", "ahead=$h $l $a", "submitprio=$h $l $a VICTORY_SUBMIT_PRIORITY=2" +``` + +Le script lance chaque partie, compte 8 minutes à partir du dernier `victory.exe` (le redémarrage de +warm-up remet le compteur à zéro), ferme la fenêtre proprement, attend 20 s, passe à la suivante, puis +affiche le tableau de `scripts/bench.py`. **C'est à vous de jouer pendant chaque partie** : charger la +sauvegarde, faire le trajet. + +## Ce qu'on regarde + +- **Plantage ou non** (`end`), `out of VRAM`, échecs du DLSS. +- **fps p10 / médiane / p90** dans le monde, et **submit thread ms/frame** (avec `refreshes ms`). +- Partie 5 : **`stale copies`** doit rester à 0, et à l'écran **aucune texture ou géométrie qui + clignote** en arrivant dans la nouvelle zone. +- Partie 4 : eau, reflets, personnages animés. #501 peut afficher certaines zones avec environ 2 images + de retard. +- Vos impressions à l'écran : saccades, textures en retard. + +## Ce qu'on garde + +Ce qui fait gagner au moins 1 fps de médiane, ou au moins 3 ms sur le thread d'envoi, **sans** plantage, +copie périmée ni défaut visible. Ces changements deviennent les PR à proposer. Les branches de PR prêtes en +local, sur la .10 : + +- `pr/texture-pool-off-8gb` (ccdd922) : pool coupé sur 8 Go, déjà mesuré (plus de plantage). +- `pr/helper-priority` (bbb8120) : `VICTORY_HELPER_PRIORITY=on` par défaut. **Seulement si la partie 3 gagne.** +- `pr/submit-priority` (1225837) : le réglage `VICTORY_SUBMIT_PRIORITY`. **Seulement si la partie 6 gagne.** +- `perf/refresh-at-submit` (41c4aa3, 0c5bc93) : `VICTORY_REFRESH_AT_SUBMIT`. **Seulement si la partie 5 gagne + sans copie périmée.** +- #614 et #501 sont les PR d'autres auteurs : on poste les mesures en commentaire sur leur PR. diff --git a/docs/test-results-2026-11-28.md b/docs/test-results-2026-11-28.md new file mode 100644 index 0000000000..66cf660e75 --- /dev/null +++ b/docs/test-results-2026-11-28.md @@ -0,0 +1,133 @@ +# Résultats des tests du 28/11/2026 (RTX 5060 8 Go, Ryzen 5 9600X) + +Les six parties du [plan de test](test-plan-2026-11-28.md) ont été lancées par `scripts/bench-run.ps1`, de 12 h 07 à 13 h 10, avec les +options `--series-s --dlss quality --framegen 2`. + +## À lire avant les chiffres : les parties n'ont pas montré la même scène + +| # | Partie | Ce qui s'est passé à l'écran | +|---|---|---| +| 1 | `base` | Jouée par l'utilisateur (sauvegarde, puis trajet) | +| 2 | `pr614` | Jouée par l'utilisateur au début ; il est parti pendant la partie | +| 3 | `helper` | Personne aux commandes : Entrée au menu, puis la cinématique d'introduction sans rien toucher | +| 4 | `lazy501` | Comme la partie 3 : Entrée une fois, puis la cinématique d'introduction | +| 5 | `ahead` | Jamais entrée en jeu : restée sur « Sélecteur de profil / Player A ». La Xbox Game Bar était passée devant le jeu et recevait les touches | +| 6 | `submitprio` | Jamais entrée en jeu, pour la même raison | + +Conséquences : + +- **Seule la comparaison 3 → 4 (#501) est valable** : même scène, même façon d'y arriver. +- Les parties 1 et 2 d'un côté, 3 et 4 de l'autre, ne se comparent pas : le trajet joué et la cinématique ne chargent pas autant + la machine. La baisse du thread d'envoi de 62 à 31 ms entre les parties 2 et 3 vient en grande partie du changement de scène, et on ne + sait pas quelle part revient à `VICTORY_HELPER_PRIORITY=on`. +- Les parties 5 et 6 n'ont rien mesuré : 0 ligne « monde » et un thread d'envoi à 0,2 ms. Leurs 24 600 lignes `ERROR` sont toutes le + même message de Streamline (`getRefreshRate: Window handle … is not a valid window`), sans gravité. +- Pendant la partie 5, un second `victory.exe` sans arguments a été lancé à 12 h 57 par l'outil de contrôle d'écran de Claude. Il a été + arrêté environ 30 s plus tard. Il n'a pas écrit de log et n'a pas fermé le jeu mesuré. +- La mesure 1 → 2 (#614) est faite sur le trajet joué, mais l'utilisateur est parti pendant la partie 2. Les deux parties ne couvrent + donc pas tout à fait le même trajet. + +Le prochain banc gagnerait à utiliser la cinématique d'introduction pour toutes les parties : elle est la même à chaque fois et ne +demande qu'un appui sur Entrée, une fois le menu affiché (environ 2 min 30 après le lancement). + +## Le tableau (`python -I scripts/bench.py` sur les 6 logs) + +| | base | pr614 | helper | lazy501 | ahead | submitprio | +|---|---|---|---|---|---|---| +| log | 20261128-111232-15272 | 20261128-112358-14660 | 20261128-113324-14612 | 20261128-114248-26360 | 20261128-115213-27520 | 20261128-120136-19536 | +| scène | jouée | jouée, puis personne | cinématique | cinématique | écran de profil | écran de profil | +| length (min:s) | 9:00 | 9:01 | 8:59 | 9:00 | 8:59 | 8:59 | +| end | cut off | cut off | cut off | cut off | cut off | cut off | +| ERROR lines | 567 | 980 | 1150 | 1381 | 24657 | 24534 | +| stale copies (VICTORY_REFRESH_CHECK) | 0 | 0 | 0 | 0 | 0 | 0 | +| out of VRAM (first at) | 0 (-) | 0 (-) | 0 (-) | 0 (-) | 0 (-) | 0 (-) | +| DLSS failing lines | 0 / 464 | 0 / 460 | 0 / 499 | 0 / 502 | 0 / 535 | 0 / 536 | +| world 5 s lines (>= 2000 draws) | 76 | 72 | 54 | 58 | 0 | 0 | +| fps p10 / median / p90 | 2.9 / 16.9 / 24.0 | 3.6 / 18.4 / 23.5 | 10.7 / 19.3 / 22.0 | 12.7 / 22.7 / 23.5 | - / - / - | - / - / - | +| ms/frame mean | 132 | 117 | 75 | 50 | - | - | +| copies ms (world) | 35.5 | 27.6 | 22.8 | 18.2 | - | - | +| on the GPU ms (world) | 12.6 | 4.6 | 4.7 | 7.5 | - | - | +| draws dropped, no pipeline (world) | 1022 | 907 | 555 | 469 | - | - | +| submit thread ms/frame | 64.6 | 62.3 | 31.0 | 31.0 | 0.2 | 0.2 | +| list steps ms | 35.8 | 33.8 | 14.9 | 15.6 | 0.0 | 0.0 | +| refreshes ms | 26.7 | 25.5 | 10.9 | 10.7 | 0.0 | 0.0 | +| card memory in use MB mean / max | 5381 / 6163 | 5254 / 6027 | 3706 / 5740 | 4023 / 5708 | 1259 / 1261 | 1267 / 1270 | +| budget MB mean / queue line MB mean | 6714 / 5371 | 6711 / 5369 | 6842 / 5473 | 6823 / 5458 | 7127 / 5701 | 7127 / 5701 | +| kept for render targets MB mean | 1842 | 1876 | 2268 | 2187 | 2862 | 2862 | +| texture queue full (no room) | 89 / 98 | 89 / 98 | 59 / 103 | 67 / 103 | 0 / 107 | 0 / 107 | +| textures due mean / max | 4344 / 19674 | 5331 / 21758 | 2804 / 21804 | 3721 / 21357 | 0 / 0 | 0 / 1 | +| frame gen: presents on / frames shown per s | 14.6 / 26.8 | 14.7 / 27.2 | 10.0 / 17.8 | 13.0 / 13.0 | 0.0 / 0.0 | 0.0 / 0.0 | + +`end = cut off` est normal : le script ferme la fenêtre au bout de 8 min, et le jeu, qui ne se fermait pas dans les 60 s, a été arrêté +de force à chaque partie. Le thread d'envoi ne donne pas de colonne « copies » séparée dans `bench.py` : la ligne « copies ms (world) » +est le temps des copies de l'image entière. + +## Partie par partie, par rapport à la précédente + +| Changement | fps médiane | fps p10 | Thread d'envoi | Remises à jour | Copies | Manque de VRAM | Copies périmées | Fin | Comparaison valable ? | +|---|---|---|---|---|---|---|---|---|---| +| 1 `base` (référence) | 16,9 | 2,9 | 64,6 ms | 26,7 ms | 35,5 ms | 0 | 0 | coupée | — | +| 2 `pr614` | +1,5 | +0,7 | −2,3 ms | −1,2 ms | −7,9 ms | 0 | 0 | coupée | À moitié : même trajet au début, puis personne aux commandes | +| 3 `helper` | +0,9 | +7,1 | −31,3 ms | −14,6 ms | −4,8 ms | 0 | 0 | coupée | **Non** : on passe du trajet joué à la cinématique | +| 4 `lazy501` | **+3,4** | **+2,0** | 0,0 ms | −0,2 ms | −4,6 ms | 0 | 0 | coupée | **Oui** : même cinématique | +| 5 `ahead` | — | — | — | — | — | 0 | 0 | coupée | Non : jamais en jeu | +| 6 `submitprio` | — | — | — | — | — | 0 | 0 | coupée | Non : jamais en jeu | + +Ce qu'on observe à l'écran et dans le log : + +- **Partie 4 (`lazy501`)** : une capture en pleine cinématique (personnages animés, contre-jour à travers une vitre grillagée) ne montre + aucun défaut. L'utilisateur n'a rien vu de cette partie, et l'eau et les reflets n'apparaissent pas dans cette scène. Le temps GPU passe + de 4,7 à 7,5 ms, ce qui reste loin du thread d'envoi (31 ms). La génération d'images affiche autant d'images qu'elle reçoit de + présentations (13,0 / 13,0, contre 10,0 / 17,8 dans la partie 3) : c'est à regarder, mais ce n'est pas expliqué ici. +- **Partie 5 (`ahead`)** : `stale copies = 0`, mais avec environ une copie remise à jour par image sur un écran fixe. Le test de copies + périmées n'a donc rien prouvé. On n'a pas pu vérifier non plus s'il y avait des clignotements. +- Aucune partie n'a planté, manqué de VRAM ou eu un échec de DLSS. + +## Verdict, avec la règle du plan + +La règle : on garde un changement s'il fait gagner au moins 1 fps de médiane ou au moins 3 ms sur le thread d'envoi, sans plantage, sans +copie périmée et sans défaut visible. + +| Changement | Verdict | +|---|---| +| #614 (remises à jour sans verrou) | **Pas tranché.** +1,5 fps de médiane mais −2,3 ms seulement, et la mesure est faussée par le départ de l'utilisateur. À refaire sur la cinématique. | +| `VICTORY_HELPER_PRIORITY=on` | **Pas tranché.** Le changement de scène empêche toute conclusion. | +| #501 (`VICTORY_LAZY_COMPARE_MB=64 VICTORY_LAZY_NARROW=1`) | **Gagne d'après la règle** : +3,4 fps de médiane, sans plantage, sans manque de VRAM et sans défaut visible sur la capture. Le thread d'envoi ne change pas, donc le gain vient des copies (−4,6 ms). Il reste à vérifier à l'œil l'eau, les reflets et l'image en retard que le plan signale, sur le trajet joué. | +| `VICTORY_REFRESH_AT_SUBMIT` | **Pas mesuré** : jamais en jeu. | +| `VICTORY_SUBMIT_PRIORITY=2` | **Pas mesuré** : jamais en jeu. | + +## Ce qu'il faut proposer + +- `pr/texture-pool-off-8gb` : reste proposable pour la raison déjà connue avant ces tests (plus de plantage par manque de VRAM sur 8 Go). + Les 6 parties d'aujourd'hui confirment 0 manque de VRAM, mais avec le pool coupé dans toutes, elles n'ajoutent pas de comparaison. +- `pr/helper-priority`, `pr/submit-priority`, `perf/refresh-at-submit` : **à ne pas proposer pour l'instant**, faute de mesure valable. +- #501 : un commentaire avec les chiffres de la comparaison 3 → 4 (texte ci-dessous). +- #614 : pas de commentaire tant qu'on n'a pas de mesure propre. + +Rien n'a été poussé, ouvert ni commenté. Chaque action attend le oui explicite de l'utilisateur, une à la fois. + +### Brouillon de commentaire pour #501 + +> Measured on an RTX 5060 8 GB / Ryzen 5 9600X, v2026.11.27.10 + #614 + `VICTORY_HELPER_PRIORITY=on`, `--series-s --dlss quality +> --framegen 2`, texture pool off. Two 8-minute runs of the opening cutscene with no input, the only difference being +> `VICTORY_LAZY_COMPARE_MB=64 VICTORY_LAZY_NARROW=1`: +> +> | | off | on | +> |---|---|---| +> | fps p10 / median / p90 | 10.7 / 19.3 / 22.0 | 12.7 / 22.7 / 23.5 | +> | copies ms/frame (world) | 22.8 | 18.2 | +> | submitting thread ms/frame | 31.0 | 31.0 | +> | GPU ms/frame | 4.7 | 7.5 | +> | crash / out of VRAM / DLSS failures | none | none | +> +> No visible defect on a mid-cutscene capture (animated characters, backlight through a window). Water and reflections were not in +> that scene, so the "about 2 frames late" case is not checked yet. One run each, so treat the numbers as a first data point. + +## À refaire + +Refaire `base`, `pr614`, `helper`, `ahead` et `submitprio` sur la cinématique d'introduction, en gardant `lazy501` d'aujourd'hui comme +point de comparaison, avec quelqu'un à proximité pour fermer la Game Bar si elle passe devant le jeu. + +Remarque sur la commande du plan : passée par `powershell -File`, la liste `-Variants` est découpée en arguments séparés, et le script +s'arrête sur le paramètre `-Pause`. Les parties ont été lancées en appelant le script dans la même session +(`& .\scripts\bench-run.ps1 ... -Variants ...`). diff --git a/docs/test-results-2026-11-29.md b/docs/test-results-2026-11-29.md new file mode 100644 index 0000000000..d81e3595db --- /dev/null +++ b/docs/test-results-2026-11-29.md @@ -0,0 +1,441 @@ +# Résultats des tests du 28-29/11/2026 au soir (RTX 5060 8 Go, Ryzen 5 9600X) + +Toutes les parties : release v2026.11.28.03 + nos modifications, `--series-s --dlss quality --framegen 2`, même sauvegarde, +trajet joué par l'utilisateur. Les logs sont dans `%LOCALAPPDATA%\victory\logs`. + +| Partie | Log | Exe | Ajouté | +|---|---|---|---| +| A | 20261128-225718-23116 | release .03 seule | rien (pool de textures allumé) | +| B | 20261128-230735-8100 | `perf/integration-3` | .03 + #614 + #501 + pool coupé sur 8 Go + helper priority + `SUBMIT_PRIORITY=2` + `REFRESH_AT_SUBMIT=1` | +| C | 20261128-232925-28724 | `perf/texture-room` (83e18df) | B + `TEXTURE_ROOM_FG_PERCENT=88` + `CARD_ROOM_FOR_TARGETS_MB=1536` | +| D | 20261128-235457-30336 | `perf/integration-4` | B + `REFRESH_AT_SUBMIT=2` + `REFRESH_THREADS=4` + `PIPELINE_ASKED=1` + `TEXTURE_ROOM_MARGIN_MB=1280` + `CARD_ROOM_FOR_TARGETS_MB=1536` | + +## Le tableau + +| | A (.03 seule) | B | C | D (tout) | +|---|---|---|---|---| +| Durée | 3:56 | 8:19 | 12:22 | 9:00 | +| Fin | fermé | fermé | **crash GPU** (device removed) | fermé par nous | +| Manques de VRAM | **1 898** | 0 | 93 | 0 | +| Échecs DLSS | 135 / 207 | 0 | 19 | 0 | +| Copies périmées | — | 0 | 2 | 0 | +| fps p10 / médiane / p90 | 1,6 / 14,4 / 19,0 | 1,8 / 14,5 / 22,8 | 2,1 / 7,1 / 20,9 | 1,5 / 11,4 / 20,5 | +| GPU ms/image | 11,2 | 13,4 | 71,2 | 45,8 | +| Thread d'envoi ms/image | 77 | 100 | 136 | 114 | +| Draws non dessinés / image | 427 | 908 | 1 280 | 1 106 | +| Carte : moyenne / max Mo | 5 724 / 7 066 | 5 096 / 5 883 | 5 290 / 6 945 | 5 152 / 5 961 | +| Ligne de la file des textures Mo | 5 314 | 5 172 | 5 562 | **5 048** | +| File « pleine » | 36 / 43 | 79 / 88 | 111 / 129 | 84 / 95 | +| Textures dues, moyenne | 3 597 | 6 895 | 5 644 | 8 000 | + +Les scènes ne sont pas identiques d'une partie à l'autre : les fps se comparent avec prudence. Plantage, VRAM et textures dues se +comparent bien. + +## Ce qui est acquis + +- **Le pool de textures coupé sur 8 Go** fait toute la différence de stabilité : A manque de VRAM au bout d'1 min, B et D jamais. +- **Aucune copie périmée** dans D, avec les mises à jour en avance sur 4 threads (`REFRESH_AT_SUBMIT=2`). Les 2 de C viendraient + des remappages de pages, pas de l'avance (à confirmer avec la trace ajoutée, 32bba05). + +## Ce qui ne marche pas encore + +1. **Textures qui n'arrivent pas.** La file est pleine dans 84 relevés sur 95, et 8 000 textures attendent en moyenne. + - Dans D, la marge de 1 280 Mo a **baissé** la ligne (5 048 Mo, contre 5 172 à 80 % dans B), parce que le budget n'était que de + 6,3 Go. C'est une erreur de réglage de ma part, et elle a empiré les choses. + - Le fond du problème : sur 5,75 Go utilisés, les textures vivantes ne font que 3,0 Go (1,6 Go remplies par le titre, 1,35 Go de + render targets). Les **2,75 Go restants** (copies de la mémoire du titre sur la carte, DLSS, frame gen…) ne sont pas détaillés. + C'est là qu'il faut trouver de la place. + - Le budget que Windows donne au jeu n'est que de 6,3 Go sur 7,9 : les autres programmes ouverts (navigateur, Claude…) prennent le reste. + - Le passage sur les textures « picked by index » coûte 1,7 s par 5 s, dont 0,96 s à se demander si une copie est à jour. +2. **Objets non dessinés : ce n'est pas la compilation.** Sur 25 relevés à plus de 1 500 draws non dessinés, 19 n'ont **aucun** + pipeline en cours de compilation (`0 being made`). `VICTORY_PIPELINE_ASKED` ne peut donc rien y faire. Ces draws sont abandonnés + pour une autre raison (bind raté, index buffer introuvable, shader non traduit…), et c'est sans doute une bonne partie des + « textures pas affichées ». De 00:02 à 00:04, dans la nouvelle zone, 2 500 draws par image manquent pendant deux minutes. +3. **Freezes.** + - L'attente de mémoire neuve (« new memory waited for ») cumule **78 s sur 9 min**, avec un pic à 1,19 s. + - Le GPU a des pics de 470 à 835 ms (00:02:08, 00:02:50). + - À 23:56:40, les mises à jour sur le thread d'envoi prennent 942 ms, alors que l'avance n'en a fait que 33. Ce qu'elle laisse à la + soumission, ce sont surtout les copies « écrites par des shaders » (2 000 à 3 000 par image) et les vues gardées (~1 000). + +## Ce qui est demandé aux agents + +| Agent | Travail | +|---|---| +| Textures (`perf/texture-room`) | Détailler les 2,75 Go qui ne sont pas des textures, et en libérer. Une ligne jamais plus basse qu'avant : max(80 %, budget − marge). Faire passer en premier les textures proches de la caméra. Alléger le passage « picked by index ». | +| Pipelines (`perf/pipeline-threads`) | Compter par cause les draws abandonnés quand rien ne compile, dans le log du build release, puis corriger la cause principale. | +| Mises à jour (`perf/refresh-parallel`) | L'attente de mémoire neuve (78 s), les pics GPU, et les copies « écrites par des shaders » que l'avance laisse au thread d'envoi. | + +Rien n'a été poussé, ouvert ni commenté. + +## Partie E (29/11, 10:39) : toutes les branches réunies, réglées + +Log `20261129-103901-3256`, exe `perf/integration-4` (f73a1c9), 15 min 48, fermée par l'utilisateur. Réglages : ceux de D, avec en plus +`VICTORY_REFRESH_WHOLE=1 VICTORY_BURY_ASIDE=1 VICTORY_WAIT_RESIDENT_UPLOADS=0`, et `VICTORY_TEXTURE_ROOM_MARGIN_MB=1024` au lieu de 1280. + +| | B (int-3) | D | **E** | +|---|---|---|---| +| Fin | fermé | fermé par nous | **fermé, 15:48** | +| Manques de VRAM / échecs DLSS | 0 / 0 | 0 / 0 | **0 / 0** | +| Copies périmées | 0 | 0 | **1** | +| fps p10 / médiane / p90 | 1,8 / 14,5 / 22,8 | 1,5 / 11,4 / 20,5 | **5,9 / 18,8 / 22,8** | +| ms/image | 221 | 251 | **84** | +| GPU ms/image | 13,4 | 45,8 | **2,1** | +| Thread d'envoi ms/image | 100 | 114 | **54** | +| dont remises à jour | 38,7 | 44,5 | **27,5** | +| Textures dues, moyenne | 6 895 | 8 000 | **4 582** | +| File « pleine » | 79 / 88 | 84 / 95 | 159 / 177 | +| Génération d'images : images montrées/s | 21,7 | 21,2 | **32,5** | + +### Le goulot : le thread d'envoi, et presque rien d'autre + +- Une image dure en moyenne 53 ms (18,8 fps), et le thread d'envoi y passe **54 ms**. La carte, elle, ne travaille que 2 ms. Le jeu est + donc limité par ce seul thread. +- Ses 54 ms par image (moyenne, p90 entre parenthèses) : + + | Poste | ms | + |---|---| + | étapes des listes | 35,6 (66,6) | + | dont remises à jour | 27,5 (53,4) | + | dont copies et remplissages | 5,7 | + | copies en mémoire carte | 5,6 | + | write watch | 3,1 | + | reste | ~4 | + +- **Les remises à jour** : 9 700 par image en 50 passes, dont **8 650 (89 %) ne copient rien**. 9 100 sont faites sur plusieurs threads, + mais le thread d'envoi attend qu'elles finissent. C'est la vérification de « rien n'a changé » qui coûte, pas la copie. +- Les traducteurs de listes attendent par moments de la mémoire neuve (jusqu'à 513 fois et 79 ms dans une image). Ce sont les pics, + pas la moyenne. + +### Les objets non dessinés : surtout le ray tracing coupé + +Le nouveau compteur par cause dit que presque tous les draws abandonnés sont des **passes de ray tracing** (« ray-tracing builder off »), +jusqu'à 4 450 par image dans les nouvelles zones. Ils sont laissés de côté exprès, parce que la release n'active pas le ray tracing. Le +reste est faible : 146 au plus « binding failed », quelques « shader that does not translate » (wave64 sans traduction wave32) et +presque aucun « being made ». Ce qui manque à l'écran pourrait donc être des **ombres, reflets ou éclairages en ray tracing**, plutôt que +des objets. À vérifier en jeu. + +### Textures + +- Plus de va-et-vient : 59 360 textures relâchées, dont 553 seulement redemandées dans les 10 s. +- La file reste pleine (159 relevés sur 177). La ligne est à 5,55 Go pour 5,76 Go utilisés. +- Répartition de la carte : **3,0 Go de textures et de render targets**, **0,99 Go de copies carte des buffers du titre**, et + **1,75 Go de reste** (DLSS, génération d'images, heaps, pilote), sur un budget de 6,57 Go. +- Le passage sur les textures prises par index n'est plus affiché comme avant, et la part « asking whether a host copy holds » n'y + apparaît plus. + +### Copie périmée + +Une seule, à 10:48:19 : une copie de 4 Mo à `0x98bc00000`, la même zone que dans la partie C. Cette fois la trace dit +`this_one_ahead=true thread="victory-refresh-ahead-3"` : c'est l'avance qui l'a remise à jour, probablement à cause de +`VICTORY_REFRESH_WHOLE=1`. + +### RAM du PC + +- Le PC a **16 Go** (15,1 utilisables). Il a deux fichiers d'échange : 13,7 Go sur C: et 24,6 Go sur D:, soit une limite de mémoire + engagée de 52,5 Go. +- **Les pics d'utilisation des fichiers d'échange depuis le démarrage sont de 7,6 Go (C:) et 16,4 Go (D:).** Quelque chose, très + probablement le jeu, a donc engagé bien plus que les 16 Go de RAM. Windows a dû écrire une partie de la mémoire sur le disque, ce qui + peut aussi causer des freezes. +- Windows n'a enregistré aucun manque de mémoire (aucun événement 2004). +- Le journal du jeu ne donne pas la mémoire du processus. `scripts/mem-watch.ps1` la relève toutes les 5 s pendant la prochaine partie + (mémoire engagée, mémoire en RAM, RAM libre). +- La mémoire du titre Series S (environ 10 Go), les copies hôte de cette mémoire, et les copies des niveaux de textures (« 22 GB of + title memory whole » vues depuis le début) sont les suspects. La prochaine partie dira combien. + +## Partie F (29/11, 12:08) : E + `VICTORY_REFRESH_GUARDED=1`, avec la mesure de la RAM + +Log `20261129-110820-7244`, exe `perf/integration-4` (avec 3720382 et b7e3e3a8), 12 min 28, fermée par l'utilisateur. Relevé +`victory-mem-20261129-120700.csv` (`scripts/mem-watch.ps1`). Les deux parties ne montrent pas la même scène. + +| | E | **F** | +|---|---|---| +| Fin | fermé | **fermé, 12:28** | +| Manques de VRAM / échecs DLSS / copies périmées | 0 / 0 / 1 | **0 / 0 / 0** | +| fps p10 / médiane / p90 | 5,9 / 18,8 / 22,8 | 3,8 / 15,9 / 20,2 | +| Relevés monde sous 5 fps | 6 % | 12 % | +| Thread d'envoi ms/image | 54,1 | **43,0** | +| dont remises à jour | 27,5 | **19,8** | +| Draws non dessinés / image | 803 | **164** | +| File « pleine » | 159 / 177 | **77 / 139** | +| Textures dues, moyenne | 4 582 | 5 594 | + +- `GUARDED=1` fait ce qu'on attendait. Le thread d'envoi passe de 54 à 43 ms, et la ligne de l'avance dit **0 « guarded views »** + laissée à la soumission (il en restait 1 337). +- Ce qui reste à la soumission : 1 605 copies « written by shaders » et 324 fenêtres hors buffers par image. +- Les vérifications qui ne copient rien coûtent 4,8 ms en tout sur tous les threads pour 8 191 copies. Les 213 vraies copies prennent + 14,8 ms. L'agent avait raison : **ce sont les copies qui coûtent, pas les vérifications.** +- Pourtant, la médiane baisse et il y a deux fois plus de moments sous 5 fps. La raison est la RAM. + +### La RAM : le vrai goulot de cette partie + +| Heure (locale) | Privé engagé | En RAM (working set) | Défauts de page / s | +|---|---|---|---| +| 12:08 (menu) | 6,9 Go | 3,9 Go | ~400 | +| 12:10:09 | 9,6 Go | 7,5 Go | 16 000 | +| 12:10:16 | **15,2 Go** | 7,2 Go | **270 000** | +| 12:10:49 | 18,0 Go | 5,8 Go | 70 000 | +| 12:12 à 12:20 | 17 à 18,3 Go | 5 à 6 Go | 10 000 à 130 000 | + +- En entrant dans le monde, **la mémoire privée du jeu prend +5,6 Go en 7 secondes**, puis monte jusqu'à **18,3 Go**, sur un PC de + 16 Go. Il faut ajouter **4,6 Go de sections partagées** : les pages physiques du titre, comptées à part. +- Windows ne garde que 5 à 6 Go du jeu en RAM. Le reste part dans le fichier d'échange, d'où **jusqu'à 270 000 défauts de page par + seconde**. **La RAM libre du PC tombe à 79 Mo.** Chaque accès à une page sortie vers le disque bloque un thread : ce sont des freezes. +- Ce que l'hôte sait compter ne fait que **~0,5 Go** : shaders 188 Mo, traductions 100 Mo, upload 150 Mo, staging 70 Mo, bibliothèque de + pipelines 30 Mo. **Il reste environ 17 Go privés non expliqués.** +- Ce que le titre a demandé (xmem, total depuis le début) : + - **16,6 Go en 256 blocs de 64 Mo** (protection 0x4, kind 0x42000) ; + - 16 Go en un seul bloc (protection 0x801) ; + - 4 Go, 1,8 Go, 1,4 Go et 1,3 Go en blocs plus gros. + + Si les 256 blocs de 64 Mo sont engagés d'un coup, ou recopiés par nos copies hôte, ils expliquent le privé. +- Le PC engageait déjà environ 22 Go avant le jeu (33 Go au total, dont 11 pour le jeu au menu) : les autres programmes ouverts, dont les + sessions de Claude et les compilations. + +### Le temps d'une image + +En médiane, une image fait 63 ms : 40 ms de préparation, dont 25 de copies, puis **9 ms de « copying back »** (1,2 Mo relus de la +carte vers la mémoire du titre), 2 ms de GPU, et le reste. Les threads du titre attendent 23 ms à chaque present : c'est le titre +qui nous attend. Après le thread d'envoi, la relecture de 9 ms par image est le prochain poste. + +## Partie G (29/11, 12:32) : les réglages de F, PC dégagé, avec les lignes mémoire détaillées + +Log `20261129-113247-26028`, exe `perf/integration-4` (avec 96d2644 et 6dfa11d7), 7 min 31. Je l'ai fermée pour passer à la +release v2026.11.29.01, ce qui explique `end = cut off`. Les 231 lignes `ERROR` sont toutes le message de Streamline +`getRefreshRate: Window handle … is not a valid window` à la fermeture, sans gravité. + +| | F | **G** | +|---|---|---| +| Manques de VRAM / échecs DLSS / copies périmées | 0 / 0 / 0 | **0 / 0 / 0** | +| fps p10 / médiane / p90 | 3,8 / 15,9 / 20,2 | **10,8 / 18,3 / 20,9** | +| ms/image moyen | 109 | **70** | +| Thread d'envoi ms/image | 43,0 | **33,1** | +| dont remises à jour | 19,8 | **15,1** | +| File « pleine » | 77 / 139 | **18 / 85** | + +Même exe et mêmes réglages que F, mais avec moins de programmes ouverts à côté : le p10 passe de 3,8 à 10,8 fps. La RAM disponible +compte donc beaucoup. + +### Où vont les ~17 Go privés (lignes « the process's memory » et « host copies of title memory now ») + +| Poste | Go | +|---|---| +| Mémoire de la carte utilisée (comptée aussi dans le privé sous WDDM) | 5,3 | +| Mémoire du PC utilisée par la carte (ressources NON_LOCAL) | 4,2 à 4,5 | +| dont copies hôte de la mémoire du titre en RAM (4 290 copies) | **3,3** | +| Copies de ces buffers sur la carte | 0,98 | +| Engagé par le titre (XMemVirtualAlloc) | 2,9 | +| Shaders, traductions, upload, staging, bibliothèque | ~0,5 | + +- **Le pic à l'entrée dans le monde se reproduit** : le privé passe de 7,6 à 15,6 Go en 40 s. La mémoire de la carte passe de 1,5 à + 5,1 Go, et la mémoire du PC utilisée par la carte de 0,7 à 3,5 Go, avec 269 000 défauts de page par seconde. +- **0 Mo de snapshots de comparaison** : ce n'est pas là qu'il faut chercher. Le levier est le côté CPU des copies carte et les copies + hôte qui ne font que répéter la mémoire du titre (estimation de l'agent multithreading : 0,5 à 0,7 Go récupérables). +- `main` (v2026.11.29.01) a déjà, pour les PC de 16 Go, `VICTORY_WINDOW_KB=1024 VICTORY_WINDOW_TAILS=1` dans + `scripts/play-foxhound.ps1`. D'après son commentaire, les fenêtres des copies hôte passent de 3 400 à 2 598 Mo. À mesurer ici. + +## Partie H (29/11, 12:58) : v2026.11.29.01 + cette PR + +Exe de la branche `pr/rtx5060-8gb-perf`, 12 min 17, fermée proprement. Les réglages sont ceux de G, avec +`VICTORY_TEXTURE_ROOM_MARGIN_MB=768` et sans `PIPELINE_ASKED` ni `CARD_ROOM_FOR_TARGETS_MB`. Le journal brut et le relevé mémoire +restent hors du dépôt. Les [outils de benchmark](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/2571) sont disponibles dans une PR dédiée. + +| | G (.03 + nos branches) | **H (v2026.11.29.01 + cette PR)** | +|---|---|---| +| Fin | coupée par nous | **fermée proprement** | +| Manques de VRAM / échecs DLSS / copies périmées | 0 / 0 / 0 | **0 / 0 / 0** | +| Lignes `ERROR` | 231 (Streamline à la fermeture) | 6 | +| Thread d'envoi ms/image | 33,1 | **88,5** | +| dont remises à jour | 15,1 | **44,8** | +| Textures dues, moyenne | 5 109 | **11 506** | +| Privé max (`mem-watch.ps1`) | ~17,5 Go | **21,5 Go** | +| RAM libre min | — | 152 Mo | + +- **Ce n'est pas un gain sur cette base, c'est même un recul.** Le thread d'envoi et les remises à jour coûtent deux à trois fois plus + que sur la .03. Il faut le comparer à la release v2026.11.29.01 seule, avec les mêmes options, avant de conclure ce qui en est la + cause : nos réglages sur ce nouveau chemin (#614 absent), ou la release elle-même. +- Au moment de cette première analyse de H, le parseur ne lisait pas encore les lignes fps et room de v2026.11.29.01. + Le tableau de la partie I reprend H avec le parseur adapté. +- Le privé monte jusqu'à 21,5 Go malgré `VICTORY_WINDOW_KB=1024`, et la RAM libre tombe à 152 Mo. Le paging reste la limite sur un PC + de 16 Go. + +## Protocole des parties suivantes (I et après) + +Repris de G et H. **Une seule chose change d'une partie à l'autre** : l'exe ou un réglage, celui que donne le manager. + +1. **Avant** : le oui de l'utilisateur dans le chat. Aucune compilation en cours (`Get-Process cargo, rustc, link -ErrorAction + SilentlyContinue` ne renvoie rien). Fermer navigateurs, Discord, launchers, éditeurs, tout ce qui garde de la RAM (G contre F : + p10 de 3,8 à 10,8 fps rien qu'en dégageant le PC). Pas de `victory.exe` déjà ouvert. +2. **Relevé mémoire**, dans un PowerShell à part, lancé avant le jeu (il attend `victory.exe` et s'arrête 30 s après la fin) : + + ```powershell + powershell -ExecutionPolicy Bypass -File scripts\mem-watch.ps1 + ``` + +3. **Commande** (celle de H, relevée dans l'en-tête de son log ; `` est celui que donne le manager, le F1 menu n'y ajoute + que `VICTORY_MENU_FRAMEGEN=2`, déjà demandé) : + + ```powershell + & $victory play $jeu --series-s --res 1440 --dlss quality --framegen 2 --fg-type auto --fps 1000 --set VICTORY_LAZY_COMPARE_MB=64 --set VICTORY_LAZY_NARROW=1 --set VICTORY_SUBMIT_PRIORITY=2 --set VICTORY_REFRESH_AT_SUBMIT=2 --set VICTORY_REFRESH_THREADS=4 --set VICTORY_REFRESH_WHOLE=1 --set VICTORY_REFRESH_GUARDED=1 --set VICTORY_REFRESH_CHECK=1 --set VICTORY_BURY_ASIDE=1 --set VICTORY_WAIT_RESIDENT_UPLOADS=0 --set VICTORY_TEXTURE_ROOM_MARGIN_MB=768 + ``` + + Renseigner `$victory` et `$jeu` avec les chemins des deux exécutables. Le seul réglage changé s'ajoute en un `--set` de plus (ou en retire un). Pour la release seule, mêmes options. + Le premier lancement d'un exe peut redémarrer une fois (préchauffage) : c'est normal. +4. **Parcours** : la même sauvegarde, le même trajet que G et H, à pied puis en voiture dans la ville, sans menus ni pause. + **Durée : 10 min dans le monde**, comptées depuis l'arrivée dans le monde (G : 7:31, H : 12:17). Noter l'heure des freezes, + des textures floues ou manquantes et des objets absents. +5. **Fin** : fermer la fenêtre du jeu (croix ou Alt+F4), pas le Gestionnaire des tâches, pour que le log se termine par `end = + closed` et garde ses lignes de fin. Attendre que `mem-watch.ps1` affiche son résumé (privé max, RAM libre min). +6. **Fichiers** : prendre le dernier `victory-nvidia-play-*.log` et le dernier `victory-mem-*.csv` dans `%LOCALAPPDATA%\victory\logs`, + et `crashes.log` dans le répertoire de données local de VIctory si la partie a planté. Conserver les captures hors du dépôt et comparer avec G et H : + + ```powershell + python -I scripts\bench.py + ``` + + Rapport : fps médiane / p10, thread d'envoi (dont remises à jour), manques de VRAM, privé max et RAM libre min, textures dues, + freezes observés. + +## Partie I (29/11, 14:00) : v2026.11.29.01 seule, la base de H + +Exe `D:\VIctory-release-2026.11.29.01\victory.exe`, même ligne de commande que H (`--series-s --res 1440 --dlss quality +--framegen 2 --fg-type auto --fps 1000` et les mêmes `--set`), même parcours, lancée par `scripts/bench-run.ps1` et fermée +proprement après 12 min 30 (dont environ 5 min de chargement sans ligne de log, comme pour H). `victory preload --used` a été lancé +avant la partie : les 3 032 pipelines étaient déjà là, car la release et la PR ont le même traducteur. Le log tient sur 7 min 31, +contre 12 min 17 pour H. Pour comparer des parcours de même longueur, la colonne « H, 7 min 31 » garde les 7 min 31 du début du +log de H. Les chiffres viennent de `scripts/bench.py` (qui lit maintenant le format v2026.11.29.01), le privé de `mem-watch.ps1`. + +| | H entière (.01 + PR) | H, 7 min 31 | **I (.01 seule)** | +|---|---|---|---| +| Fin | fermée | — | **fermée** | +| fps p10 / médiane / p90 | 3,6 / 12,7 / 15,7 | 3,6 / 12,3 / 15,9 | **3,6 / 10,3 / 13,2** | +| ms/image moyenne | 126 | 145 | **151** | +| copies ms (monde) | 50,1 | 57,2 | **91,6** | +| Thread d'envoi ms/image | 88,5 | 94,5 | **120,1** | +| dont remises à jour | 44,8 | 50,3 | **72,8** | +| Manques de VRAM | 0 | 0 | **1 (à 3:38)** | +| Pipelines refusés (mesh, 0x8007000e) | 0 | — | **8** | +| Mémoire de la carte moy. / max Mo | 5 346 / 6 383 | 4 906 / 5 871 | **6 262 / 6 869** | +| File des textures pleine | 125 / 135 | 71 / 81 | **74 / 81** | +| Textures dues moy. / max | 11 506 / 22 260 | 11 114 / 22 260 | **3 677 / 18 301** | +| Images de frame gen montrées /s | 19,3 | 16,5 | **14,3** | +| Privé max (`mem-watch.ps1`) | 21,5 Go | — | **21,7 Go** | +| RAM libre min | 152 Mo | — | **63 Mo** | + +Ce que la release règle autrement que la PR (lu dans les switches de l'en-tête) : `VICTORY_TEXTURE_POOL=1` (0 avec la PR), +`VICTORY_HELPER_PRIORITY=1` (`on`), et ni `VICTORY_WINDOW_KB` ni `VICTORY_WINDOW_TAILS`. + +- **Le recul de H vient de la release v2026.11.29.01, pas de la PR.** Seule et sur le même parcours, la release fait pire que H : + le thread d'envoi passe à 120 ms (94,5 pour H sur la même durée), dont 73 ms de remises à jour (50), et la médiane à 10,3 fps + (12,3). La PR enlève donc environ un quart du temps du thread d'envoi, sans revenir aux 33 ms de G (.03). +- **La seule chose que la release fait mieux, c'est la file des textures** (3 677 dues en moyenne, contre 11 114). C'est + vraisemblablement l'effet de son `VICTORY_TEXTURE_POOL=1` : elle garde plus de mémoire de carte (6,3 Go en moyenne, 268 Mo libres + dans les blocs de textures), au prix d'un manque de VRAM et de 8 pipelines mesh refusés par manque de mémoire. +- **Le privé engagé est le même** (21,7 Go contre 21,5), et la RAM libre tombe à 63 Mo : le paging sur 16 Go vient de la release, + pas de la PR. +- Limites : une seule partie de chaque côté, et pas exactement le même chemin dans le jeu ; les écarts (+27 % sur le thread + d'envoi, +45 % sur les remises à jour) vont tous dans le même sens que les fps. Pour + retrouver G, il faut chercher ce qui a changé entre la .03 et la .01 dans les remises à jour (`refreshes`). + +Le log et le relevé de mémoire de I restent hors du dépôt, dans `%LOCALAPPDATA%\victory\logs` : +`victory-nvidia-play-20261129-130029-19252.log` et `victory-mem-20261129-140029.csv`. Les captures de H restent également hors du dépôt. + +## Partie J (29/11, 14:23) : H + `VICTORY_WINDOW_KB=4096 VICTORY_WINDOW_TAILS=0` + +Exe `D:\VIctory-NVIDIA-int5\target\release\victory.exe` (`perf/integration-5`), la commande du protocole avec les `--set` de H +(dont `VICTORY_REFRESH_CHECK=1`) et `--set VICTORY_WINDOW_KB=4096 --set VICTORY_WINDOW_TAILS=0`, lancée directement (sans +script) : la ligne switches du log montre bien 4096 et 0. Firefox et Discord fermés, 8,8 Go de RAM libre au départ. Jouée par +l'utilisateur, fenêtre fermée proprement à 14:41 (`end = closed`), log de 13 min 24. Les colonnes « 12 min 17 » et « 7 min 31 » +gardent le début des logs, pour comparer à H et à I sur la même durée. Chiffres de `scripts/bench.py`. Les copies Mo/image sont la +moyenne monde du champ `copies … MB` de la ligne fps, et les « refreshed » viennent de la ligne « the submission's refreshes per +frame ». + +| | H (12:17) | **J, 12 min 17** | H, 7 min 31 | I (7:31) | **J, 7 min 31** | +|---|---|---|---|---|---| +| fps p10 / médiane / p90 | 3,6 / 12,7 / 15,7 | **8,3 / 12,4 / 15,8** | 3,6 / 12,3 / 15,9 | 3,6 / 10,3 / 13,2 | **4,8 / 13,0 / 16,5** | +| ms/image moyenne | 126 | **92** | 145 | 151 | **98** | +| Thread d'envoi ms/image | 88,5 | **68,6** | 94,5 | 120,1 | **57,9** | +| dont remises à jour | 44,8 | **39,0** | 50,3 | 72,8 | **33,0** | +| Copies Mo/image (monde) | 69,7 | **49,6** | 78,0 | 57,6 | **53,1** | +| Copies regardées / remises à jour par image | 9 358 / 1 194 | **7 532 / 1 189** | 8 817 / 1 155 | — | **7 006 / 1 145** | +| **Copies périmées** (`REFRESH_CHECK`) | 0 | **12** | 0 | 0 | **2** | +| Manques de VRAM | 0 | **1 (DLSS, 10:16)** | 0 | 1 | **0** | +| Mémoire de la carte moy. / max Mo | 5 346 / 6 383 | **5 473 / 6 913** | 4 906 / 5 871 | 6 262 / 6 869 | **4 685 / 6 416** | +| File des textures pleine | 125 / 135 | **112 / 139** | 71 / 81 | 74 / 81 | **58 / 85** | +| Textures dues moy. / max | 11 506 / 22 260 | **10 384 / 25 412** | 11 114 / 22 260 | 3 677 / 18 301 | **8 453 / 25 412** | +| Images de frame gen montrées /s | 19,3 | **20,5** | 16,5 | 14,3 | **18,0** | +| Privé max (`mem-watch.ps1`) | 21,5 Go | **21,2 Go** (log entier) | — | 21,7 Go | — | +| RAM libre min | 152 Mo | **119 Mo** (à 14:31) | — | 63 Mo | — | + +- **Le thread d'envoi baisse nettement** : 68,6 ms contre 88,5 pour H (−22 %), 57,9 contre 94,5 sur 7 min 31. Les copies tombent de + 70 à 50 Mo par image, ce qui est proche des 40 Mo attendus. Les remises à jour ne baissent que de 13 % (39 ms au lieu des ~20 + attendues) : il y en a autant par image (~1 190), et c'est le nombre de copies regardées qui baisse (−20 %). +- **Le p10 remonte** (8,3 contre 3,6 fps), la médiane ne bouge pas (12,4 contre 12,7). Quatre relevés monde sont sous 5 fps : 3,4 à + 4,8 fps de 14:32:28 à 14:32:39, et 3,8 fps à 14:35:01. +- **Mais 12 copies périmées, contre 0 pour H et pour I.** 11 des 12 sont des copies à fenêtre (`window=true`, des copies de 6 Mo) : + 1 à 14:35:15 (copie 3624) et 10 à 14:36:40, toutes sur la copie 1876. Une autre, à 14:30:46, est une copie sur la carte. Avec des fenêtres de + 4 Mo sans queues, une partie de la mémoire du titre change sans être recopiée : c'est un risque d'image fausse (géométrie ou + texture d'une image précédente). Sur 7 min 31, il n'y en a que 2. +- **RAM** : privé engagé max 21,2 Go (21,5 pour H), RAM libre min 119 Mo. Les fenêtres plus grandes ne coûtent donc pas de RAM sur + cette partie, mais le paging reste la limite. +- **VRAM** : un avertissement « out of VRAM » de Streamline pendant un upscaling DLSS (14:38:19), puis la frame gen repasse à 2x à + 14:40:48 avec ce même avertissement. Pas de crash, pas de pipeline refusé. +- Limites : une seule partie, sans relevé des freezes ni des textures fait par l'utilisateur. Les fps se comparent avec prudence, + le thread d'envoi et les copies mieux. + +Le log et le relevé de mémoire restent hors du dépôt, dans `%LOCALAPPDATA%\victory\logs` : +`victory-nvidia-play-20261129-132325-5748.log` et `victory-mem-20261129-142324.csv`. Le résumé de `mem-watch.ps1` est vide sous +Windows PowerShell 5.1 (`Measure-Object -Property { … }` n'y accepte pas de bloc) : privé max et RAM libre min ont été lus dans le +CSV. + +## Partie K (29/11, 16:47) : la PR + `fix/texture-queue`, `fix/transitions` et `fix/reflections` + +Exe `D:\VIctory-NVIDIA-pr\target\release\victory.exe` construit sur `c670cd1f` (la PR et les trois branches fusionnées ; 939 tests +de `victory-gpu` passent). On la compare à la partie de 16:20 : même exe sans les trois branches, mêmes `--set` +(`REFRESH_CHECK=1`, `TEXTURE_ROOM_MARGIN_MB=768`, `TEXSPK_PASS_MS=8`, `WINDOW_KB=1024`, `WINDOW_TAILS=1`). Par rapport à elle, +la partie K retire `VICTORY_RAYMISS_KEEP=1` et ajoute `VICTORY_SAMPLED_MARKS=1 VICTORY_HELD_HOT=1 VICTORY_RAYMISS_SKY=0.25`. +**Plusieurs réglages changent à la fois**, à la demande de l'utilisateur. Firefox est fermé et il reste 6,6 Go de RAM libre au +départ (7,3 Go à 16:20). Le jeu est fermé proprement (`end = closed`) après 5 min 58, dont 4 min 45 dans le monde : la partie +dure moins que les 10 min du protocole. +Pour les deux parties, les lignes fps et room ont été relevées par un script à part, parce que `bench.py` ne lit pas encore le +format de cette base : on compte les lignes monde à partir de 1000 draws par image. Les autres lignes viennent de `bench.py`. + +| | 16:20 (sans les branches) | **K** | +|---|---|---| +| Lignes monde (5 s) | 54 | 54 | +| fps p10 / médiane / p90 | 7,5 / 14,9 / 16,9 | **3,9 / 15,4 / 18,3** | +| ms/image moyenne | 93 | **136** | +| Copies ms / Mo par image (monde) | 47,5 / 63,6 | **76,2 / 67,1** | +| Thread d'envoi ms/image (dont remises à jour) | 73,9 (38,6) | **76,1 (42,0)** | +| Images dont les remises à jour dépassent 300 ms | 1 | **5** | +| Relevés monde sous 5 fps | 4 (le plus bas 2,2) | **6 (0,8 à 16:50:54, 0,9 à 16:52:02)** | +| Copies périmées (`REFRESH_CHECK`) | 0 | **0** | +| Manques de VRAM | 0 | **0** | +| Mémoire de carte moy. / max Mo (ligne de la file) | 6 035 / 6 811 (6 022) | **6 130 / 7 168 (6 099)** | +| File des textures sans place | 55 / 62 | **56 / 65** | +| Textures dues moy. / max | 19 124 / 31 729 | **22 280 / 31 330** | +| « texture picked by index changed after its upload » | 185 | **44** | +| Images de frame gen montrées /s | 17,3 | **21,9** | +| Privé max / RAM libre min (`mem-watch.ps1`) | 20,9 Go / 70 Mo | **21,3 Go / 39 Mo** | + +- **Les deux freezes de K viennent des remises à jour du thread d'envoi, pas des trois branches.** À 16:50:54, une image dure + 1,2 s : 1 169 ms de remises à jour copient 239 Mo. À 16:52:02, 380 ms de remises à jour copient 108 Mo. Ces deux images arrivent + quand la RAM libre tombe à 39 Mo : c'est le paging. Aucune des trois branches ne touche à ces copies (`fix/transitions` ne change + que le compte de `REFRESH_CHECK`). Ces deux images suffisent à faire tomber le p10 (3,9 contre 7,5) et à faire monter la moyenne + (136 ms contre 93). +- **Hors freezes, K est un peu meilleure** : médiane 15,4 contre 14,9, p90 18,3 contre 16,9, et 21,9 images de frame gen par + seconde contre 17,3. Sur une seule partie de 5 min, l'écart reste dans le bruit. +- **Textures** : les avertissements « texture changed after its upload with nothing to tell » passent de 185 à 44. La mémoire de + carte va plus haut (7 168 Mo au max, plus de 1 Go au-dessus de la ligne). C'est attendu avec `HELD_HOT`, qui fait revenir les + textures à l'écran même quand la carte n'a pas de place. Il n'y a eu aucun manque de VRAM. Les textures dues restent nombreuses + (22 000 en moyenne) : la file n'est pas plus courte. Faute de compteur dans le log, on ne sait pas combien de textures + `HELD_HOT` a fait revenir. +- **Reflets** : la passe `RAYMISS_SKY` a bien tourné (« the reflections' sky scaled after the miss program, share=0.25 »). Aucun + relevé visuel n'a été fait pendant la partie : il reste à vérifier à l'œil que les taches de couleur ont disparu des vitres et + des carrosseries. +- **Transitions** : 0 copie périmée avec le nouveau compte. L'intro n'a pas donné les 65 faux avertissements de 16:05. +- **Ce qui limite cette partie** : elle est seule et courte, plusieurs réglages y changent ensemble, et il n'y a pas de relevé + visuel. Le goulot reste le même : la RAM (21,3 Go engagés sur 16 Go) et les copies du thread d'envoi. + +Le log et le relevé de mémoire restent hors du dépôt, dans `%LOCALAPPDATA%\victory\logs` : +`victory-nvidia-play-20261129-154741-11008.log` et `victory-mem-20261129-164741.csv` (référence : +`victory-nvidia-play-20261129-152010-27184.log` et `victory-mem-20261129-162009.csv`). diff --git a/docs/texture-queue-under-pressure.md b/docs/texture-queue-under-pressure.md new file mode 100644 index 0000000000..6a38fcaf40 --- /dev/null +++ b/docs/texture-queue-under-pressure.md @@ -0,0 +1,24 @@ +# Texture work under VRAM pressure + +In a local RTX 5060 8 GB session at `4c20058c`, the log reported 40 queue samples where new textures waited for room, 30 texture changes discovered after the first upload, and six prelude uploads left out after the host wrote the texture. The test reached gameplay and closed normally. The shader copy checker reported zero stale buffer copies. These counts identify several paths to investigate and do not map each visual defect to a log line. + +The supplied GDKX reference for Xbox sampler feedback describes hardware support for feedback about what the GPU samples. VIctory already records recently sampled indexed slots. During a regular texture pass with no VRAM room, use those marks to put recently sampled due slots first, including rechecks of textures already on the card. Keep the recheck metadata paired with each slot. Existing room, commit, and per-pass limits still govern admissions and work. The background order applies after the sampled slots. + +`VICTORY_DUE_HOT_FIRST=0` restores the former queue order. `VICTORY_DUE_HOT_FIRST=1` asks for the new order even when room is available. Without a readable feedback mark, the slot follows the normal order. This change does not merge PC RAM and VRAM or change the contents, layout, or mapping of any texture. The remaining alias invalidation and prelude warnings need separate evidence before changing those paths. + +## Local verification + +The Windows release built, 73 descriptor tests passed, and the staged asset check passed. A regression test checks that a sampled recheck keeps its fingerprint when it moves ahead of background slots. + +One run per revision used Series S, 1440p, DLSS Quality, 2x Frame Generation, XMem diagnostics, and copies of the same shader cache and save state. The table covers the first 45 seconds after the first log sample with at least 2,000 draws per frame. + +| Measurement | Parent | Patched | +| --- | ---: | ---: | +| Rendered FPS, median | 5.6 (7 samples) | 8.1 (8 samples) | +| Buffer copy time, median | 80.4 ms/frame | 60.8 ms/frame | +| Queue samples blocked by VRAM budget | 8 | 8 | +| Texture changes discovered after upload | 4 | 0 | +| Skipped prelude uploads | 1 | 0 | +| Peak due slots | 29,016 | 33,035 | + +The patched run reached gameplay and closed normally. The logs show different scene timing and workload. The higher peak backlog and recurring budget pressure remain. These runs do not establish a causal frame-rate gain or confirm a visual fix for all textures. diff --git a/docs/textures-h-cause.md b/docs/textures-h-cause.md new file mode 100644 index 0000000000..73f719f78a --- /dev/null +++ b/docs/textures-h-cause.md @@ -0,0 +1,36 @@ +# Textures lentes, grises ou fausses dans la partie H (29/11/2026) + +Lu dans le log local de H (`victory-nvidia-play-20261129-115844-29880.log`, v2026.11.29.01 + PR, RTX 5060 8 Go, +`--series-s --dlss quality --framegen 2`). Pas de manque de VRAM, pas de mauvais format ni swizzle relevé. + +## Ce qui se passe + +1. **La passe des textures prises par index est limitée par son temps, pas par la place.** Chaque passe s'arrête à + son temps (`VICTORY_TEXSPK_PASS_MS=8` : « 146 stopped at their time » sur 146 passes, toutes les 5 s). Elle sert + ~1 500 à 2 400 slots et ~400 téléversements par 5 s, pour **12 780 slots dus sur 15 388** à la fin (le plus vieux + écrit il y a 9 348 images). « held back for room » vaut presque toujours 0 : les premiers téléversements au-dessus de + la ligne sont tous admis. Le temps part en création et résidence des copies hôte (~930 ms / 5 s), en vues (~560 ms) et + ~600 ms avant la boucle pour prendre les slots dus. Le jeu tourne à ~13 images/s, donc ~13 passes de 8 ms par seconde. +2. **Ordre de service.** Les slots déjà regardés (mémoire absente, ~500 par 5 s) passent avant les textures que les + shaders échantillonnent : avec ~30 slots par passe, l'écran attend derrière des re-vérifications. +3. **La VRAM n'est jamais rendue.** La file dit « no room, new textures wait » dès la 1re minute (6,4 à 7,0 Go comptés + pour une ligne de ~5,7-6,0 Go). L'éviction des slots (`VICTORY_SLOT_EVICT=1`) a libéré **0 texture en 12 min** : + ce jeu lit toutes ses textures par index, et avec `VICTORY_SAMPLED_EVICT=0` (coupé le 28/11 pour le feuillage qui + clignotait) elles sont toutes « not to be taken ». Les marques disent pourtant que **~930 Mo** d'entre elles + n'ont été lues par aucun shader dans le temps d'inactivité. Sans place, la passe garde aussi son plafond de base : + le rattrapage (×3 en temps et en octets) ne s'active qu'avec de la place. +4. **Gris et fausses textures.** Un slot qui attend montre le gris neutre (c9c53541) ; un slot réécrit avec une autre + texture garde l'ancienne en attendant (`VICTORY_KEEP_SHOWN` : 259 081 fois) : c'est la « mauvaise texture » visible, + jusqu'à ce que la passe arrive au slot, parfois des minutes plus tard. 200 avertissements « changed after its upload + with nothing to tell of it » : ceux-là sont re-téléversés, pas laissés faux. + +## Correctifs (éteints par défaut) + +- `VICTORY_DUE_HOT_FIRST=1` (`descriptor/host.rs`, `Due::ordered`) : les slots échantillonnés récemment + (`VICTORY_SAMPLED_MARKS=1`) passent avant les slots déjà regardés. +- `VICTORY_COLD_EVICT_S=` (`resource.rs`, `slot_evict`; 10 à 110 s) : l'éviction prend aussi les textures prises + par index qu'aucun shader n'a lues depuis `` secondes (au lieu de 4-15 s pour `SAMPLED_EVICT`), pour rendre la + place sans faire clignoter ce qui est lu de temps en temps. Une texture revenue est protégée 60 s ; un slot relu est + remis dans la file et, avec `DUE_HOT_FIRST`, servi en premier. + +Non fait : relever `VICTORY_TEXSPK_PASS_MS` (dans `draw.rs`, se règle déjà par l'environnement). diff --git a/docs/threads-6-cores.md b/docs/threads-6-cores.md new file mode 100644 index 0000000000..139af17582 --- /dev/null +++ b/docs/threads-6-cores.md @@ -0,0 +1,139 @@ +# Threads sur un 6 cœurs / 12 threads (Ryzen 5 9600X) + +Hypothèse vérifiée : la couche fait tourner plus de threads occupés qu'il n'y a de cœurs physiques, et le +thread de soumission (`victory-submit`, celui qui limite l'image) perd du temps à cause d'eux. + +Sources : le code (`crates/victory-gpu`, `crates/victory-hle`, `apps/victory/src/play.rs`), la PR #419 +(ouverte, non fusionnée) et le log `victory-nvidia-play-20261128-021001-14692.log` (Series S, pool off, +8 min 26 s, médiane 17,8 fps, thread de soumission 64 ms/image). + +## 1. Recensement + +Priorités Windows : le processus tourne en classe « au-dessus de la normale » (base 10, +`VICTORY_PROCESS_PRIORITY`). Un thread à +1 = 11, +2 (« highest ») = 12, « time critical » = 15, +-1 = 9, -2 = 8. Aucun thread n'a d'affinité : sur un Ryzen sans E-cores, `cores.rs` ne demande rien +(tous les cœurs ont la même classe), donc **le thread de soumission peut tourner n'importe où, y +compris à côté d'un autre thread occupé sur le même cœur physique**. + +| Thread / pool | Nombre sur 12 logiques | Comment le nombre est choisi | Priorité | Occupé | +|---|---|---|---|---| +| `victory-submit` (soumission) | 1 | fixe (`VICTORY_ASYNC_SUBMIT`) | +1 (11), ou `VICTORY_HELPER_PRIORITY` | chaque image : 43-77 ms | +| `victory-relay` (copie en retour) | 1 | fixe | +1 | chaque image : 13-24 ms d'atterrissage | +| `victory-heap-sync` (registres des tas) | 1 | fixe | +1 | chaque image : 13-16 ms | +| `victory-late-wait`, `victory-aside` | 1 + 1 | fixe | +1 | chaque image, court | +| `victory-list-*` (traduction, `VICTORY_THIN=1`) | **8** | constante, `VICTORY_THIN_THREADS` | **+1 avec le défaut du lanceur** (voir plus bas), sinon 0 | chaque image : **160-315 ms de CPU par image**, tous threads | +| `victory-wide-*` (rafraîchissements) | 4 | logiques × 3/8, 2-8, `VICTORY_WIDE_THREADS` | +1 | chaque image (5 760 des 6 369 vidages sur plusieurs threads) | +| `victory-land-*` | 2 (+ le relais) | logiques / 4, 1-4, `VICTORY_LAND_THREADS` | +1 | chaque image : ~6 ms tous threads | +| `victory-under-*` | 5 (+ l'appelant) | constante 6, `VICTORY_UNDER_THREADS` | +1 | chaque image, court | +| `dstorage N` | **12** | = logiques, `VICTORY_DSTORAGE_WORKERS` | -1 (9), `VICTORY_DSTORAGE_PRIORITY` | pendant le streaming (chargements, scènes qui arrivent) | +| `victory-pipelines-*` | 8 | logiques × 2/3, 2-16 (× 3/4 si peu de RAM), `VICTORY_PIPELINE_WORKERS` | « lowest » (8) | au chargement / cache froid ; en jeu presque rien (« 1 being made ») | +| `uploads ahead 0-1` | 2 | fixe | 0 | par à-coups | +| `victory-ahead`, `victory-picked` | 1 + 1 | fixe | -1 | par à-coups | +| map threads | 0 | `VICTORY_MAP_THREADS=1` (défaut du lanceur) | – | – | +| petits (card-clock, sample, timeline, menu, audio, manettes…) | ~10 | fixe | divers | presque rien | +| **Titre** : ~9 workers | ~9 | le titre | **« highest » +2 (12)** | chaque image | +| **Titre** : ~8 autres + 1 « time critical » | ~9 | le titre | jusqu'à 15 | une partie chaque image | + +Les masques d'affinité du titre (relevés dans la PR #419 sur un Intel) : `0xFF` (processeurs 0-7), +`0x1F00` (8-12), `0x2000` (13). La couche les passe tels quels à Windows (#419 non fusionnée). Sur un +Ryzen, les processeurs 2n et 2n+1 sont les deux threads d'un même cœur : `0xFF` met les ~9 workers +« highest » du titre sur les **cœurs physiques 0 à 3**, `0x1F00` sur les cœurs 4-5, et le processeur 13 +n'existe pas ici. Ce placement n'est pas vérifié sur ce PC (aucune trace des masques dans le log). + +Point important trouvé dans le code : le lanceur met `VICTORY_HELPER_PRIORITY=1` par défaut +(`apps/victory/src/play.rs`). Ce réglage est appliqué par `cores::ask` à **tous** les threads qui +passent par `keep_*_on_fast_cores`, y compris les 8 threads qui traduisent les listes et les pools +`land`/`under`. Résultat : le thread de soumission (11) est **au même niveau que les 8 traducteurs** +(Windows les fait tourner chacun leur tour) et **sous les ~9 workers du titre** (12). Le commentaire de +`cores::helpers_raised` montre que l'intention était l'inverse : aides au-dessus, traducteurs à la +normale. + +## 2. Verdict + +Oui, il y a sursouscription, et elle touche le thread de soumission : + +- Charge CPU par image (~55-60 ms) côté couche seule : soumission 45-65 + relais 15-25 + tas 14-16 + + traduction 160-315 + rafraîchissements, soit **4,5 à 7 processeurs logiques occupés en continu**, + plus les ~9-10 workers du titre. Il y a plus de threads prêts que de processeurs : chaque cœur + physique tourne avec ses deux threads SMT occupés. +- SMT AMD : deux threads sur un même cœur se partagent ses unités et son cache L1/L2. Un frère occupé + ralentit le thread de soumission d'environ 20 à 40 % sur du code de copie et de hachage comme le + sien. La priorité n'y change rien : un thread dstorage à -1 sur le frère ralentit quand même la + soumission. Seuls moins de threads prêts au total libèrent le frère. +- Les pools dimensionnés sur les processeurs logiques ne sont **pas** les plus gênants en jeu : + dstorage (12) n'est occupé que pendant le streaming, et à -1 ; les pipelines (8) sont à « lowest » et + presque inactifs en jeu. Ceux qui pèsent à chaque image sont les 8 traducteurs (nombre constant, + priorité montée par le défaut du lanceur), puis wide (4), land (3) et under (6). +- Le symptôme correspond : les threads du titre attendent la soumission aux presents (3 à 7 ms par image + dans la fenêtre de 02:15). + +## 3. Matrice de tests + +Même exe pour toutes les parties, y compris la référence : celui construit ici (même code que la +v2026.11.27.9 plus `bench.py` et le nouveau réglage `VICTORY_SUBMIT_PRIORITY`, éteint par défaut). + +```powershell +$exe = 'D:\VIctory-NVIDIA\.claude\worktrees\perf-threads-6-cores-24de25\target\release\victory.exe' +$game = 'D:\GTA6.Xbox.v1.0.2.1-CYBERLEEK\game_scarlett_master.exe' +``` + +Référence (R) : + +```powershell +& $exe play $game --series-s --dlss quality --framegen 2 --set VICTORY_TEXTURE_POOL=0 +``` + +Classées par gain attendu : + +| # | Réglages ajoutés | Effet attendu | À surveiller | +|---|---|---|---| +| V1 | `VICTORY_HELPER_PRIORITY=on` | Les 8 traducteurs repassent à la normale (10) ; la soumission et ses aides restent à +1 (11). La soumission ne partage plus son tour avec eux. Gain attendu : thread de soumission −5 à −10 ms/image. | Que la soumission n'attende pas plus les listes traduites (« taking translated lists out of the line »). | +| V2 | V1 + `VICTORY_SUBMIT_PRIORITY=2` | La soumission seule passe à « highest » (12), au niveau des workers du titre. Effet attendu : moins d'attente « prêt mais pas lancé », surtout dans les zones chargées. | Le titre peut ralentir (ses workers cèdent des tours). Comparer fps et attente aux presents. | +| V3 | V1 + `VICTORY_THIN_THREADS=4` | 4 traducteurs au lieu de 8 : moins de threads prêts, des frères SMT libérés. | Le temps de traduction par image monte ; si la soumission attend les listes, c'est perdu. | +| V4 | V1 + `VICTORY_DSTORAGE_WORKERS=6 VICTORY_WIDE_THREADS=3 VICTORY_UNDER_THREADS=3` | Pools ramenés au nombre de cœurs physiques. Gain surtout dans les cutscenes et pendant le streaming ; faible en jeu calme. | Chargements un peu plus longs ; rafraîchissements (`refreshes ms`) qui montent. | + +Commandes : + +```powershell +& $exe play $game --series-s --dlss quality --framegen 2 --set VICTORY_TEXTURE_POOL=0 --set VICTORY_HELPER_PRIORITY=on +``` + +```powershell +& $exe play $game --series-s --dlss quality --framegen 2 --set VICTORY_TEXTURE_POOL=0 --set VICTORY_HELPER_PRIORITY=on --set VICTORY_SUBMIT_PRIORITY=2 +``` + +```powershell +& $exe play $game --series-s --dlss quality --framegen 2 --set VICTORY_TEXTURE_POOL=0 --set VICTORY_HELPER_PRIORITY=on --set VICTORY_THIN_THREADS=4 +``` + +```powershell +& $exe play $game --series-s --dlss quality --framegen 2 --set VICTORY_TEXTURE_POOL=0 --set VICTORY_HELPER_PRIORITY=on --set VICTORY_DSTORAGE_WORKERS=6 --set VICTORY_WIDE_THREADS=3 --set VICTORY_UNDER_THREADS=3 +``` + +Comparer ensuite avec : + +```powershell +python -I scripts/bench.py --last 5 +``` + +Lignes à lire : fps médiane, `submit thread ms/frame`, `refreshes ms`, et dans le log la ligne +`VICTORY_ASYNC_SUBMIT` (« threads of the title waited … ms at presents »). Même trajet, au moins 5 min +chacune. `VICTORY_SUBMIT_PRIORITY=2` ne marche qu'avec l'exe construit ici (ignoré par la v2026.11.27.9). +`VICTORY_HELPER_PRIORITY=on` : toute valeur autre qu'un nombre ou `0` donne le comportement prévu +(aides montées, traducteurs à la normale). + +## 4. Nouveau réglage et cible du build + +- `VICTORY_SUBMIT_PRIORITY=<-2..2 | 15>` (`crates/victory-gpu/src/queue/behind.rs`) : priorité du seul + thread de soumission, appliquée après les autres réglages. Absent ou invalide : rien ne change. Test + unitaire `the_submitting_threads_priority_is_a_thread_priority_or_nothing`. +- Cible CPU : **le build release vise x86-64 de base (SSE2), pas AVX2 / x86-64-v3.** `.cargo/config.toml` + ne contient qu'un alias, `[profile.release]` seulement `debug = "line-tables-only"` (ni `lto`, ni + `codegen-units = 1`), et le CI ne fait que clippy. Quelques chemins utilisent AVX2 avec une détection + à l'exécution (`host/torn.rs`, `safecopy.rs`, `shadow.rs`, `indirect.rs`) ; le reste (hachage, + détuilage, copies en Rust) n'utilise pas AVX2. Un build `-C target-cpu=x86-64-v3` est à mesurer à + part : il ne se teste pas avec `--set`. + +Pas fait : la PR #419 (affinités du titre) reste ouverte, et elle ne change rien sur un Ryzen. Aucun +réglage ne place le thread de soumission seul sur un cœur physique avec son frère libre : il faudrait +des CPU sets pour la couche et le titre, ce n'est pas un petit changement. diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1 index 11a45eec0c..49ae44785d 100644 --- a/scripts/play-foxhound.ps1 +++ b/scripts/play-foxhound.ps1 @@ -173,6 +173,12 @@ $ramGb = try { (Get-CimInstance Win32_ComputerSystem -ErrorAction Stop).TotalPhy if ($ramGb -gt 0 -and $ramGb -le 16.5) { $settings.VICTORY_WINDOW_KB = '1024'; $settings.VICTORY_WINDOW_TAILS = '1' } +# Cards of 8 GB or less play without the texture pool: its blocks' holes ran the card out of memory (#597, #196). +# shortcut: the largest card's memory from the registry, not the monitor's card the layer plays on; differs only on +# a PC with an 8 GB card beside a bigger one. +$cardMemory = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\0*' -Name 'HardwareInformation.qwMemorySize' -ErrorAction SilentlyContinue | + ForEach-Object { [uint64]$_.'HardwareInformation.qwMemorySize' } | Measure-Object -Maximum +if ($cardMemory.Count -gt 0 -and $cardMemory.Maximum -le 8GB) { $settings.VICTORY_TEXTURE_POOL = '0' } if (-not $SeriesS) { if ($Res -eq '1440') { $settings.VICTORY_NATIVE_1440P = '1' } elseif ($Res -eq '1080to1440') { $settings.VICTORY_RENDER_1080P = '1' }