diff --git a/.gitignore b/.gitignore index 1be7f5e8e..168fd8110 100644 --- a/.gitignore +++ b/.gitignore @@ -13,7 +13,7 @@ # Local configuration (contains paths to YOUR files) /victory.toml - +.claude # Places people tend to drop data into. Keep data outside the repo instead. /game/ /games/ @@ -82,3 +82,4 @@ Thumbs.db # What the F1 menu saved /victory-settings.txt /victory-settings.*.txt +docs/performance/baseline-data/ diff --git a/Benchmark-VIctory.cmd b/Benchmark-VIctory.cmd new file mode 100644 index 000000000..aeca494c1 --- /dev/null +++ b/Benchmark-VIctory.cmd @@ -0,0 +1,12 @@ +@echo off +setlocal EnableExtensions DisableDelayedExpansion +rem Frame-rate estimate without opening the game: replays the work a run's log +rem counted through this build's code and compares with that run's frame rate. +rem Usage: Benchmark-VIctory.cmd [path\to\play-*.log] (default: newest run with gameplay) +set "runner=%~dp0target\release\victory.exe" +if not exist "%runner%" ( + echo Build first: cargo build --release --locked -p victory 1>&2 + exit /b 2 +) +"%runner%" bench %* +exit /b %errorlevel% diff --git a/Cargo.lock b/Cargo.lock index 9a656d8bf..f1095b10e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -248,6 +248,15 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -275,6 +284,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -676,6 +694,7 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", + "mimalloc", "tempfile", "tracing", "victory-formats", diff --git a/Cargo.toml b/Cargo.toml index 4e21b692d..579d8a65f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ license = "GPL-3.0-or-later" publish = false [workspace.dependencies] +mimalloc = { version = "0.1", default-features = false } # Internal crates victory-core = { path = "crates/victory-core" } victory-pe = { path = "crates/victory-pe" } diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index efaa1091e..e57f298f2 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -30,6 +30,8 @@ diagnostics = [ "victory-loader/diagnostics", "victory-shader/diagnostics", ] +# Rust allocations through mimalloc instead of the shared process heap. +mimalloc = ["victory-hle/mimalloc"] [lints] workspace = true diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index f3cfa2f82..1a2f0bd80 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -174,6 +174,20 @@ enum Command { /// docs/replay.md). #[cfg(all(windows, feature = "diagnostics"))] Replay(replay::Replay), + /// Estimate the frame rate without the title: a run's log says what work + /// each frame had; this build runs the steps it can (write watch, + /// refreshes' copies, sending up, landing) on stand-in title memory, puts + /// them with the rest of the log's times and compares with the run's + /// frame rate. Without a log: the newest run's with gameplay. + #[cfg(windows)] + Bench { + /// A run's log (`%LOCALAPPDATA%\victory\logs\play-*.log`). + log: Option, + /// An earlier report of `victory bench` (saved output, another + /// build, the same log): prints the change of the estimate. + #[arg(long)] + compare: Option, + }, /// Show the resolved configuration and check it. Config, /// Check NVIDIA Streamline, DLSS and DLSS Frame Generation on this PC @@ -308,6 +322,15 @@ fn main() -> Result<()> { } #[cfg(all(windows, feature = "diagnostics"))] Command::Replay(options) => replay::run(options), + #[cfg(windows)] + Command::Bench { log, compare } => { + let log = match log { + Some(log) => log, + None => newest_gameplay_log()?, + }; + print!("{}", victory_hle::bench::run(&log, compare.as_deref())?); + Ok(()) + } Command::Config => show_config(), #[cfg(windows)] Command::UpscalerCheck { output, device, present } => { @@ -323,6 +346,26 @@ fn main() -> Result<()> { } } +/// The newest play log with gameplay frame-rate lines (`victory bench` without a log). +#[cfg(windows)] +fn newest_gameplay_log() -> Result { + let base = std::env::var_os("LOCALAPPDATA").ok_or_else(|| anyhow::anyhow!("no %LOCALAPPDATA%"))?; + let dir = PathBuf::from(base).join("victory").join("logs"); + let mut logs: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(&dir)? + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().starts_with("play-")) + .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path()))) + .collect(); + logs.sort_by(|a, b| b.0.cmp(&a.0)); + for (_, path) in logs { + let Ok(text) = std::fs::read_to_string(&path) else { continue }; + if !victory_hle::bench::gameplay(&victory_hle::bench::windows(&text)).is_empty() { + return Ok(path); + } + } + anyhow::bail!("no play log with gameplay in {}", dir.display()) +} + fn show_config() -> Result<()> { let cfg = victory_core::Config::load()?; let status = |p: &Option| match p { diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index ec9ff6195..8f62cd119 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -30,7 +30,8 @@ const FETCH: &str = include_str!("../../../scripts/get-nvidia-sdks.ps1"); const SETTINGS: &[(&str, &str)] = &[ // Submission and copy machinery ("VICTORY_THIN", "1"), - ("VICTORY_JOIN_PARTS", "8"), + ("VICTORY_JOIN_PARTS", "16"), + ("VICTORY_JOIN_LISTS", "96"), ("VICTORY_RELAY", "2"), ("VICTORY_RELAY_COPY", "1"), ("VICTORY_WIDE_BACK", "1"), @@ -44,16 +45,13 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_UPLOAD_AHEAD", "1"), ("VICTORY_SHOW_AFTER", "1"), ("VICTORY_MAP_THREADS", "1"), - // Shader writes into big write-combined copies stay on the card - ("VICTORY_WC_NO_BACK", "1"), - ("VICTORY_WC_NO_BACK_MIN_KB", "1024"), // The title's page-mapping copies kept without Windows views ("VICTORY_SOFT_VIEWS", "copies"), // Textures ("VICTORY_TEXTURE_POOL", "1"), ("VICTORY_RIPE_BLOCKS", "0"), ("VICTORY_TEXTURE_NO_WAIT", "1"), - ("VICTORY_TEXTURE_CATCHUP", "0"), + ("VICTORY_TEXTURE_CATCHUP", "1"), ("VICTORY_TEXTURE_STAGE_MS", "16"), ("VICTORY_LEVELS_ON_DEMAND", "0"), ("VICTORY_PRELUDE_UPLOADS", "1"), @@ -254,10 +252,8 @@ fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> ( if let Some(x) = framegen_x { set("VICTORY_FRAMEGEN", "1"); set("VICTORY_FRAMEGEN_X", &x.to_string()); - // Frame generation takes 1.5 to 2 GB of the card's memory, which the layer - // otherwise fills with textures: on from the start it is left a fifth of the - // budget; ready but off, a little less is held back. - set("VICTORY_TEXTURE_ROOM_PERCENT", if framegen { "80" } else { "86" }); + // (The texture line leaves frame generation its room by itself: + // `resource::room_line`, a constant there, not a switch here.) } } // AMD FSR 3 frame generation, made ready as DLSS frame generation is: auto, the layer uses @@ -506,7 +502,7 @@ mod tests { assert_eq!(get("VICTORY_STREAMLINE_DIR"), Some(r"C:\nvidia")); // frame generation ready, off, with a little memory held back for it assert_eq!((get("VICTORY_FRAMEGEN"), get("VICTORY_FRAMEGEN_X")), (Some("1"), Some("0"))); - assert_eq!(get("VICTORY_TEXTURE_ROOM_PERCENT"), Some("86")); + assert_eq!(get("VICTORY_TEXTURE_ROOM_PERCENT"), None); assert_eq!(get("VICTORY_FRAME_INTERVAL_US"), Some("1000")); assert_eq!((get("VICTORY_MENU_DLSS"), get("VICTORY_MENU_FRAMEGEN")), (Some("quality"), Some("0"))); assert_eq!((get("VICTORY_MENU_CONSOLE"), get("VICTORY_MENU_FPS")), (Some("series-x"), Some("1000"))); @@ -553,7 +549,7 @@ mod tests { // the Series S profile has no picture size of its own assert_eq!(get("VICTORY_NATIVE_1440P"), None); assert_eq!((get("VICTORY_DLSS_MODE"), get("VICTORY_FRAMEGEN_X")), (Some("performance"), Some("6"))); - assert_eq!(get("VICTORY_TEXTURE_ROOM_PERCENT"), Some("80")); + assert_eq!(get("VICTORY_TEXTURE_ROOM_PERCENT"), None); assert_eq!(get("VICTORY_FRAME_INTERVAL_US"), Some("16667")); // a switch with a value is set, an empty one unset; the menu's own choices are not switches assert_eq!((get("VICTORY_AMBIENT"), get("VICTORY_EARLY_DEPTH")), (Some("0.5"), None)); diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 6dc2e7090..381aeb588 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -143,6 +143,12 @@ pub fn run( cfg.cache_subdir("images")? }; victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + // The pipelines earlier runs used are made from here on, not when the + // title creates each (its loading screen is the time to make them). + #[cfg(windows)] + if execute { + victory_hle::known_pipelines::prewarm(); + } let image = victory_loader::load(&prepared, &images)?; // The program is mapped from the copy `load` wrote: the file's bytes // and their patched copy are not read again, and were held for the diff --git a/apps/victory/src/warm.rs b/apps/victory/src/warm.rs index ac7a66bc0..82f0dbf1c 100644 --- a/apps/victory/src/warm.rs +++ b/apps/victory/src/warm.rs @@ -60,14 +60,25 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect(); let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default(); let early: HashSet<&str> = early.lines().collect(); - // Those earlier runs drew with first, the others in no order (by key). + // Those earlier runs drew with first, in the order they first drew with + // them (`pipeline-order.txt`, the line is the place), then those listed + // without a place, then the others in no order (by key). + let order = std::fs::read_to_string(dir.join("pipeline-order.txt")).unwrap_or_default(); + let mut place: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for key in order.lines().filter_map(|l| l.split_whitespace().next()) { + let next = place.len(); + place.entry(key).or_insert(next); + } let mut all: Vec = (0..keys.len()) .filter(|&n| { let key = keys[n].as_str(); (again || !done.contains(key)) && !bad.contains(key) && (!used || early.contains(key)) }) .collect(); - all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n])); + all.sort_by_key(|&n| { + let key = keys[n].as_str(); + (!early.contains(key), place.get(key).copied().unwrap_or(usize::MAX), &keys[n]) + }); all.truncate(limit.unwrap_or(usize::MAX)); let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); let jobs = jobs.unwrap_or(cores * 2 / 3).max(1); diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index b08d11168..3a6e66f5c 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true publish.workspace = true [dependencies] +mimalloc = { workspace = true, optional = true } blake3.workspace = true zlib-rs.workspace = true tracing.workspace = true @@ -25,6 +26,9 @@ tempfile.workspace = true [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diagnostics = [] +# The Rust side allocates through mimalloc (per-thread caches) instead of the +# process heap it shares with the title and the drivers. +mimalloc = ["dep:mimalloc"] [lints] workspace = true diff --git a/crates/victory-gpu/examples/lut3d_probe.rs b/crates/victory-gpu/examples/lut3d_probe.rs index 917e82259..5e591f9f0 100644 --- a/crates/victory-gpu/examples/lut3d_probe.rs +++ b/crates/victory-gpu/examples/lut3d_probe.rs @@ -148,6 +148,67 @@ fn main() -> windows::core::Result<()> { } } let device = device.expect("an NVIDIA adapter"); + // PRELOAD=1: the composite's three samplers made first, each in a root signature + // of its own (register 0, visible to all stages), kept: the fixed order a run + // makes its known static samplers in before any pipeline + // (`pipeline::samplers`). PRELOAD=rev: in the other order. + let mut preloaded: Vec = Vec::new(); + if let Some(order) = std::env::var_os("PRELOAD") { + let mut filters = vec![ + D3D12_FILTER_MIN_MAG_MIP_POINT, + D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, + D3D12_FILTER_MIN_MAG_MIP_LINEAR, + ]; + if order == "rev" { + filters.reverse(); + } + // PRELOAD=lin: the linear one first (another place than PRELOAD=1 gives it). + if order == "lin" { + filters.swap(0, 1); + } + // PRELOAD_ODD=1: made at another register and visible to the pixel stage only + // (does the driver's table tell samplers apart by their state alone?). + let odd = std::env::var_os("PRELOAD_ODD").is_some(); + for filter in filters { + let sampler = D3D12_STATIC_SAMPLER_DESC { + Filter: filter, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + BorderColor: D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, + MaxLOD: 12.0, + ShaderRegister: if odd { 5 } else { 0 }, + RegisterSpace: if odd { 7 } else { 0 }, + ShaderVisibility: if odd { + D3D12_SHADER_VISIBILITY_PIXEL + } else { + D3D12_SHADER_VISIBILITY_ALL + }, + ..Default::default() + }; + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumStaticSamplers: 1, + pStaticSamplers: &sampler, + ..Default::default() + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None)?; + let blob = blob.unwrap(); + let bytes = std::slice::from_raw_parts( + blob.GetBufferPointer().cast::(), + blob.GetBufferSize(), + ); + preloaded.push(device.CreateRootSignature(0, bytes)?); + } + println!("the composite's samplers made first, one root signature each"); + } let fill = compile(s!("fill")); let probe = compile(s!("probe")); // SHIFT=: n root signatures with static point samplers of their own made (and diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index e7153c1b3..eeea7e4e5 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -737,31 +737,32 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { l.SetComputeRootDescriptorTable(2, views.image); l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress()); l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress()); - let run = |pso: &ID3D12PipelineState, x, y, z| { + let run = |name, pso: &ID3D12PipelineState, x: u32, y: u32, z: u32| { + list.trace_gpu_pass(name, [x.into(), y.into(), z.into(), 0, 0]); l.SetPipelineState(pso); l.Dispatch(x, y, z); uav_barrier(l); }; match role { Role::Radiance => { - run(&pass.keep, 8, 9, 1); - run(&pass.mean, 1, 1, 1); + run("ambient: keep", &pass.keep, 8, 9, 1); + run("ambient: mean", &pass.mean, 1, 1, 1); KEPT.store(true, Ordering::Relaxed); } - Role::Air => run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)), + Role::Air => run("ambient: air", &pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)), Role::Resolve => { if constant == 0.0 { - run(&pass.place, 8, 9, 1); - run(&pass.gather, 20, 45, 1); + run("ambient: place", &pass.place, 8, 9, 1); + run("ambient: gather", &pass.gather, 20, 45, 1); } - run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); + run("ambient: raise", &pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); } Role::Miss => { // The points afresh, from this frame's depth: the diffuse // stand-in makes them later in the frame. - run(&pass.place, 8, 9, 1); - run(&pass.gather, 20, 45, 1); - run(&pass.reflect, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); + run("ambient: place", &pass.place, 8, 9, 1); + run("ambient: gather", &pass.gather, 20, 45, 1); + run("ambient: reflect", &pass.reflect, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); } } } diff --git a/crates/victory-gpu/src/bench.rs b/crates/victory-gpu/src/bench.rs new file mode 100644 index 000000000..8bc314ece --- /dev/null +++ b/crates/victory-gpu/src/bench.rs @@ -0,0 +1,810 @@ +//! A frame-rate estimate without the title (`victory bench`): the per-frame work a run's log +//! counted (bytes refreshed, sent up, landed; askings of the write watch) is run again through +//! this build's own code on memory made as the runtime makes the title's, each step timed, and +//! the steps put together as the threads that carry them: the submitting thread, the relay +//! (landing what shaders wrote) and the card. The slowest of them sets the frame. +//! +//! Measured here (this build's code): each submission's one asking of the write watch +//! (`watch::ask_once`) and its refresh steps as a submission runs them (`host::bench_refreshes`: +//! the batch, the copies known to copy nothing told so as they come, the rest checked and +//! copied on the refreshing threads, into host copies made as the runtime makes them), the +//! sending up of submissions' bytes (`shadow::copy_all`), the landing of what the card +//! wrote (`land::piece`, on as many threads as the run had), and the heaps' records' asking +//! and compare (`watch::Tracked::take`, `safecopy::changed`). Taken from the log as it was: +//! the rest of the submitting thread's work (sending lists, D3D12 calls, other steps), the +//! relay's waits for the card, the records' making, and the card's own time. So the +//! estimate follows changes to the measured steps; others need a new log. +//! +//! # How the threads make a frame +//! +//! The title, the submitting thread, the relay and the card work as a pipeline: each frame +//! waits for the slowest of them, so the estimate is the largest of four times per frame. +//! +//! - **The submitting thread.** The log's "that thread worked" counts the whole of each +//! submission, its waits for the card included ("stood waiting for the card"). In +//! card-bound windows (below) those waits are the card's time showing through and are +//! taken out (they come back through the card's term); elsewhere the few ms are the +//! pipeline's friction and stay. Then the logged steps this build measures are put in +//! place of the logged ones. +//! - **The relay**: its landing, with the merging measured. +//! - **The card.** The log has no clock of the card's work, only of its queue: "nothing of +//! ours queued" is idle; the rest ("busy") is work *or* the card standing at a wait inside +//! a submission, and in most windows it is about the submitting thread's own time, which +//! is what a queue fed by a slower thread looks like either way. Busy is therefore an upper +//! bound. It is the card's time only where the card held the pipeline up: the windows where +//! the submitting thread stood waiting for the card (5 ms or more a frame; "card-bound" +//! below). In the others the card's time is estimated from the card-bound windows of the +//! same run, as a line through their busy time against their draws a frame, and never above +//! that window's busy. (That line comes from windows where the card was slow, so it leans +//! high: the estimate does not promise frame rates the card may not reach.) Without three +//! card-bound windows to draw it through, busy is taken as it is. Our own passes that a +//! build measures as gone from the card ([`Measured::card_saved_ms`]) come off this term. +//! The report also gives the frame rate if the card kept up (only the CPU's threads and the +//! card-bound windows' busy), the most CPU-side work could bring. +//! - **The title**, its own time a frame: frame time less what its threads waited at +//! presents for us. That includes its waits on fences we set, so per window it is an upper +//! bound; the floor used is the run's 10th percentile of it. +//! +//! The split of the card's frame printed: busy (of which our water passes, which have GPU +//! timestamps, `host::water_timing`), idle while the submitting thread worked (the card fed +//! late, waiting on us) and idle while the title had not submitted. + +use std::fmt::Write as _; +use std::path::Path; +use std::time::Instant; + +const PAGE: usize = 4096; +const BLOCK: usize = crate::land::BLOCK; + +/// One frame-rate line of a log (5 s) and the lines about the same seconds. +#[derive(Clone, Debug, Default)] +pub struct Window { + pub at: String, + pub fps: f64, + pub frame_ms: f64, + pub draws: f64, + /// Frame line: refreshes' copies (ms, MB). + pub copies_ms: f64, + pub copies_mb: f64, + /// The submitting thread: what it worked, and of it the write watch's askings. + pub submit_ms: f64, + pub watch_ms: f64, + /// Of its list steps, the refreshes: ms, how many, how many known to copy nothing. + pub refresh_ms: f64, + pub refreshes: f64, + pub refreshes_nothing: f64, + /// Submissions per frame (each asks the write watch). + pub submissions: f64, + /// Bytes of submissions sent up: MB, runs, ms taking them. + pub sent_mb: f64, + pub sent_runs: f64, + pub sent_ms: f64, + /// The relay: landing in all, waiting for fetches. + pub relay_ms: f64, + pub fetch_wait_ms: f64, + /// Landing: merging (ms), pieces, pages with a new byte. + pub merge_ms: f64, + pub pieces: f64, + pub new_pages: f64, + pub land_threads: f64, + /// The card: time nothing of ours was queued; of that, while the submitting thread + /// worked (the card fed late); the submitting thread standing waiting for the card. + pub card_idle_ms: f64, + pub card_behind_ms: f64, + pub submit_waited_ms: f64, + /// The title's threads waiting at presents (for us). + pub title_waited_ms: f64, + /// Our water passes on the card (GPU timestamps; `host::water_timing`). + pub water_ms: f64, + /// The present call's time a frame on the thread that presents (Streamline's line), and + /// whether this run already presented on a thread of its own (`VICTORY_PRESENT_THREAD`). + pub present_ms: f64, + pub present_apart: bool, + /// The title's busiest thread's own code a frame, sampled (`VICTORY_CPU_STAGES`, "the + /// title's floor"); 0 where the log has no such line. + pub title_own_ms: f64, + /// Host copies in the card's memory (MB): the title memory the write watch covers. + pub copies_held_mb: f64, + /// Our passes on the card per frame: hash passes and their pieces, compare passes and + /// the pieces compared. + pub hash_passes: f64, + pub hashed_pieces: f64, + pub compare_passes: f64, + pub compared_pieces: f64, + /// The heaps' records copied as bytes (`crate::descriptor::sync_heaps`, a thread of its + /// own): changed heap pages, new records on them, rounds, and its ms in all, asking the + /// write watch, reading and comparing. + pub heap_pages: f64, + pub heap_changed: f64, + pub heap_rounds: f64, + pub heap_ms: f64, + pub heap_ask_ms: f64, + pub heap_read_ms: f64, +} + +/// The number right after `key` in `line` (spaces skipped). +fn after(line: &str, key: &str) -> Option { + let rest = &line[line.find(key)? + key.len()..]; + let rest = rest.trim_start(); + let end = rest.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == 'e')).unwrap_or(rest.len()); + rest[..end].trim_end_matches('.').parse().ok() +} + +/// The number right before `key` in `line`. +fn before(line: &str, key: &str) -> Option { + let head = line[..line.find(key)?].trim_end(); + let start = head.rfind(|c: char| !(c.is_ascii_digit() || c == '.')).map_or(0, |i| i + 1); + head[start..].parse().ok() +} + +/// The frame-rate windows of a log with what the lines about the same seconds said. A +/// window's other lines are those printed since the frame-rate line before it. +pub fn windows(log: &str) -> Vec { + let mut out = Vec::new(); + let mut w = Window::default(); + for line in log.lines() { + if line.contains("victory_gpu::host:") && line.contains(" fps, ") && line.contains("ms/frame") { + let fields = || -> Option { + let mut n = w.clone(); + n.at = line.get(..19).unwrap_or("").to_owned(); + n.fps = before(line, " fps,")?; + n.frame_ms = before(line, " ms/frame")?; + n.draws = before(line, " draws/frame")?; + let copies = &line[line.find("copies ")?..]; + n.copies_ms = after(copies, "copies")?; + n.copies_mb = before(copies, " MB")?; + Some(n) + }; + if let Some(n) = fields() { + out.push(n); + } + let held = w.copies_held_mb; + w = Window { copies_held_mb: held, ..Window::default() }; + continue; + } + if line.contains("preparing per frame, the submitting thread:") { + w.watch_ms = before(line, " asking the write watch").unwrap_or(0.0); + w.refresh_ms = after(line, "(refreshes").unwrap_or(0.0); + w.refreshes = after(line, " flushes of").unwrap_or(0.0); + w.refreshes_nothing = before(line, " of them known to copy nothing").unwrap_or(0.0); + } else if line.contains("submissions prepared by a thread of ours") { + w.submissions = after(line, "per frame (VICTORY_ASYNC_SUBMIT):").unwrap_or(0.0); + w.submit_ms = after(line, "that thread worked").unwrap_or(0.0); + w.title_waited_ms = before(line, " ms at presents").unwrap_or(0.0); + } else if line.contains("bytes of submissions' own sent up per frame") { + w.sent_mb = after(line, "(VICTORY_SEND_OWN):").unwrap_or(0.0); + w.sent_runs = before(line, " runs").unwrap_or(0.0); + w.sent_ms = before(line, " ms taking them").unwrap_or(0.0); + } else if line.contains("the relay per frame") { + w.relay_ms = before(line, " ms landing in all").unwrap_or(0.0); + w.fetch_wait_ms = before(line, " ms for fetches").unwrap_or(0.0); + } else if line.contains("landing per frame (VICTORY_LAND=") { + w.land_threads = before(line, " threads)").unwrap_or(1.0); + w.merge_ms = after(line, "merging what was fetched").unwrap_or(0.0); + } else if line.contains("victory_gpu::land: landed per frame:") { + w.pieces = after(line, "landed per frame:").unwrap_or(0.0); + w.new_pages = before(line, " with a new byte (").unwrap_or(0.0); + } else if line.contains("the card's clock per frame: nothing of ours queued") { + w.card_idle_ms = after(line, "nothing of ours queued").unwrap_or(0.0); + w.card_behind_ms = before(line, " ms of that while the submitting thread").unwrap_or(0.0); + w.submit_waited_ms = after(line, "stood waiting for the card").unwrap_or(0.0); + } else if line.contains("DLSS Frame Generation, time per frame") { + w.present_ms = before(line, " ms in it").unwrap_or(0.0); + } else if line.contains("presents on a thread of their own") { + w.present_apart = true; + } else if line.contains("cpu stages, the title's threads per frame") { + w.title_own_ms = after(line, "the title's floor (its busiest thread's own code)").unwrap_or(0.0); + } else if line.contains("water light GPU time") { + w.water_ms += after(line, "ms_per_frame=").unwrap_or(0.0); + } else if line.contains("host copies in the card's memory:") && line.contains(" copies ") { + w.copies_held_mb = before(line, " MB, their bytes").unwrap_or(w.copies_held_mb); + w.compared_pieces = before(line, " pieces compared on the card").unwrap_or(0.0); + } else if line.contains("our passes over copies in the card's memory per frame:") { + w.hash_passes = after(line, "memory per frame:").unwrap_or(0.0); + w.hashed_pieces = before(line, " pieces after").unwrap_or(0.0); + w.compare_passes = before(line, " compare passes").unwrap_or(0.0); + } else if line.contains("descriptor records the title copied into its heap as bytes") { + w.heap_pages = after(line, "not looked for): per frame").unwrap_or(0.0); + w.heap_changed = before(line, " whose record was new").unwrap_or(0.0) + + before(line, " new ones of draws' tables").unwrap_or(0.0) + + before(line, " that waited for a draw first").unwrap_or(0.0); + w.heap_ms = before(line, " ms (").unwrap_or(0.0); + w.heap_ask_ms = before(line, " ms asking").unwrap_or(0.0); + w.heap_read_ms = before(line, " reading and comparing").unwrap_or(0.0); + } else if line.contains("the heaps' records, rounds per frame:") { + w.heap_rounds = after(line, "rounds per frame:").unwrap_or(0.0); + } + } + out +} + +/// Gameplay windows: drawing a world (many draws) with the submitting thread's lines there. +pub fn gameplay(all: &[Window]) -> Vec { + all.iter().filter(|w| w.draws >= 1000.0 && w.submit_ms > 0.0 && w.fps > 0.0).cloned().collect() +} + +/// Title memory as the runtime makes it: a view of a pagefile section, noted as it notes it. +/// Kept for the process (the journal of writes knows its addresses). +struct Title { + at: usize, + len: usize, +} + +impl Title { + fn new(len: usize) -> Option { + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, PAGE_READWRITE}; + // SAFETY: a section of our own and a view of it. + unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + (len as u64 >> 32) as u32, + len as u32, + std::ptr::null(), + ); + if section.is_null() { + return None; + } + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + if at == 0 { + return None; + } + crate::inplace::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::inplace::title_memory_view(at, len, section as usize, 0); + // Every page there (as a running title's are). + std::ptr::write_bytes(at as *mut u8, 1, len); + Some(Title { at, len }) + } + } +} + +/// Least of `runs` timings of `f`, in ms. +fn best(runs: usize, mut f: impl FnMut()) -> f64 { + let mut least = f64::MAX; + for _ in 0..runs { + let t = Instant::now(); + f(); + least = least.min(t.elapsed().as_secs_f64() * 1e3); + } + least +} + +/// This build's time for one window's work, per frame. +#[derive(Clone, Copy, Debug, Default)] +pub struct Measured { + pub watch_ms: f64, + pub copies_ms: f64, + pub sent_ms: f64, + pub merge_ms: f64, + /// The card's time a frame this build no longer spends against the logged run (our own + /// passes measured less: 0 when nothing measures them). Comes off the card's term. + pub card_saved_ms: f64, + /// The heaps' records: asking the write watch, reading and comparing. + pub heap_ask_ms: f64, + pub heap_read_ms: f64, +} + +/// A placed heap of descriptors as the records' rounds see it: title memory the write +/// watch tracks (`watch::Tracked`, as `crate::descriptor` keeps one per heap), and the +/// records last seen of it. +struct Heap { + title: Title, + tracked: crate::watch::Tracked, + seen: Vec<u8>, +} + +impl Heap { + fn new(len: usize) -> Option<Heap> { + let title = Title::new(len)?; + let tracked = crate::watch::track(title.at, title.len, true)?; + // (as last seen: what is there now) + // SAFETY: the view, all of it. + let seen = unsafe { std::slice::from_raw_parts(title.at as *const u8, title.len) }.to_vec(); + Some(Heap { title, tracked, seen }) + } +} + +/// The heaps' records' work of a window, per frame: its rounds each ask the write watch +/// about the heap after the title wrote that round's share of the changed pages, and the +/// changed pages' records are read where they are and compared with those last seen +/// (`safecopy::changed`, as with `VICTORY_SYNC_IN_PLACE=1`) on the records' threads, eight +/// pages a job. (ask ms, read ms); zeros without such work or a safe copy. +fn measure_heap(w: &Window, heap: &mut Heap, next: &mut dyn FnMut() -> usize) -> (f64, f64) { + const HEAP_PAGE: usize = crate::watch::PAGE; + const RECORD: usize = 32; + if w.heap_pages < 1.0 || !crate::safecopy::on() { + return (0.0, 0.0); + } + let heap_pages = heap.title.len / HEAP_PAGE; + let pages = (w.heap_pages.round() as usize).clamp(1, heap_pages); + let rounds = (w.heap_rounds.round() as usize).max(1); + let per_page = ((w.heap_changed / w.heap_pages).round() as usize).clamp(1, HEAP_PAGE / RECORD); + let (mut ask_ms, mut read_ms) = (f64::MAX, f64::MAX); + let mut stamp = 0u32; + for _ in 0..3 { + stamp += 1; + let chosen: Vec<usize> = (0..pages).map(|_| next() % heap_pages).collect(); + // The rounds: the title writes a share of the pages' records (not timed), the + // round asks about all of the heap. + let mut asking = 0.0; + for share in chosen.chunks(pages.div_ceil(rounds)) { + for &page in share { + for r in 0..per_page { + let record = (r * (HEAP_PAGE / RECORD) / per_page) * RECORD; + // SAFETY: inside the view. + unsafe { std::ptr::write_volatile((heap.title.at + page * HEAP_PAGE + record) as *mut u32, stamp) }; + } + } + let t = Instant::now(); + std::hint::black_box(heap.tracked.take(heap.title.at, heap.title.at + heap.title.len)); + asking += t.elapsed().as_secs_f64() * 1e3; + } + for _ in share_rest(pages, rounds) { + let t = Instant::now(); + std::hint::black_box(heap.tracked.take(heap.title.at, heap.title.at + heap.title.len)); + asking += t.elapsed().as_secs_f64() * 1e3; + } + ask_ms = ask_ms.min(asking); + // Reading and comparing the changed pages, eight a job. + let (title_at, seen_at) = (heap.title.at, heap.seen.as_mut_ptr() as usize); + let jobs: Vec<&[usize]> = chosen.chunks(8).collect(); + let t = Instant::now(); + crate::land::each_view(true, jobs.len(), &|n| { + let mut bits = vec![0u64; (HEAP_PAGE / RECORD).div_ceil(64)]; + for &page in jobs[n] { + bits.iter_mut().for_each(|b| *b = 0); + // SAFETY: the view's page and the records last seen of it; the jobs' pages + // are read by one job each at a time (a page twice in a job is read twice). + unsafe { + crate::safecopy::changed( + (title_at + page * HEAP_PAGE) as *const u8, + (seen_at + page * HEAP_PAGE) as *mut u8, + HEAP_PAGE / RECORD, + &mut bits, + ) + }; + std::hint::black_box(&bits); + } + }); + read_ms = read_ms.min(t.elapsed().as_secs_f64() * 1e3); + } + (ask_ms, read_ms) +} + +/// The rounds past those that found a share of the pages (rounds that found nothing). +fn share_rest(pages: usize, rounds: usize) -> std::ops::Range<usize> { + let asked = pages.div_ceil(pages.div_ceil(rounds).max(1)); + 0..rounds.saturating_sub(asked) +} + +/// Host copies of title memory for the refreshes, made once: [`Rig::COPIES`] copies +/// of [`Rig::COPY`] bytes each, side by side from the title memory's start, as the +/// heap's buffer views are (some 4,100 copies a frame refreshes). The first half +/// take the refreshes that copy; the second half the ones known to copy nothing +/// (refreshed whole once, here, and not written by the title since). +struct Rig { + copies: Vec<std::sync::Arc<crate::shadow::Shadow>>, +} + +impl Rig { + const COPIES: usize = 4096; + const COPY: usize = 128 << 10; + + fn new(title: &Title) -> Rig { + let count = Self::COPIES.min(title.len / Self::COPY); + // The copies' CPU sides: never let go, as the copies are not. + let data: &'static mut [u8] = Box::leak(vec![0u8; count * Self::COPY].into_boxed_slice()); + let copies: Vec<_> = (0..count) + .map(|i| { + let start = (title.at + i * Self::COPY) as u64; + // SAFETY: inside the leaked block, `COPY` bytes each, apart. + let at = unsafe { data.as_mut_ptr().add(i * Self::COPY) }; + crate::shadow::Shadow::unbacked_for_bench(start, at, Self::COPY as u64, true) + }) + .collect(); + // Every copy refreshed whole once (as a running title's are by now). + let all: Vec<_> = copies.iter().map(|c| (c.clone(), c.span().0 as usize, Self::COPY)).collect(); + let _ = crate::host::bench_refreshes(&[all.clone()]); + let _ = crate::host::bench_refreshes(&[all]); + copies.iter().for_each(|c| { + c.take_card_dirty(); + }); + Rig { copies } + } +} + +/// Runs a window's per-frame work through this build's code. +fn measure(w: &Window, title: &Title, rig: &Rig, held: &mut [u8], card: &mut [u8], heap: Option<&mut Heap>) -> Measured { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 8) as usize + }; + // The submissions' refresh steps, through the real code (`host::bench_refreshes`): + // each submission asks the write watch once for what it refreshes, then its steps go + // into a batch and are flushed. Of the frame's refresh steps (the log's count), those + // known to copy nothing are of copies the title did not write; the others are of copies + // whose ranges it wrote since the last frame, the copies' bytes (the log's MB) between + // them, a range each. + let half = (rig.copies.len() / 2).max(1); + let copying = ((w.refreshes - w.refreshes_nothing).round().max(1.0) as usize).min(half); + let nothing = w.refreshes_nothing.round() as usize; + let size = (((w.copies_mb * 1e6) as usize / copying).div_ceil(PAGE).max(1) * PAGE).min(Rig::COPY); + let writing: Vec<usize> = (0..copying).collect(); + let asks = w.submissions.round().max(1.0) as usize; + let mut steps: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::with_capacity(copying + nothing); + // (A no-op step for every copying one and more, spread through the submissions.) + for k in 0..copying + nothing { + if k < copying { + let c = &rig.copies[writing[k]]; + steps.push((c.clone(), c.span().0 as usize, size)); + } else { + let c = &rig.copies[half + (k - copying) % (rig.copies.len() - half).max(1)]; + let off = (next() % (Rig::COPY / PAGE)) * PAGE; + steps.push((c.clone(), c.span().0 as usize + off, PAGE.min(Rig::COPY - off))); + } + } + // Mixed as a frame's lists mix them. + for i in (1..steps.len()).rev() { + steps.swap(i, next() % (i + 1)); + } + let per = steps.len().div_ceil(asks).max(1); + let submissions: Vec<Vec<_>> = steps.chunks(per).map(<[_]>::to_vec).collect(); + let (mut watch_ms, mut copies_ms) = (f64::MAX, f64::MAX); + for round in 0..3u32 { + // The title's writes (its own cost, not timed): a dword in every KiB of the ranges + // the copying refreshes take. + for &i in &writing { + let at = rig.copies[i].span().0 as usize; + for p in (0..size).step_by(1024) { + // SAFETY: inside the view (the copies lie in it). + unsafe { std::ptr::write_volatile((at + p) as *mut u32, round.wrapping_add(7)) }; + } + } + let (asking, refreshing) = crate::host::bench_refreshes(&submissions); + watch_ms = watch_ms.min(asking); + copies_ms = copies_ms.min(refreshing); + // (What went to the card's lists is sent: not timed here, see below.) + for c in &rig.copies { + c.take_card_dirty(); + } + } + // Sending up: submissions' bytes in their runs, by `copy_all` (its threads included). + let sent = ((w.sent_mb * 1e6) as usize).min(card.len()); + let runs = w.sent_runs.round().max(1.0) as usize; + let run = (sent / runs).max(1); + let sent_ms = best(3, || { + let copies: Vec<(usize, usize, usize)> = (0..runs) + .map(|i| { + let from = title.at + (next() % (title.len - run)) / 64 * 64; + (from, card.as_mut_ptr() as usize + (i * run) % (card.len() - run), run) + }) + .collect(); + crate::shadow::copy_all(copies); + }); + // Landing: the pieces the card wrote, with their pages' new bytes (every dword), merged + // into title memory and the held copy on the landing's threads. + let pieces = (w.pieces.round() as usize).min(card.len() / BLOCK).min(title.len / BLOCK); + let new_share = if w.pieces > 0.0 { w.new_pages / (w.pieces * (BLOCK / PAGE) as f64) } else { 0.0 }; + let threads = (w.land_threads.round() as usize).max(1); + let blocks = title.len / BLOCK; + let at: Vec<usize> = (0..pieces).map(|_| next() % blocks).collect(); + let mut round = 0u32; + let mut merge_ms = f64::MAX; + for _ in 0..3 { + round += 1; + for (k, &b) in at.iter().enumerate() { + for page in 0..BLOCK / PAGE { + let from = k * BLOCK + page * PAGE; + let old = b * BLOCK + page * PAGE; + card[from..from + PAGE].copy_from_slice(&held[old..old + PAGE]); + if (page as f64 + 0.5) / (BLOCK / PAGE) as f64 <= new_share { + for d in card[from..from + PAGE].chunks_exact_mut(4) { + d.copy_from_slice(&round.wrapping_mul(0x0101_0101).to_le_bytes()); + } + } + } + } + let work: Vec<(usize, usize, usize)> = at + .iter() + .enumerate() + .map(|(k, &b)| (title.at + b * BLOCK, card.as_ptr() as usize + k * BLOCK, held.as_mut_ptr() as usize + b * BLOCK)) + .collect(); + let t = Instant::now(); + crate::land::bench_land(&work, threads); + merge_ms = merge_ms.min(t.elapsed().as_secs_f64() * 1e3); + } + let (heap_ask_ms, heap_read_ms) = match heap { + Some(heap) => measure_heap(w, heap, &mut next), + None => (0.0, 0.0), + }; + Measured { watch_ms, copies_ms, sent_ms, merge_ms, card_saved_ms: 0.0, heap_ask_ms, heap_read_ms } +} + +/// What the card's term of a run is drawn from ([`card_model`]): a line through the +/// card-bound windows' busy time against their draws, and the title's floor. +#[derive(Clone, Copy, Debug, Default)] +pub struct CardModel { + /// Busy ms = `.0` + `.1` × draws, if three card-bound windows or more drew it. + pub line: Option<(f64, f64)>, + pub card_bound_windows: usize, + /// The title's own time a frame: the run's 10th percentile of frame less its waits at + /// presents. + pub title_floor_ms: f64, +} + +/// The submitting thread stood waiting for the card this long a frame or more: the card +/// held the pipeline up, and its busy time is its own. +const CARD_BOUND_MS: f64 = 5.0; + +fn busy(w: &Window) -> f64 { + (w.frame_ms - w.card_idle_ms).max(0.0) +} + +fn card_bound(w: &Window) -> bool { + w.submit_waited_ms >= CARD_BOUND_MS +} + +/// [`CardModel`] of a run's gameplay windows. +pub fn card_model(play: &[Window]) -> CardModel { + let points: Vec<(f64, f64)> = play.iter().filter(|w| card_bound(w)).map(|w| (w.draws, busy(w))).collect(); + let line = (points.len() >= 3).then(|| { + let n = points.len() as f64; + let mx = points.iter().map(|p| p.0).sum::<f64>() / n; + let my = points.iter().map(|p| p.1).sum::<f64>() / n; + let sxx: f64 = points.iter().map(|p| (p.0 - mx).powi(2)).sum(); + let sxy: f64 = points.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum(); + // (more draws never make less card work: a falling line is taken flat) + let b = if sxx > 0.0 { (sxy / sxx).max(0.0) } else { 0.0 }; + (my - b * mx, b) + }); + let mut own: Vec<f64> = play.iter().map(|w| (w.frame_ms - w.title_waited_ms).max(0.0)).collect(); + own.sort_by(f64::total_cmp); + let title_floor_ms = own.get(own.len() / 10).copied().unwrap_or(0.0); + CardModel { line, card_bound_windows: points.len(), title_floor_ms } +} + +/// A window's frame put together: the threads' times per frame (ms). +#[derive(Clone, Copy, Debug, Default)] +pub struct Estimate { + /// The submitting thread's own work (its waits for the card out). + pub submit_ms: f64, + pub relay_ms: f64, + /// The card's time (the model), and its queue's busy time (the upper bound). + pub card_ms: f64, + pub card_busy_ms: f64, + pub title_ms: f64, + /// The heaps' records' thread (submissions wait for its rounds). + pub records_ms: f64, + pub frame_ms: f64, + /// The frame if the card kept up wherever the log does not show it holding the + /// pipeline up (the CPU's threads, the title, and the card-bound windows' card). + pub cpu_frame_ms: f64, + /// Which of them sets the frame. + pub bound: &'static str, +} + +/// The submitting thread with the measured steps in place of the logged ones; the relay +/// likewise, and the heaps' records; the card as [`card_model`] has it; the title's floor. +fn present_apart_on() -> bool { + std::env::var_os("VICTORY_PRESENT_THREAD").is_none_or(|v| v != "0") +} + +pub fn estimate(w: &Window, m: &Measured, model: &CardModel) -> Estimate { + // (its waits for the card out where they are the card's time; short ones, in windows the + // card did not hold up, are the pipeline's friction and stay) + let waits = if card_bound(w) { w.submit_waited_ms } else { 0.0 }; + // A run that presented on the submitting thread: this build presents on a thread of its + // own (`VICTORY_PRESENT_THREAD`, on unless 0), so the present call's time comes off it. + // (A model, not a measurement: the call's time moves to the presenting thread.) + let moved = if !w.present_apart && present_apart_on() { w.present_ms } else { 0.0 }; + let submit_ms = (w.submit_ms - waits - moved - w.watch_ms - w.refresh_ms - w.sent_ms).max(0.0) + + m.watch_ms + + m.copies_ms + + m.sent_ms; + let relay_ms = (w.relay_ms - w.merge_ms).max(0.0) + m.merge_ms; + let card_busy_ms = busy(w); + let card_ms = if card_bound(w) { + card_busy_ms + } else { + model.line.map_or(card_busy_ms, |(a, b)| (a + b * w.draws).clamp(0.0, card_busy_ms)) + }; + let card_ms = (card_ms - m.card_saved_ms).max(0.0); + // (sampled where the log has it: the busiest title thread's own code; else the run's floor) + let title_ms = if w.title_own_ms > 0.0 { w.title_own_ms } else { model.title_floor_ms }; + let records_ms = if w.heap_ms > 0.0 { + (w.heap_ms - w.heap_ask_ms - w.heap_read_ms).max(0.0) + m.heap_ask_ms + m.heap_read_ms + } else { + 0.0 + }; + let terms = [(submit_ms, "submit"), (relay_ms, "relay"), (card_ms, "card"), (title_ms, "title"), (records_ms, "records")]; + let (frame_ms, bound) = terms.iter().copied().fold((0.0, "submit"), |a, t| if t.0 > a.0 { t } else { a }); + let card_kept_up = if card_bound(w) { card_ms } else { 0.0 }; + let cpu_frame_ms = submit_ms.max(relay_ms).max(title_ms).max(records_ms).max(card_kept_up); + Estimate { submit_ms, relay_ms, card_ms, card_busy_ms, title_ms, records_ms, frame_ms, cpu_frame_ms, bound } +} + +fn median(mut v: Vec<f64>) -> f64 { + if v.is_empty() { + return 0.0; + } + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// The number on a report's first line that begins with `head`, right after `key`. +fn reported(report: &str, head: &str, key: &str) -> Option<f64> { + report.lines().find(|l| l.starts_with(head)).and_then(|l| after(l, key)) +} + +/// The report of `victory bench` for a log: per gameplay window the estimate against the +/// frame rate the run had, and the steps measured against the logged ones. With `compare`, +/// an earlier report (of another build, on the same log) to set this one's against. +pub fn run(log_path: &Path, compare: Option<&Path>) -> anyhow::Result<String> { + let earlier = compare.map(std::fs::read_to_string).transpose()?; + let log = std::fs::read_to_string(log_path)?; + let all = windows(&log); + let play = gameplay(&all); + anyhow::ensure!(!play.is_empty(), "no gameplay frame-rate lines (1,000 draws a frame or more) in {}", log_path.display()); + let model = card_model(&play); + let held_mb = play.iter().map(|w| w.copies_held_mb).fold(0.0, f64::max).clamp(256.0, 2048.0); + let title = Title::new(((held_mb * 1e6) as usize).div_ceil(BLOCK) * BLOCK) + .ok_or_else(|| anyhow::anyhow!("no title memory of {held_mb:.0} MB"))?; + let most = |f: fn(&Window) -> f64| play.iter().map(f).fold(0.0, f64::max); + let rig = Rig::new(&title); + let mut held = vec![0u8; title.len]; + let card_len = ((most(|w| w.sent_mb).max(most(|w| w.pieces) * BLOCK as f64 / 1e6) * 1e6) as usize).max(4 << 20) + (4 << 20); + let mut card = vec![0u8; card_len]; + // A heap of descriptors of the size the title's placed one has (2,048 records of 32 bytes + // a 64 KiB page; 185 MB in the runs of 2026-11-27). + let mut heap = play.iter().any(|w| w.heap_pages > 0.0).then(|| Heap::new(185 << 20)).flatten(); + // (warm: first touches, the pool's threads, the write watch's first asking) + let _ = measure(&play[0], &title, &rig, &mut held, &mut card, heap.as_mut()); + + let mut out = String::new(); + writeln!(out, "log: {}", log_path.display())?; + writeln!(out, "title memory watched: {:.0} MB; {} gameplay windows of {} (5 s each)", title.len as f64 / 1e6, play.len(), all.len())?; + match model.line { + Some((a, b)) => writeln!( + out, + "card model: {} card-bound windows (the submitting thread waited {CARD_BOUND_MS:.0} ms or more for the card); busy = {a:.1} ms + {:.2} ms per 1,000 draws, never above a window's busy", + model.card_bound_windows, + b * 1000.0 + )?, + None => writeln!( + out, + "card model: {} card-bound windows, too few for a line: the card's busy time taken as its time (an upper bound)", + model.card_bound_windows + )?, + } + writeln!(out, "title floor: {:.1} ms a frame (10th percentile of frame less its waits at presents)\n", model.title_floor_ms)?; + writeln!( + out, + "{:<19} {:>6} {:>7} | {:>7} {:>7} {:>7} {:>7} {:>7} | {:>7} {:>6} {:>6} {:<7}", + "window", "fps", "ms", "submit", "relay", "card", "busy", "title", "est ms", "est", "error", "bound" + )?; + let (mut errors, mut est_fps, mut log_fps, mut cpu_fps) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut steps: Vec<(Measured, Window, Estimate)> = Vec::new(); + for w in &play { + let m = measure(w, &title, &rig, &mut held, &mut card, heap.as_mut()); + let e = estimate(w, &m, &model); + let fps = 1000.0 / e.frame_ms.max(1e-3); + let error = (fps - w.fps) / w.fps * 100.0; + let bound = if card_bound(w) { format!("{}*", e.bound) } else { e.bound.to_owned() }; + writeln!( + out, + "{:<19} {:>6.1} {:>7.1} | {:>7.1} {:>7.1} {:>7.1} {:>7.1} {:>7.1} | {:>7.1} {:>6.1} {:>+5.0}% {:<7}", + w.at, w.fps, w.frame_ms, e.submit_ms, e.relay_ms, e.card_ms, e.card_busy_ms, e.title_ms, e.frame_ms, fps, error, bound + )?; + errors.push(error.abs()); + est_fps.push(fps); + log_fps.push(w.fps); + cpu_fps.push(1000.0 / e.cpu_frame_ms.max(1e-3)); + steps.push((m, w.clone(), e)); + } + writeln!(out, "(* a card-bound window: its card time is its busy time)")?; + let mean = |v: &[f64]| v.iter().sum::<f64>() / v.len() as f64; + writeln!(out)?; + writeln!(out, "measured steps, median ms a frame (this build | the run's log):")?; + let pair = |f: fn(&(Measured, Window, Estimate)) -> (f64, f64)| { + let (a, b): (Vec<f64>, Vec<f64>) = steps.iter().map(f).unzip(); + (median(a), median(b)) + }; + for (name, (a, b)) in [ + ("write watch (the submission's asking)", pair(|s| (s.0.watch_ms, s.1.watch_ms))), + ("refreshes (batch, checks, copies)", pair(|s| (s.0.copies_ms, s.1.refresh_ms))), + ("sending submissions' bytes up", pair(|s| (s.0.sent_ms, s.1.sent_ms))), + ("landing (merging)", pair(|s| (s.0.merge_ms, s.1.merge_ms))), + ("heap records: asking", pair(|s| (s.0.heap_ask_ms, s.1.heap_ask_ms))), + ("heap records: reading, comparing", pair(|s| (s.0.heap_read_ms, s.1.heap_read_ms))), + ] { + writeln!(out, " {name:<38} {a:>6.1} | {b:>6.1}")?; + } + writeln!(out)?; + let logged = |f: fn(&Window) -> f64| median(play.iter().map(f).collect()); + writeln!( + out, + "the card's frame, median ms (from the log): busy {:.1} (of it our water passes {:.2}; the rest the title's work, our other passes and waits inside submissions, which the log does not tell apart), idle while the submitting thread worked {:.1} (fed late, waiting on us), idle while the title had not submitted {:.1}; the submitting thread stood waiting for the card {:.1}", + logged(busy), + logged(|w| w.water_ms), + logged(|w| w.card_behind_ms), + logged(|w| (w.card_idle_ms - w.card_behind_ms).max(0.0)), + logged(|w| w.submit_waited_ms), + )?; + let bounds = |name: &str| steps.iter().filter(|s| s.2.bound == name).count(); + writeln!( + out, + "what sets the frame, windows: the submitting thread {}, the relay {}, the card {}, the title {}", + bounds("submit"), + bounds("relay"), + bounds("card"), + bounds("title") + )?; + writeln!(out)?; + let (est, cpu) = (mean(&est_fps), mean(&cpu_fps)); + writeln!( + out, + "average frame rate: estimated {:.1} fps, the run {:.1} fps (median {:.1} | {:.1}); mean error per window {:.1} %", + est, + mean(&log_fps), + median(est_fps.clone()), + median(log_fps.clone()), + mean(&errors) + )?; + writeln!(out, "if the card kept up: {cpu:.1} fps (the CPU's threads and the title alone: the most CPU-side work could bring)")?; + writeln!( + out, + "(measured: the write watch's asking and the refreshes as submissions run them, sending up, landing, the heaps' records' asking and compare; from the log: the rest of the submitting thread, the relay's waits, the records' making, the card, the title)" + )?; + // Our own passes on the card (hashes before submissions, compares after them), on this + // PC's card with the log's counts: a pass per run as the log's build recorded them, and + // as table passes (`VICTORY_CARD_TABLE`, a pass per submission and kind here). The log + // has no card time of its own for them. + let counted: Vec<&Window> = play.iter().filter(|w| w.compare_passes > 0.0 || w.hash_passes > 0.0).collect(); + match (counted.is_empty(), crate::bench_gpu::Card::new()) { + (true, _) => writeln!(out, "host GPU passes: the log counts none")?, + (false, None) => writeln!(out, "host GPU passes: no hardware D3D12 device here; not measured")?, + (false, Some(mut card)) => { + let mut runs = Vec::new(); + let mut tables = Vec::new(); + for w in &counted { + if let Some((run, table)) = + card.frame(w.hash_passes, w.hashed_pieces, w.compare_passes, w.compared_pieces, w.submissions.max(1.0)) + { + runs.push(run); + tables.push(table); + } + } + let card_ms = median(counted.iter().map(|w| (w.frame_ms - w.card_idle_ms).max(0.0)).collect()); + writeln!( + out, + "host GPU passes measured, median ms a frame: {:.2} as a pass per run | {:.2} as table passes (log: none timed; the card busy {:.1})", + median(runs), + median(tables), + card_ms + )?; + } + } + if let (Some(earlier), Some(path)) = (earlier, compare) { + writeln!(out)?; + let change = |a: f64, b: f64| if a > 0.0 { (b - a) / a * 100.0 } else { 0.0 }; + match reported(&earlier, "average frame rate: estimated", "estimated") { + Some(before) => { + writeln!(out, "against {}: estimated {before:.1} -> {est:.1} fps ({:+.1} %)", path.display(), change(before, est))? + } + None => writeln!(out, "against {}: it has no \"average frame rate\" line", path.display())?, + } + if let Some(before) = reported(&earlier, "if the card kept up:", "if the card kept up:") { + writeln!(out, " if the card kept up: {before:.1} -> {cpu:.1} fps ({:+.1} %)", change(before, cpu))?; + } + let same_log = earlier.lines().next().is_some_and(|l| l == format!("log: {}", log_path.display())); + if !same_log { + writeln!(out, " (the earlier report is of another log: the change says little)")?; + } + } + Ok(out) +} diff --git a/crates/victory-gpu/src/bench_gpu.rs b/crates/victory-gpu/src/bench_gpu.rs new file mode 100644 index 000000000..c8cfd090a --- /dev/null +++ b/crates/victory-gpu/src/bench_gpu.rs @@ -0,0 +1,227 @@ +//! `victory bench`: the host layer's own passes on the card ([`crate::host::CARD_COMPARE`]: the +//! hashes before a submission's lists and the compares after them), timed on the first +//! hardware adapter with the counts a run's log gave: as a pass per run of pieces, and as the +//! table passes `VICTORY_CARD_TABLE` makes (a pass per copy and submission). + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows::Win32::Graphics::Dxgi::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, s}; + +const PIECE: u64 = 64 << 10; +/// The copy the passes walk: 1,024 pieces (64 MB) in the card's memory. +const COPY_PIECES: u32 = 1024; +/// Result dwords (`differs`): as many as a frame's pieces may need. +const SLOTS: u64 = 1 << 18; + +/// The device and what the passes need. +pub(crate) struct Card { + _device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + event: HANDLE, + submitted: u64, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + now: ID3D12Resource, + hashes: ID3D12Resource, + differs: ID3D12Resource, + differs_data: usize, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + back_data: usize, + ticks_per_ms: f64, +} + +fn buffer(device: &ID3D12Device, heap: D3D12_HEAP_PROPERTIES, size: u64, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES) -> windows::core::Result<ID3D12Resource> { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut made: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made)? }; + made.ok_or_else(windows::core::Error::empty) +} + +impl Card { + /// On the first hardware adapter; `None` without one. + pub(crate) fn new() -> Option<Card> { + // SAFETY: plain DXGI and D3D12 object creation and mapping. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapters(0).ok()?; + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .ok()?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + let source = crate::host::CARD_COMPARE; + let mut code: Option<ID3DBlob> = None; + D3DCompile(source.as_ptr().cast(), source.len(), s!("card compare"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None) + .ok()?; + let code = code?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes).ok()?; + let pso: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + }) + .ok()?; + let default = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let shared = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let now = buffer(&device, default, u64::from(COPY_PIECES) * PIECE, uav, D3D12_RESOURCE_STATE_COMMON).ok()?; + let hashes = buffer(&device, default, 16 * u64::from(COPY_PIECES), uav, D3D12_RESOURCE_STATE_COMMON).ok()?; + // The results in PC memory, as the host keeps them. + let differs = buffer(&device, shared, 4 * SLOTS, uav, D3D12_RESOURCE_STATE_COMMON).ok()?; + let mut data = std::ptr::null_mut(); + differs.Map(0, None, Some(&mut data)).ok()?; + let mut stamps: Option<ID3D12QueryHeap> = None; + device + .CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2, NodeMask: 0 }, &mut stamps) + .ok()?; + let back = buffer(&device, readback, 16, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST).ok()?; + let mut back_data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut back_data)).ok()?; + let ticks_per_ms = queue.GetTimestampFrequency().ok()? as f64 / 1000.0; + Some(Card { + _device: device, + queue, + allocator, + list, + fence, + event, + submitted: 0, + root, + pso, + now, + hashes, + differs, + differs_data: data as usize, + stamps: stamps?, + back, + back_data: back_data as usize, + ticks_per_ms, + }) + } + } + + /// The card's time (ms) of `passes`: each (mode, pieces), a pass per entry as the host + /// records them; with `table`, the pieces of a pass are named in their result dwords. + fn time(&mut self, passes: &[(u32, Vec<u32>)], table: bool) -> Option<f64> { + // SAFETY: our list, open; live buffers; the compare's own root signature; the result + // dwords hold every pass's pieces (`SLOTS`). + unsafe { + let list = &self.list; + list.SetComputeRootSignature(&self.root); + list.SetPipelineState(&self.pso); + list.SetComputeRootShaderResourceView(1, self.now.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, self.hashes.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, self.differs.GetGPUVirtualAddress()); + list.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + let size = (u64::from(COPY_PIECES) * PIECE) as u32; + let mut slot = 0u32; + for (mode, pieces) in passes { + if u64::from(slot) + pieces.len() as u64 > SLOTS { + break; + } + if table { + for (i, &p) in pieces.iter().enumerate() { + (self.differs_data as *mut u32).add(slot as usize + i).write_volatile(p); + } + let constants = [0u32, 0, size, pieces.len() as u32, slot * 4, mode | 4]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(pieces.len() as u32, 1, 1); + } else { + // (a run: its pieces one after the other from the first) + let constants = [pieces[0], 0, size, pieces.len() as u32, slot * 4, *mode]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(pieces.len() as u32, 1, 1); + } + slot += pieces.len() as u32; + } + list.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + list.Close().ok()?; + let cmd: ID3D12CommandList = list.cast().ok()?; + self.queue.ExecuteCommandLists(&[Some(cmd)]); + self.submitted += 1; + self.queue.Signal(&self.fence, self.submitted).ok()?; + self.fence.SetEventOnCompletion(self.submitted, self.event).ok()?; + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().ok()?; + self.list.Reset(&self.allocator, None).ok()?; + let ticks = (self.back_data as *const u64).add(1).read_volatile().saturating_sub((self.back_data as *const u64).read_volatile()); + Some(ticks as f64 / self.ticks_per_ms) + } + } + + /// A frame's hash and compare passes as a log counted them (`hash` passes over + /// `hashed` pieces, `compares` passes over `compared` pieces), with `groups` table passes + /// of each kind instead: (per run, table) ms on the card. Least of three. + pub(crate) fn frame(&mut self, hash: f64, hashed: f64, compares: f64, compared: f64, groups: f64) -> Option<(f64, f64)> { + let mut seed = 0x2545_F491_4F6C_DD1Du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 8) as u32 + }; + // Runs: the pieces cut evenly over the passes, each run at a place of its own. + let mut runs = |passes: f64, pieces: f64, mode: u32| -> Vec<(u32, Vec<u32>)> { + let passes = (passes.round() as u32).max(1); + let pieces = (pieces.round() as u32).max(passes); + (0..passes) + .map(|i| { + let n = (pieces / passes + u32::from(i < pieces % passes)).clamp(1, COPY_PIECES); + let first = next() % (COPY_PIECES - n + 1); + (mode, (first..first + n).collect()) + }) + .collect() + }; + let per_run: Vec<(u32, Vec<u32>)> = runs(hash, hashed, 0).into_iter().chain(runs(compares, compared, 2)).collect(); + // The same pieces as `groups` table passes of each kind. + let joined = |mode: u32| -> Vec<(u32, Vec<u32>)> { + let all: Vec<u32> = per_run.iter().filter(|r| r.0 == mode).flat_map(|r| r.1.iter().copied()).collect(); + let n = (groups.round() as usize).max(1); + all.chunks(all.len().div_ceil(n).max(1)).map(|c| (mode, c.to_vec())).collect() + }; + let tabled: Vec<(u32, Vec<u32>)> = joined(0).into_iter().chain(joined(2)).collect(); + let mut least = (f64::MAX, f64::MAX); + // (warm) + self.time(&per_run, false)?; + for _ in 0..3 { + least.0 = least.0.min(self.time(&per_run, false)?); + least.1 = least.1.min(self.time(&tabled, true)?); + } + Some(least) + } +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 3bbb9dd6a..5a62ee3a9 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -381,14 +381,21 @@ fn big_blocks() -> String { /// The system's allocator with every block counted in [`OWN`] (two atomic /// additions per allocation and per release: diagnostics builds only). +/// With the `mimalloc` feature the blocks come from mimalloc instead. struct Counting; +/// Where [`Counting`] gets its blocks. +#[cfg(not(feature = "mimalloc"))] +const INNER: std::alloc::System = std::alloc::System; +#[cfg(feature = "mimalloc")] +const INNER: mimalloc::MiMalloc = mimalloc::MiMalloc; + // SAFETY: every call goes to the system's allocator unchanged; only // counters are kept beside it. unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let at = unsafe { std::alloc::System.alloc(layout) }; + let at = unsafe { INNER.alloc(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); @@ -398,7 +405,7 @@ unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + let at = unsafe { INNER.alloc_zeroed(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); @@ -410,12 +417,12 @@ unsafe impl std::alloc::GlobalAlloc for Counting { own(layout.size(), false); big(at, layout.size(), false); // SAFETY: the caller's contract, passed on. - unsafe { std::alloc::System.dealloc(at, layout) }; + unsafe { INNER.dealloc(at, layout) }; } unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + let moved = unsafe { INNER.realloc(at, layout, size) }; if !moved.is_null() { own(layout.size(), false); own(size, true); diff --git a/crates/victory-gpu/src/copystat_footprint.rs b/crates/victory-gpu/src/copystat_footprint.rs new file mode 100644 index 000000000..21465fa59 --- /dev/null +++ b/crates/victory-gpu/src/copystat_footprint.rs @@ -0,0 +1,250 @@ +//! Measurement only (no behaviour change): which 64 KiB blocks of each host +//! copy shaders ever wrote, which of those the title's CPU wrote afterwards, +//! and which the title wrote while a flight's declared range held them +//! ("pending", the bytes `Shadow::merge_under_writes` puts in). Distinct +//! blocks since the copy was made, per copy, logged every ~10 s next to the +//! frame lines. It decides how much a learned GPU-write footprint (report 02, +//! R1) could narrow what is declared. `VICTORY_FOOTPRINT=0` turns it off. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +const SHIFT: u32 = 16; +const EVERY: Duration = Duration::from_secs(10); + +fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FOOTPRINT").is_none_or(|v| v != "0")) +} + +#[derive(Default)] +struct Foot { + start: u64, + len: u64, + blocks: usize, + /// Blocks shaders wrote (bytes landed in title memory). + gpu: Vec<u64>, + /// Blocks the title's CPU changed after shaders had written them. + cpu_after: Vec<u64>, + /// Blocks the title wrote while a flight's range held them. + pending: Vec<u64>, + /// Events: landings, CPU changes seen, pending merges. + events: [u64; 3], + /// Window of the last event (pruning). + last: u64, +} + +fn mark(bits: &mut [u64], i: usize) { + bits[i / 64] |= 1u64 << (i % 64); +} + +fn has(bits: &[u64], i: usize) -> bool { + bits[i / 64] >> (i % 64) & 1 != 0 +} + +fn count(bits: &[u64]) -> usize { + bits.iter().map(|w| w.count_ones() as usize).sum() +} + +fn count_and(a: &[u64], b: &[u64]) -> usize { + a.iter().zip(b).map(|(x, y)| (x & y).count_ones() as usize).sum() +} + +impl Foot { + fn new(start: u64, len: u64) -> Foot { + let blocks = ((start + len).div_ceil(1 << SHIFT) - (start >> SHIFT)) as usize; + let words = blocks.div_ceil(64); + Foot { start, len, blocks, gpu: vec![0; words], cpu_after: vec![0; words], pending: vec![0; words], ..Foot::default() } + } + + /// The blocks that offsets `[from, to)` of the copy lie in. + fn blocks_of(&self, from: usize, to: usize) -> std::ops::Range<usize> { + if from >= to { + return 0..0; + } + let first = (((self.start + from as u64) >> SHIFT) - (self.start >> SHIFT)) as usize; + let last = (((self.start + to as u64 - 1) >> SHIFT) - (self.start >> SHIFT)) as usize; + first.min(self.blocks)..(last + 1).min(self.blocks) + } + + fn gpu_wrote(&mut self, from: usize, to: usize) { + self.events[0] += 1; + for i in self.blocks_of(from, to) { + mark(&mut self.gpu, i); + } + } + + fn cpu_wrote(&mut self, from: usize, to: usize) { + self.events[1] += 1; + for i in self.blocks_of(from, to) { + if has(&self.gpu, i) { + mark(&mut self.cpu_after, i); + } + } + } + + fn pending_wrote(&mut self, runs: usize, spans: &[(usize, usize)]) { + self.events[2] += runs as u64; + for &(from, to) in spans { + for i in from.min(self.blocks)..to.min(self.blocks) { + mark(&mut self.pending, i); + } + } + } + + /// (blocks, shaders', title's after shaders', pending, pending and shaders'). + fn totals(&self) -> [usize; 5] { + [self.blocks, count(&self.gpu), count(&self.cpu_after), count(&self.pending), count_and(&self.pending, &self.gpu)] + } +} + +static FEET: Mutex<Option<HashMap<u64, Foot>>> = Mutex::new(None); +static WINDOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn with(id: u64, start: u64, len: u64, f: impl FnOnce(&mut Foot)) { + if !on() { + return; + } + let window = WINDOW.load(std::sync::atomic::Ordering::Relaxed); + let mut all = FEET.lock().unwrap_or_else(|e| e.into_inner()); + let foot = all.get_or_insert_with(Default::default).entry(id).or_insert_with(|| Foot::new(start, len)); + foot.last = window; + f(foot); +} + +/// Shaders wrote bytes that landed in offsets `[from, to)` of copy `id` +/// (title memory `[start, start + len)`). +pub(crate) fn gpu_wrote(id: u64, start: u64, len: u64, from: usize, to: usize) { + crate::tight::landed(id, from, to); + with(id, start, len, |f| f.gpu_wrote(from, to)); +} + +/// The title's CPU changed offsets `[from, to)` of the copy (an upper bound +/// where a refresh copies whole pages). +pub(crate) fn cpu_wrote(id: u64, start: u64, len: u64, from: usize, to: usize) { + with(id, start, len, |f| f.cpu_wrote(from, to)); +} + +/// Collapse word runs to the 64 KiB blocks tracked by the report before +/// taking the lock shared by the submitter and the copy-back workers. +fn pending_blocks(start: u64, runs: &[(usize, usize)]) -> Vec<(usize, usize)> { + let block = 1usize << SHIFT; + let skew = start as usize % block; + let mut spans: Vec<(usize, usize)> = Vec::new(); + for &(from, to) in runs { + if from < to { + let (from, to) = ((from + skew) / block, (to + skew).div_ceil(block)); + match spans.last_mut() { + Some(last) if from <= last.1 && last.0 <= to => { + *last = (last.0.min(from), last.1.max(to)); + } + _ => spans.push((from, to)), + } + } + } + spans +} + +/// The title wrote these byte ranges (offsets in the copy) while flights +/// may have been writing the same copy. +pub(crate) fn pending_wrote(id: u64, start: u64, len: u64, runs: &[(usize, usize)]) { + if runs.is_empty() || !on() { + return; + } + let spans = pending_blocks(start, runs); + with(id, start, len, |f| f.pending_wrote(runs.len(), &spans)); +} + +/// Every ~10 s, from the frame line: the totals and the eight copies shaders +/// wrote most blocks of. +pub(crate) fn log() { + // What the refreshes took, on or off (its own few seconds). + { + static SAID: Mutex<Option<Instant>> = Mutex::new(None); + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + match *said { + Some(t) if t.elapsed() < EVERY => {} + Some(t) => { + crate::shadow::refreshed_line(t.elapsed().as_secs_f64()); + *said = Some(Instant::now()); + } + None => *said = Some(Instant::now()), + } + } + if !on() { + return; + } + static LAST: Mutex<Option<Instant>> = Mutex::new(None); + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if last.is_some_and(|t| t.elapsed() < EVERY) { + return; + } + *last = Some(Instant::now()); + } + let window = WINDOW.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut rows: Vec<(u64, [usize; 5], [u64; 3], u64, u64)> = { + let mut all = FEET.lock().unwrap_or_else(|e| e.into_inner()); + let Some(all) = all.as_mut() else { + return; + }; + // Copies untouched for ten windows are gone. + all.retain(|_, f| window.saturating_sub(f.last) < 10); + all.iter().map(|(&id, f)| (id, f.totals(), f.events, f.start, f.len)).collect() + }; + rows.sort_by_key(|r| std::cmp::Reverse(r.1[1] + r.1[3])); + let sum = |i: usize| rows.iter().map(|r| r.1[i]).sum::<usize>(); + tracing::info!( + "footprint of 64 KiB blocks since each copy was made (distinct; VICTORY_FOOTPRINT=0 off): {} copies, {} blocks, \ + {} written by shaders, {} of those changed by the title after, {} written by the title while pending ({} of them \ + also shaders'); the most:", + rows.len(), + sum(0), + sum(1), + sum(2), + sum(3), + sum(4) + ); + for (id, t, e, start, len) in rows.into_iter().take(8) { + tracing::info!( + " copy {id} {start:#x}+{len:#x}: {} blocks, shaders {} ({:.0} %), then title {}, pending title {} ({} also shaders'); \ + events {} landings, {} title changes, {} pending merges", + t[0], + t[1], + 100.0 * t[1] as f64 / t[0].max(1) as f64, + t[2], + t[3], + t[4], + e[0], + e[1], + e[2] + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_distinct_blocks() { + // A copy that starts in the middle of a block: 3 blocks. + let mut f = Foot::new(0x1_8000, 0x2_8000); + assert_eq!(f.blocks, 3); + f.gpu_wrote(0, 0x100); + f.gpu_wrote(0x10, 0x20); + f.gpu_wrote(0x8000, 0x8001); + assert_eq!(f.totals()[1], 2); + f.cpu_wrote(0x8000, 0x8010); + f.cpu_wrote(0x1_8000, 0x1_8010); + assert_eq!(f.totals()[2], 1); + let runs = [(0, 0x70), (0x10, 0x8001), (0x8004, 0x8008)]; + let spans = pending_blocks(f.start, &runs); + assert_eq!(spans, [(0, 2)]); + f.pending_wrote(runs.len(), &spans); + assert_eq!(f.events[2], 3); + assert_eq!(f.totals()[3], 2); + assert_eq!(f.totals()[4], 2); + } +} diff --git a/crates/victory-gpu/src/demand.rs b/crates/victory-gpu/src/demand.rs new file mode 100644 index 000000000..9da61bcde --- /dev/null +++ b/crates/victory-gpu/src/demand.rs @@ -0,0 +1,623 @@ +//! Demand landing for shader-written memory in carded copies (`VICTORY_DEMAND_LAND=1`). +//! +//! Carded host copies (such as the 174 MB graphics heap) accumulate hundreds of +//! GPU-written 64 KiB pieces per frame (skinning output, compute scratch) that +//! are consumed solely by subsequent GPU passes and never read by the title +//! CPU. Instead of fetching and merging every differing piece over PCIe before +//! signalling the title, [`park`] records the latest GPU range per 64 KiB block, +//! marks pages whose block is not yet known to be CPU-read as `PAGE_NOACCESS`, +//! and skips the eager copy-back. +//! +//! Any CPU read or write to a parked block traps in `watch::on_write`, fetches +//! the latest bytes from the card via a dedicated copy queue, lands them +//! (through the runtime's `beside` view when available), restores protection, +//! and promotes the block to `CPU_READ` so subsequent frames land it eagerly +//! with zero further faults. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +const BLOCK: usize = 64 << 10; +const MAX_BLOCKS: usize = 1 << 16; // 4 GiB / 64 KiB +const WORDS: usize = MAX_BLOCKS / 64; +const SHARDS: usize = 16; + +/// `VICTORY_DEMAND_LAND=0` disables demand landing (eagerly lands every +/// differing piece, as before). +pub(crate) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DEMAND_LAND").is_none_or(|v| v != "0") && crate::shadow::cards()) +} + +static CPU_READ: [AtomicU64; WORDS] = [const { AtomicU64::new(0) }; WORDS]; +static GUARDED: [AtomicU64; WORDS] = [const { AtomicU64::new(0) }; WORDS]; +static PINNED: [AtomicU32; MAX_BLOCKS] = [const { AtomicU32::new(0) }; MAX_BLOCKS]; + +static STATS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; +const DEFERRED_PIECES: usize = 0; +const DEFERRED_BYTES: usize = 1; +const FAULTS: usize = 2; +const FAULT_BYTES: usize = 3; +const KNOWN_READ_BLOCKS: usize = 4; +const TITLE_FAULTS: usize = 5; +const SAFECOPY_FAULTS: usize = 6; +const PIN_FULFILLS: usize = 7; +const WRITE_FULFILLS: usize = 8; +const KERNEL_FULFILLS: usize = 9; + +#[derive(Clone)] +struct ParkedPiece { + shadow: Arc<crate::shadow::Shadow>, + lo: usize, + hi: usize, + fetched_after: u64, +} + +struct ParkedBlock { + pieces: Vec<ParkedPiece>, + views: Vec<(usize, u32)>, +} + +type ShardMap = HashMap<usize, ParkedBlock>; +static PARKED: [Mutex<Option<ShardMap>>; SHARDS] = [const { Mutex::new(None) }; SHARDS]; +static ALIASES: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); + +#[inline] +fn has_bit(bits: &[AtomicU64; WORDS], block: usize) -> bool { + block < MAX_BLOCKS && (bits[block / 64].load(Ordering::Acquire) >> (block % 64)) & 1 != 0 +} + +#[inline] +fn set_bit(bits: &[AtomicU64; WORDS], block: usize) -> bool { + if block >= MAX_BLOCKS { + return false; + } + let mask = 1u64 << (block % 64); + (bits[block / 64].fetch_or(mask, Ordering::AcqRel) & mask) == 0 +} + +#[inline] +fn clear_bit(bits: &[AtomicU64; WORDS], block: usize) { + if block < MAX_BLOCKS { + bits[block / 64].fetch_and(!(1u64 << (block % 64)), Ordering::AcqRel); + } +} + +#[inline] +fn has_any(bits: &[AtomicU64; WORDS], from: usize, to: usize) -> bool { + let to = to.min(MAX_BLOCKS); + if from >= to { + return false; + } + let mut b = from; + while b < to { + let word = bits[b / 64].load(Ordering::Acquire); + if word == 0 { + b = (b / 64 + 1) * 64; + continue; + } + let bit = b % 64; + let end = ((b / 64 + 1) * 64).min(to) - b; + let mask = if end >= 64 { !0u64 << bit } else { ((1u64 << end) - 1) << bit }; + if (word & mask) != 0 { + return true; + } + b += end; + } + false +} + +fn shard(block: usize) -> std::sync::MutexGuard<'static, Option<ShardMap>> { + PARKED[block % SHARDS].lock().unwrap_or_else(|e| e.into_inner()) +} + +fn mark_cpu_read(block: usize) { + if set_bit(&CPU_READ, block) { + STATS[KNOWN_READ_BLOCKS].fetch_add(1, Ordering::Relaxed); + } +} + +/// Pins blocks overlapping `[at, at + len)` so `park` will not mark them +/// `PAGE_NOACCESS` while the caller inspects title memory under a shadow lock. +/// Also fulfills any already-parked blocks in that range first. +pub(crate) struct Pin { + from: usize, + to: usize, +} + +impl Drop for Pin { + fn drop(&mut self) { + for b in self.from..self.to { + PINNED[b].fetch_sub(1, Ordering::Release); + } + } +} + +pub(crate) fn pin_range(at: usize, len: usize) -> Pin { + if !on() || len == 0 { + return Pin { from: 0, to: 0 }; + } + let from = (at / BLOCK).min(MAX_BLOCKS); + let to = at.saturating_add(len).div_ceil(BLOCK).min(MAX_BLOCKS); + for b in from..to { + PINNED[b].fetch_add(1, Ordering::AcqRel); + } + if has_any(&GUARDED, from, to) { + for b in from..to { + if has_bit(&GUARDED, b) && fulfill_block(b, false) { + STATS[PIN_FULFILLS].fetch_add(1, Ordering::Relaxed); + } + } + } + Pin { from, to } +} + +/// Attempts to defer landing of piece `[lo, hi)` of `shadow`. +/// Returns `true` if parked on the card (caller must skip eager fetch/land). +pub(crate) fn park(shadow: &Arc<crate::shadow::Shadow>, lo: usize, hi: usize, fetched_after: u64) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; + if !on() || lo >= hi { + return false; + } + let title_start = shadow.span().0 as usize + lo; + let title_end = shadow.span().0 as usize + hi; + let b = title_start / BLOCK; + if b >= MAX_BLOCKS || b != (title_end - 1) / BLOCK { + return false; + } + // Never allow C1 in-place reads to bypass a shader-written block parked on card. + crate::port::gpu_bound(title_start, title_end - title_start); + if has_bit(&CPU_READ, b) || PINNED[b].load(Ordering::Acquire) != 0 { + return false; + } + + let mut map = shard(b); + if has_bit(&CPU_READ, b) || PINNED[b].load(Ordering::Acquire) != 0 { + return false; + } + let blocks = map.get_or_insert_with(Default::default); + if let Some(existing) = blocks.get_mut(&b) { + push_or_merge_piece(&mut existing.pieces, shadow, lo, hi, fetched_after); + STATS[DEFERRED_PIECES].fetch_add(1, Ordering::Relaxed); + STATS[DEFERRED_BYTES].fetch_add((hi - lo) as u64, Ordering::Relaxed); + return true; + } + + // Collect the title view block(s) backing physical block `b`. + let mut addrs = Vec::with_capacity(2); + addrs.push(b * BLOCK); + if let Some(_reading) = crate::watch::title_memory_reading_now() + && let Some((_, shown)) = crate::inplace::beside_page(b * BLOCK) + { + for v in shown { + if v != 0 && v < MAX_BLOCKS * BLOCK && !addrs.contains(&v) { + if has_bit(&CPU_READ, v / BLOCK) || PINNED[v / BLOCK].load(Ordering::Acquire) != 0 { + return false; + } + addrs.push(v); + } + } + } + + for &addr in &addrs { + set_bit(&GUARDED, addr / BLOCK); + } + + let mut views = Vec::with_capacity(addrs.len()); + let mut failed = false; + for &addr in &addrs { + let mut old = 0u32; + // SAFETY: `addr` is a 64 KiB-aligned title virtual block; only protection changes. + let ok = unsafe { VirtualProtect(addr as *const _, BLOCK, PAGE_NOACCESS, &mut old) } != 0; + if !ok || !matches!(old, PAGE_READWRITE | PAGE_READONLY) { + if ok { + // SAFETY: restore original protection for non-RW/RO pages (code/noaccess). + unsafe { VirtualProtect(addr as *const _, BLOCK, old, &mut old) }; + } + failed = true; + break; + } + views.push((addr, old)); + } + + if failed || PINNED[b].load(Ordering::Acquire) != 0 { + restore_views(&views); + for &addr in &addrs { + clear_bit(&GUARDED, addr / BLOCK); + } + if failed { + mark_cpu_read(b); + } + return false; + } + + if addrs.len() > 1 { + let mut aliases = ALIASES.lock().unwrap_or_else(|e| e.into_inner()); + let a = aliases.get_or_insert_with(Default::default); + for &addr in &addrs[1..] { + a.insert(addr / BLOCK, b); + } + } + + blocks.insert( + b, + ParkedBlock { + pieces: vec![ParkedPiece { + shadow: shadow.clone(), + lo, + hi, + fetched_after, + }], + views, + }, + ); + STATS[DEFERRED_PIECES].fetch_add(1, Ordering::Relaxed); + STATS[DEFERRED_BYTES].fetch_add((hi - lo) as u64, Ordering::Relaxed); + true +} + +fn push_or_merge_piece(pieces: &mut Vec<ParkedPiece>, shadow: &Arc<crate::shadow::Shadow>, lo: usize, hi: usize, fetched_after: u64) { + for p in pieces.iter_mut() { + if Arc::ptr_eq(&p.shadow, shadow) { + p.lo = p.lo.min(lo); + p.hi = p.hi.max(hi); + p.fetched_after = p.fetched_after.max(fetched_after); + return; + } + } + pieces.push(ParkedPiece { + shadow: shadow.clone(), + lo, + hi, + fetched_after, + }); +} + +fn restore_views(views: &[(usize, u32)]) { + use windows_sys::Win32::System::Memory::VirtualProtect; + for &(addr, old) in views { + let mut unused = 0u32; + // SAFETY: restoring previous protection saved from `VirtualProtect`. + unsafe { VirtualProtect(addr as *const _, BLOCK, old, &mut unused) }; + } +} + +/// Called from `watch::on_write` when an access violation occurs at `at`. +/// `permanent` is `true` for title thread faults and `false` for `safecopy`. +pub(crate) fn on_fault(at: usize, permanent: bool) -> bool { + if !on() { + return false; + } + let block = at / BLOCK; + if !has_bit(&GUARDED, block) { + return false; + } + let canonical = ALIASES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|a| a.get(&block).copied()) + .unwrap_or(block); + let ok = fulfill_block(canonical, permanent); + if ok { + STATS[if permanent { TITLE_FAULTS } else { SAFECOPY_FAULTS }].fetch_add(1, Ordering::Relaxed); + } + ok +} + +/// Fulfills any demand-guarded blocks overlapping `[at, at + len)`. +/// Returns `true` if at least one guarded block was fulfilled. +pub(crate) fn fulfill_range(at: usize, len: usize, permanent: bool) -> bool { + if !on() || len == 0 { + return false; + } + let from = (at / BLOCK).min(MAX_BLOCKS); + let to = at.saturating_add(len).div_ceil(BLOCK).min(MAX_BLOCKS); + if !has_any(&GUARDED, from, to) { + return false; + } + let mut did = false; + for block in from..to { + if has_bit(&GUARDED, block) { + let canonical = ALIASES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|a| a.get(&block).copied()) + .unwrap_or(block); + if fulfill_block(canonical, permanent) { + STATS[if permanent { KERNEL_FULFILLS } else { WRITE_FULFILLS }].fetch_add(1, Ordering::Relaxed); + did = true; + } + } + } + did +} + +fn fulfill_block(block: usize, permanent: bool) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect}; + if !has_bit(&GUARDED, block) { + return false; + } + let mut map = shard(block); + let Some(entry) = map.as_mut().and_then(|m| m.remove(&block)) else { + // Another thread just finished fulfilling this block concurrently. + if permanent { + mark_cpu_read(block); + } + return !has_bit(&GUARDED, block); + }; + + if entry.views.len() > 1 { + let mut aliases = ALIASES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(a) = aliases.as_mut() { + for &(addr, _) in &entry.views[1..] { + a.remove(&(addr / BLOCK)); + } + } + } + + let has_beside = crate::land::beside_on() + && crate::watch::title_memory_reading_now() + .and_then(|_| crate::inplace::beside_page(block * BLOCK)) + .is_some(); + + if !has_beside { + // Private allocation with no alias mapping: temporarily open title view + // so `land_card` can merge bytes in place. + for &(addr, _) in &entry.views { + let mut old = 0u32; + // SAFETY: saved address from our `VirtualProtect`. + unsafe { VirtualProtect(addr as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + } + } + + let mut gpu = Vec::new(); + let mut notes = crate::land::Notes::default(); + let mut total_bytes = 0u64; + if let Some(host) = crate::host::existing() { + for p in &entry.pieces { + let len = p.hi - p.lo; + let raw = windows::core::Interface::as_raw(&p.shadow.buffer) as usize; + if len > 0 && raw > 0x1000 && host.demand_fetch(&p.shadow.buffer, p.lo as u64, len, &mut gpu) { + total_bytes += len as u64; + let ptr = gpu.as_ptr() as usize; + // SAFETY: `gpu` holds `len` bytes just fetched for `[p.lo, p.hi)`. + unsafe { + p.shadow.land_card(&[(p.lo, p.hi, ptr)], p.fetched_after, &mut notes); + } + } + } + } + notes.flush(); + + if has_beside { + restore_views(&entry.views); + } else { + for &(addr, old) in &entry.views { + if old == PAGE_READONLY { + let mut unused = 0u32; + // SAFETY: restore `PAGE_READONLY` expected by `watch::Guards`. + unsafe { VirtualProtect(addr as *const _, BLOCK, old, &mut unused) }; + } + } + } + + for &(addr, _) in &entry.views { + clear_bit(&GUARDED, addr / BLOCK); + if permanent { + mark_cpu_read(addr / BLOCK); + } + } + if permanent { + mark_cpu_read(block); + } + STATS[FAULTS].fetch_add(1, Ordering::Relaxed); + STATS[FAULT_BYTES].fetch_add(total_bytes, Ordering::Relaxed); + true +} + +/// Forgets any parked blocks overlapping `[at, at + len)` when title memory is +/// unmapped, remapped, or freed (`len == 0`: queries the region at `at`). +pub(crate) fn forget(at: usize, len: usize) { + if !on() { + return; + } + let len = if len != 0 { + len + } else { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: valid out pointer of `MEMORY_BASIC_INFORMATION`. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { BLOCK } else { info.RegionSize.max(BLOCK) } + }; + let from = (at / BLOCK).min(MAX_BLOCKS); + let to = at.saturating_add(len).div_ceil(BLOCK).min(MAX_BLOCKS); + for b in from..to { + clear_bit(&CPU_READ, b); + if has_bit(&GUARDED, b) { + let canonical = ALIASES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_mut() + .and_then(|a| a.remove(&b)) + .unwrap_or(b); + let mut map = shard(canonical); + if let Some(entry) = map.as_mut().and_then(|m| m.remove(&canonical)) { + for &(addr, _) in &entry.views { + clear_bit(&GUARDED, addr / BLOCK); + } + } + clear_bit(&GUARDED, b); + } + } +} + +/// Removes parked pieces belonging to a dropped `Shadow`. +pub(crate) fn drop_shadow(id: u64) { + if !on() { + return; + } + for s in 0..SHARDS { + let mut map = PARKED[s].lock().unwrap_or_else(|e| e.into_inner()); + let Some(blocks) = map.as_mut() else { + continue; + }; + let mut empty = Vec::new(); + for (&b, entry) in blocks.iter_mut() { + entry.pieces.retain(|p| p.shadow.id() != id); + if entry.pieces.is_empty() { + empty.push(b); + } + } + for b in empty { + if let Some(entry) = blocks.remove(&b) { + if entry.views.len() > 1 { + let mut aliases = ALIASES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(a) = aliases.as_mut() { + for &(addr, _) in &entry.views[1..] { + a.remove(&(addr / BLOCK)); + } + } + } + restore_views(&entry.views); + for &(addr, _) in &entry.views { + clear_bit(&GUARDED, addr / BLOCK); + } + } + } + } +} + +pub(crate) fn log(frames: f64) { + let pieces = STATS[DEFERRED_PIECES].swap(0, Ordering::Relaxed) as f64 / frames; + let bytes = STATS[DEFERRED_BYTES].swap(0, Ordering::Relaxed) as f64 / frames; + let faults = STATS[FAULTS].swap(0, Ordering::Relaxed) as f64 / frames; + let fault_bytes = STATS[FAULT_BYTES].swap(0, Ordering::Relaxed) as f64 / frames; + let title_f = STATS[TITLE_FAULTS].swap(0, Ordering::Relaxed) as f64 / frames; + let safe_f = STATS[SAFECOPY_FAULTS].swap(0, Ordering::Relaxed) as f64 / frames; + let pin_f = STATS[PIN_FULFILLS].swap(0, Ordering::Relaxed) as f64 / frames; + let write_f = STATS[WRITE_FULFILLS].swap(0, Ordering::Relaxed) as f64 / frames; + let kern_f = STATS[KERNEL_FULFILLS].swap(0, Ordering::Relaxed) as f64 / frames; + let known = STATS[KNOWN_READ_BLOCKS].load(Ordering::Relaxed); + if pieces == 0.0 && faults == 0.0 && known == 0 { + return; + } + tracing::info!( + "demand landing (VICTORY_DEMAND_LAND={}): per frame {:.1} C2 pieces deferred ({:.1} KB), {:.2} demand fulfills ({:.1} KB: title {:.2}, safecopy {:.2}, pin {:.2}, write {:.2}, kernel {:.2}), {} blocks known CPU-read", + u8::from(on()), + pieces, + bytes / 1024.0, + faults, + fault_bytes / 1024.0, + title_f, + safe_f, + pin_f, + write_f, + kern_f, + known, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn alloc_low_block() -> *mut std::ffi::c_void { + use windows_sys::Win32::System::Memory::{ + MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RESERVE, + MemExtendedParameterAddressRequirements, PAGE_READWRITE, VirtualAlloc2, + }; + let mut req = MEM_ADDRESS_REQUIREMENTS { + LowestStartingAddress: std::ptr::null_mut(), + HighestEndingAddress: ((1usize << 32) - 1) as *mut _, + Alignment: 0, + }; + let mut param = MEM_EXTENDED_PARAMETER::default(); + param.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + param.Anonymous2.Pointer = (&raw mut req).cast(); + // SAFETY: allocating a temporary 64 KiB private block below 4 GiB for tests. + unsafe { VirtualAlloc2(std::ptr::null_mut(), std::ptr::null(), BLOCK, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE, &mut param, 1) } + } + + #[test] + fn pin_prevents_parking_and_forgets_cleanly() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, PAGE_NOACCESS, PAGE_READWRITE, VirtualFree, VirtualProtect}; + let mem = alloc_low_block(); + if mem.is_null() { + return; + } + let addr = mem as usize; + let block = addr / BLOCK; + assert!(block < MAX_BLOCKS); + forget(addr, BLOCK); + { + let _pin = pin_range(addr, BLOCK); + assert_ne!(PINNED[block].load(Ordering::Relaxed), 0); + } + assert_eq!(PINNED[block].load(Ordering::Relaxed), 0); + + let mut old = 0u32; + // SAFETY: `mem` is a valid 64 KiB allocation from `alloc_low_block`. + unsafe { + VirtualProtect(mem, BLOCK, PAGE_NOACCESS, &mut old); + } + set_bit(&GUARDED, block); + assert!(has_any(&GUARDED, block, block + 1)); + forget(addr, 0); + assert!(!has_any(&GUARDED, block, block + 1)); + assert!(!has_bit(&CPU_READ, block)); + // SAFETY: restoring access and releasing `mem`. + unsafe { + VirtualProtect(mem, BLOCK, PAGE_READWRITE, &mut old); + VirtualFree(mem, 0, MEM_RELEASE); + } + } + + #[test] + fn fault_handler_fulfills_and_promotes_block_below_4gib() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; + crate::watch::install(); + let mem = alloc_low_block(); + if mem.is_null() { + return; + } + let addr = mem as usize; + let block = addr / BLOCK; + forget(addr, BLOCK); + // SAFETY: `mem` is writable; initialize a sentinel byte before parking. + unsafe { + (addr as *mut u8).write(0x42); + } + let mut backing = vec![0x42u8; BLOCK]; + let shadow = crate::shadow::Shadow::unbacked(addr as u64, backing.as_mut_ptr(), BLOCK as u64, true); + if on() { + assert!(park(&shadow, 0, BLOCK, 1), "park protects low RW block"); + assert!(has_bit(&GUARDED, block)); + // Real CPU read faults on `PAGE_NOACCESS`, enters `watch::on_write` -> `demand::on_fault`, + // unprotects, promotes `CPU_READ`, and resumes. + // SAFETY: `watch::on_write` restores read access transparently on fault. + let got = unsafe { (addr as *const u8).read_volatile() }; + assert_eq!(got, 0x42); + assert!(!has_bit(&GUARDED, block)); + assert!(has_bit(&CPU_READ, block)); + assert!(!park(&shadow, 0, BLOCK, 2), "promoted block is no longer parked"); + } + forget(addr, BLOCK); + drop(shadow); + // SAFETY: freeing `mem`. + unsafe { VirtualFree(mem, 0, MEM_RELEASE) }; + } + + #[test] + fn cpu_read_bitmap_is_isolated_per_block() { + let a = 1234usize; + let b = 1235usize; + mark_cpu_read(a); + assert!(has_bit(&CPU_READ, a)); + assert!(!has_bit(&CPU_READ, b)); + clear_bit(&CPU_READ, a); + } +} diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index cf0d5e2a9..06a067197 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -289,7 +289,7 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { let mut r = rounds(); let mut asked = r.0 != r.1; while !asked { - let Some(every) = sync_early().filter(|_| last.elapsed().as_millis() < 500) else { + let Some(every) = sync_early().filter(|_| last.elapsed().as_millis() < 100) else { r = SYNC_ROUNDS.1.wait(r).unwrap_or_else(|e| e.into_inner()); asked = r.0 != r.1; continue; @@ -434,6 +434,11 @@ pub(crate) fn sync_heaps() { let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64); let (mut views, mut bytes) = (0u64, 0u64); let mut spent = [0u64; 3]; + // Calls to the kernel's write watch (`Tracked::take`), ns of those that found nothing, + // ns of those that found pages, calls that found nothing. + let mut ask = [0u64; 4]; + // Ring pages, their bytes, changed records on them. + let mut ring = [0u64; 3]; let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; let mut kinds = [0u64; 5]; let mut short = 0u64; @@ -474,7 +479,12 @@ pub(crate) fn sync_heaps() { let mut make: Vec<u32> = Vec::new(); let began = std::time::Instant::now(); let taken = written.take(start as usize, end as usize); - spent[0] += since(began); + let asking = since(began); + spent[0] += asking; + // (E4) the asking, split by whether it found anything. + ask[0] += 1; + ask[if taken.is_empty() { 1 } else { 2 }] += asking; + ask[3] += u64::from(taken.is_empty()); let mut parts: Vec<(usize, usize)> = Vec::new(); for (range_from, range_end) in taken { let mut page = range_from & !(crate::watch::PAGE - 1); @@ -545,6 +555,8 @@ pub(crate) fn sync_heaps() { unsafe { copied.changes(first as u32, &records[..(count * step) as usize], &mut changed) }; records }; + let tabled_before = out.tabled; + let changed_here = changed.len() as u64; for &index in &changed { let at = (u64::from(index) - first) as usize * step as usize; let word = |n: usize| { @@ -587,6 +599,14 @@ pub(crate) fn sync_heaps() { 2 }] += 1; } + // (E5) a ring page: nearly all of the records that changed on it + // are of draws' tables (the title's table ring). + let tabled_here = out.tabled - tabled_before; + if changed_here > 0 && tabled_here * 10 > changed_here * 9 { + out.ring[0] += 1; + out.ring[1] += (to - from) as u64; + out.ring[2] += changed_here; + } } *found[n].lock().unwrap_or_else(|e| e.into_inner()) = out; }); @@ -607,6 +627,9 @@ pub(crate) fn sync_heaps() { for (kind, n) in kinds.iter_mut().zip(part.kinds) { *kind += n; } + for (sum, n) in ring.iter_mut().zip(part.ring) { + *sum += n; + } } spent[1] += since(began); let began = std::time::Instant::now(); @@ -633,8 +656,33 @@ pub(crate) fn sync_heaps() { count.fetch_add(n, Relaxed); } SYNC_SHORT.fetch_add(short, Relaxed); + for (count, n) in SYNC_ASK.iter().zip(ask) { + count.fetch_add(n, Relaxed); + } + for (count, n) in SYNC_RING.iter().zip(ring) { + count.fetch_add(n, Relaxed); + } + SYNC_ROUNDS_DONE[0].fetch_add(1, Relaxed); + SYNC_ROUNDS_DONE[1].fetch_add(u64::from(pages == 0), Relaxed); } +/// Since the last frame line, of [`sync_heaps`]: rounds run, rounds in which no +/// heap page had changed. +#[cfg(windows)] +static SYNC_ROUNDS_DONE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the last frame line: asks of the kernel's write watch (one per heap per +/// round), nanoseconds of those that found nothing, of those that found pages, +/// and how many found nothing. +#[cfg(windows)] +static SYNC_ASK: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Since the last frame line: ring pages (changed pages on which more than 90% +/// of the changed records were of draws' tables), their bytes, the records that +/// changed on them. +#[cfg(windows)] +static SYNC_RING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + /// Pages [`sync_heaps`] read in place of which a part could not be read /// ([`sync_in_place`]), since the last frame line. #[cfg(windows)] @@ -682,6 +730,8 @@ struct SyncPart { kinds: [u64; 5], /// Pages read in place not all there ([`SYNC_SHORT`]). short: u64, + /// Ring pages, their bytes, the records that changed on them. + ring: [u64; 3], } /// Pages [`sync_heaps`] gives a thread at a time. @@ -763,6 +813,34 @@ pub(crate) fn sync_line(frames: f64) { sync_jobs().0 ); } + let rounds = [0, 1].map(|i| SYNC_ROUNDS_DONE[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let ask = [0, 1, 2, 3].map(|i| SYNC_ASK[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); + let ring = [0, 1, 2].map(|i| SYNC_RING[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); + let [made, made_ns, twin_made, twin_ns] = + [0, 1, 2, 3].map(|i| host::VIEW_MAKE[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); + if made > 0.0 { + tracing::info!( + "view creation per frame (VICTORY_DESCRIPTOR_TIMING=0: counted, not timed): {:.0} buffer views in {:.2} ms, {:.0} raw twins in {:.2} ms (thread time, all threads)", + made / frames, + made_ns / 1e6 / frames, + twin_made / frames, + twin_ns / 1e6 / frames + ); + } + if rounds[0] > 0 { + tracing::info!( + "the heaps' records, rounds per frame: {:.1} run, {:.1} of them with no changed page; {:.1} asks of the write watch, {:.2} ms in those that found nothing ({:.1}), {:.2} ms in those that found pages; {:.1} ring pages (over 90% of their changed records of draws' tables), {:.2} MB of them read, {:.0} records changed on them", + rounds[0] as f64 / frames, + rounds[1] as f64 / frames, + ask[0] / frames, + ask[1] / 1e6 / frames, + ask[3] / frames, + ask[2] / 1e6 / frames, + ring[0] / frames, + ring[1] / (1 << 20) as f64 / frames, + ring[2] / frames + ); + } if pages == 0 { return; } @@ -846,16 +924,16 @@ pub(crate) fn with_heap<T>(heap: usize, f: impl FnOnce(&Heap) -> T) -> Option<T> heaps.iter().any(|&(_, _, h)| h == heap).then(|| f(unsafe { &*(heap as *const Heap) })) } -/// Gives back dynamic slots of the host heap behind the title heap at -/// `heap`, if that host heap instance (`id`) still exists. +/// Give back the slots of completed command lists before readbacks and merges. #[cfg(windows)] -pub(crate) fn release_dynamic(heap: usize, id: u64, first: u32, n: u32) { - let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); - if heaps.iter().any(|&(_, _, h)| h == heap) - // SAFETY: registered heaps are live (removed when dropped). - && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() - { - host.release(id, first, n); +pub(crate) fn reclaim_dynamic(completed: u64) { + // Allocation can also reclaim completed ranges if a heap is being registered. + let Ok(heaps) = SHADER_HEAPS.try_read() else { return }; + for &(_, _, heap) in heaps.iter() { + // SAFETY: registered heaps are live for the read guard. + if let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() { + host.reclaim_dynamic(completed); + } } } @@ -1019,7 +1097,7 @@ const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV"); /// A shader view or sampler as the title described it (descriptions in the /// host's layout, kept as words), for the host to build its own from. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) enum View { /// Constant buffer: GPU address and size. Constant(u64, u32), @@ -1076,30 +1154,110 @@ impl View { /// without the address: as many as the title has kinds of textures and /// buffers, however often it moves them). /// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before. -struct Views { +struct FastHash(u64); + +impl std::hash::Hasher for FastHash { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + let mut i = 0; + while i + 8 <= bytes.len() { + let chunk = u64::from_ne_bytes(bytes[i..i + 8].try_into().unwrap()); + self.write_u64(chunk); + i += 8; + } + if i < bytes.len() { + let mut tail = 0u64; + for &b in &bytes[i..] { + tail = (tail << 8) | u64::from(b); + } + self.write_u64(tail); + } + } + fn write_usize(&mut self, n: usize) { + self.write_u64(n as u64); + } + fn write_u64(&mut self, n: u64) { + let h = (self.0.rotate_left(5) ^ n).wrapping_mul(0x9E37_79B9_7F4A_7C15); + self.0 = h ^ (h >> 32); + } + fn write_u32(&mut self, n: u32) { + self.write_u64(u64::from(n)); + } +} + +#[derive(Default, Clone, Copy)] +struct FastBuildHasher; + +impl std::hash::BuildHasher for FastBuildHasher { + type Hasher = FastHash; + fn build_hasher(&self) -> FastHash { + FastHash(0) + } +} + +type FastMap<K, V> = std::collections::HashMap<K, V, FastBuildHasher>; + +const VIEW_SHARD_BITS: u32 = 5; +const VIEW_SHARD_COUNT: usize = 1 << VIEW_SHARD_BITS; +const VIEW_SHARD_MASK: usize = VIEW_SHARD_COUNT - 1; + +struct ViewShard { /// Each entry's view and generation. list: Vec<(View, u32)>, - index: std::collections::BTreeMap<View, u32>, - /// Entries naming each resource. - by_resource: std::collections::BTreeMap<usize, Vec<u32>>, + index: FastMap<View, u32>, + /// Local entries naming each resource. + by_resource: FastMap<usize, Vec<u32>>, free: Vec<u32>, - /// The shapes of views of placed memory, and where each is. - shapes: Vec<Shape>, - shape_index: std::collections::BTreeMap<Shape, u32>, } -/// Read far more often than written: every slot a draw reads through a -/// table is looked up here, on several recording threads at once in the -/// world. Readers share it; only a view not seen before (a new table entry -/// or shape) and a released resource take it alone. -static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { +struct Shapes { + /// The shapes of views of placed memory, and where each is. + list: Vec<Shape>, + index: FastMap<Shape, u32>, +} + +/// Sharded by resource/view so a writer adding an entry or releasing a resource +/// only blocks readers on that single shard instead of stalling every thread +/// across the process. Placed shapes live apart in [`SHAPES_TABLE`]. +static VIEW_SHARDS: [crate::sharded::ReadMostly<ViewShard>; VIEW_SHARD_COUNT] = [const { + crate::sharded::ReadMostly::new(ViewShard { + list: Vec::new(), + index: std::collections::HashMap::with_hasher(FastBuildHasher), + by_resource: std::collections::HashMap::with_hasher(FastBuildHasher), + free: Vec::new(), + }) +}; VIEW_SHARD_COUNT]; + +static SHAPES_TABLE: crate::sharded::ReadMostly<Shapes> = crate::sharded::ReadMostly::new(Shapes { list: Vec::new(), - index: std::collections::BTreeMap::new(), - by_resource: std::collections::BTreeMap::new(), - free: Vec::new(), - shapes: Vec::new(), - shape_index: std::collections::BTreeMap::new(), + index: std::collections::HashMap::with_hasher(FastBuildHasher), }); + +/// Extra shards holding an unordered-access view whose counter resource hashes +/// to another shard than its primary resource. +static COUNTER_SHARDS: std::sync::RwLock<FastMap<usize, u32>> = + std::sync::RwLock::new(std::collections::HashMap::with_hasher(FastBuildHasher)); +static HAS_COUNTER_SHARDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[inline] +fn shard_index(key: usize) -> usize { + let h = key.wrapping_mul(0x9E37_79B9_7F4A_7C15); + ((h ^ (h >> 32)) as usize) & VIEW_SHARD_MASK +} + +fn view_shard(view: &View) -> usize { + match view { + View::Shader(r, _) | View::Unordered(r, _, _) if *r != 0 => shard_index(*r), + _ => { + use std::hash::{Hash, Hasher}; + let mut h = FastHash(0); + view.hash(&mut h); + (h.finish() as usize) & VIEW_SHARD_MASK + } + } +} const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); /// A record is the tag and two words, `i` and `generation` (the host keeps @@ -1191,19 +1349,19 @@ fn placed_words(shape: u32, address: u64) -> [u32; 2] { kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) } -impl Views { +impl Shapes { /// The number of `shape`, a new one if it is not there yet; `None` when /// the shapes are full (the view is then a table entry). fn shape(&mut self, shape: Shape) -> Option<u32> { - if let Some(&at) = self.shape_index.get(&shape) { + if let Some(&at) = self.index.get(&shape) { return Some(at); } - if self.shapes.len() >= SHAPES { + if self.list.len() >= SHAPES { return None; } - let at = self.shapes.len() as u32; - self.shapes.push(shape); - self.shape_index.insert(shape, at); + let at = self.list.len() as u32; + self.list.push(shape); + self.index.insert(shape, at); Some(at) } @@ -1211,30 +1369,43 @@ impl Views { fn placed_of(&self, i: u32, generation: u32) -> Option<View> { let payload = payload(i, generation); let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); - let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let &(unordered, resource, rest) = self.list.get((payload >> PLACED_ADDRESS_BITS) as usize)?; let mut desc = [0u32; 16]; desc[..10].copy_from_slice(&rest[..10]); (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); desc[12..].copy_from_slice(&rest[10..]); Some(View::Placed(unordered, resource, desc)) } +} +impl ViewShard { /// The record words of `view` as a table entry, if it has one. - fn entry_of(&self, view: &View) -> Option<[u32; 2]> { - let &i = self.index.get(view)?; - Some([i, self.list[i as usize].1]) + fn entry_of(&self, shard: usize, view: &View) -> Option<[u32; 2]> { + let &local = self.index.get(view)?; + Some([ + (local << VIEW_SHARD_BITS) | (shard as u32), + self.list[local as usize].1, + ]) } /// The record words of `view` as a table entry: its entry (a new or a /// freed one if the view is not there yet) and that entry's generation. - fn entry(&mut self, view: View) -> [u32; 2] { - let i = match self.index.get(&view) { - Some(&i) => i, + fn entry(&mut self, shard: usize, view: View) -> [u32; 2] { + let local = match self.index.get(&view) { + Some(&local) => local, None => { - let i = match self.free.pop() { - Some(i) => { - self.list[i as usize].0 = view.clone(); - i + if let View::Unordered(_, counter, _) = &view + && *counter != 0 + && shard_index(*counter) != shard + { + let mut counters = COUNTER_SHARDS.write().unwrap_or_else(|e| e.into_inner()); + *counters.entry(*counter).or_insert(0) |= 1u32 << shard; + HAS_COUNTER_SHARDS.store(true, std::sync::atomic::Ordering::Release); + } + let local = match self.free.pop() { + Some(local) => { + self.list[local as usize].0 = view.clone(); + local } None => { self.list.push((view.clone(), 1)); @@ -1242,18 +1413,21 @@ impl Views { } }; for r in view.resources().into_iter().filter(|&r| r != 0) { - self.by_resource.entry(r).or_default().push(i); + self.by_resource.entry(r).or_default().push(local); } - self.index.insert(view, i); - i + self.index.insert(view, local); + local } }; - [i, self.list[i as usize].1] + [ + (local << VIEW_SHARD_BITS) | (shard as u32), + self.list[local as usize].1, + ] } } /// The two words that name `view` in a record: the view itself where its -/// kind allows ([`Views`]), else its table entry. +/// kind allows ([`ViewShard`]), else its table entry. fn words_for(view: View) -> [u32; 2] { use std::sync::atomic::Ordering::Relaxed; if inline() { @@ -1268,8 +1442,8 @@ fn words_for(view: View) -> [u32; 2] { let (shape, address) = shape_of(*unordered, resource, desc); if address >> PLACED_ADDRESS_BITS == 0 { // Nearly every placed view has a shape seen before. - let known = views_read().shape_index.get(&shape).copied(); - let shape = known.or_else(|| views_write().shape(shape)); + let known = shapes_read().index.get(&shape).copied(); + let shape = known.or_else(|| shapes_write().shape(shape)); if let Some(shape) = shape { NAMED_WHOLE[1].fetch_add(1, Relaxed); return placed_words(shape, address); @@ -1279,41 +1453,66 @@ fn words_for(view: View) -> [u32; 2] { _ => {} } } + let shard = view_shard(&view); // A view written before keeps its entry and generation. - if let Some(words) = views_read().entry_of(&view) { + if let Some(words) = shard_read(shard).entry_of(shard, &view) { return words; } - views_write().entry(view) + shard_write(shard).entry(shard, view) } -fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { - match VIEWS.try_read() { - Ok(views) => views, - Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => { +fn shard_read(shard: usize) -> crate::sharded::ReadGuard<'static, ViewShard> { + let table = &VIEW_SHARDS[shard]; + match table.try_read() { + Some(views) => views, + None => { let started = std::time::Instant::now(); - let views = VIEWS.read().unwrap_or_else(|e| e.into_inner()); + let views = table.read(); waited(1, started); views } } } -fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { - match VIEWS.try_write() { - Ok(views) => views, - Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => { +fn shard_write(shard: usize) -> crate::sharded::WriteGuard<'static, ViewShard> { + let table = &VIEW_SHARDS[shard]; + match table.try_write() { + Some(views) => views, + None => { let started = std::time::Instant::now(); - let views = VIEWS.write().unwrap_or_else(|e| e.into_inner()); + let views = table.write(); waited(1, started); views } } } -/// For the memory line: the distinct views kept ([`Views`]), those of them -/// free for reuse, and the bytes the table and its index hold for them (an +fn shapes_read() -> crate::sharded::ReadGuard<'static, Shapes> { + match SHAPES_TABLE.try_read() { + Some(shapes) => shapes, + None => { + let started = std::time::Instant::now(); + let shapes = SHAPES_TABLE.read(); + waited(1, started); + shapes + } + } +} + +fn shapes_write() -> crate::sharded::WriteGuard<'static, Shapes> { + match SHAPES_TABLE.try_write() { + Some(shapes) => shapes, + None => { + let started = std::time::Instant::now(); + let shapes = SHAPES_TABLE.write(); + waited(1, started); + shapes + } + } +} + +/// For the memory line: the distinct views kept ([`VIEW_SHARDS`]), those of +/// them free for reuse, and the bytes the table and its index hold for them (an /// estimate: an entry of the table, and one of the index with its share of /// a tree node; the shapes likewise); then the entries that are constant /// buffer views and views of placed memory (those that did not fit a @@ -1323,27 +1522,35 @@ fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn views_kept() -> [u64; 8] { use std::sync::atomic::Ordering::Relaxed; - let views = views_read(); let each = size_of::<(View, u32)>() as u64; let shape = size_of::<Shape>() as u64; - let (mut constants, mut placed) = (0, 0); - for (view, _) in &views.list { - match view { - View::Constant(..) => constants += 1, - View::Placed(..) => placed += 1, - _ => {} + let (mut list_len, mut free_len, mut list_cap, mut index_len) = (0u64, 0u64, 0u64, 0u64); + let (mut constants, mut placed) = (0u64, 0u64); + for s in 0..VIEW_SHARD_COUNT { + let views = shard_read(s); + list_len += views.list.len() as u64; + free_len += views.free.len() as u64; + list_cap += views.list.capacity() as u64; + index_len += views.index.len() as u64; + for (view, _) in &views.list { + match view { + View::Constant(..) => constants += 1, + View::Placed(..) => placed += 1, + _ => {} + } } } + let shapes = shapes_read(); [ - views.list.len() as u64, - views.free.len() as u64, - views.list.capacity() as u64 * each - + views.index.len() as u64 * each * 3 / 2 - + views.shapes.capacity() as u64 * shape - + views.shape_index.len() as u64 * shape * 3 / 2, + list_len, + free_len, + list_cap * each + + index_len * each * 3 / 2 + + shapes.list.capacity() as u64 * shape + + shapes.index.len() as u64 * shape * 3 / 2, constants, placed, - views.shapes.len() as u64, + shapes.list.len() as u64, NAMED_WHOLE[0].load(Relaxed), NAMED_WHOLE[1].load(Relaxed), ] @@ -1474,30 +1681,60 @@ fn record(handle: u64, view: View) { mirror(handle); } -/// The title released `resource`: the views naming it go stale. -pub(crate) fn forget(resource: usize) { - #[cfg(windows)] - WAITING - .lock() - .unwrap_or_else(|e| e.into_inner()) - .remove(&resource); - let mut views = views_write(); +fn forget_in_shard(shard: usize, resource: usize) { + // Most released resources have no entry (buffers, textures whose views + // are named whole): those take no writer's lock, which stops every + // reader. (A view of a resource made while it is released is a title's + // fault; as before, such an entry stays if it comes after.) + if !shard_read(shard).by_resource.contains_key(&resource) { + return; + } + let mut views = shard_write(shard); let Some(entries) = views.by_resource.remove(&resource) else { return; }; - for i in entries { - let (view, generation) = views.list[i as usize].clone(); + for local in entries { + let (view, generation) = views.list[local as usize].clone(); // Entries freed through a view's other resource may hold another // view by now. - if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) { + if views.index.get(&view) != Some(&local) || !view.resources().contains(&resource) { continue; } views.index.remove(&view); // (Below the bits that say a record is no table entry.) - views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); + views.list[local as usize].1 = ((generation + 1) & GENERATIONS).max(1); // The view's other resource (a counter) keeps a stale entry, which // `forget` of that resource skips. - views.free.push(i); + views.free.push(local); + } +} + +/// The title released `resource`: the views naming it go stale. +pub(crate) fn forget(resource: usize) { + #[cfg(windows)] + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + let primary = shard_index(resource); + forget_in_shard(primary, resource); + if HAS_COUNTER_SHARDS.load(std::sync::atomic::Ordering::Acquire) { + let has = COUNTER_SHARDS + .read() + .unwrap_or_else(|e| e.into_inner()) + .contains_key(&resource); + if has { + let mask = COUNTER_SHARDS + .write() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource) + .unwrap_or(0); + for s in 0..VIEW_SHARD_COUNT { + if s != primary && (mask & (1u32 << s)) != 0 { + forget_in_shard(s, resource); + } + } + } } } @@ -1506,12 +1743,14 @@ pub(crate) fn forget(resource: usize) { fn view_at(i: u32, generation: u32) -> Option<View> { match generation >> KIND_SHIFT { 0 => { - let views = views_read(); - let (view, current) = views.list.get(i as usize)?; + let shard = (i as usize) & VIEW_SHARD_MASK; + let local = (i as usize) >> VIEW_SHARD_BITS; + let views = shard_read(shard); + let (view, current) = views.list.get(local)?; (*current == generation).then(|| view.clone()) } CONSTANT => Some(constant_of(i, generation)), - PLACED => views_read().placed_of(i, generation), + PLACED => shapes_read().placed_of(i, generation), _ => None, } } @@ -1995,8 +2234,12 @@ mod tests { View::Placed(_, r, _) => *r == resource, _ => false, }; - let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); - let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + let entries = || { + (0..VIEW_SHARD_COUNT) + .map(|s| shard_read(s).list.iter().filter(|(v, _)| mine(v)).count()) + .sum::<usize>() + }; + let shapes = || shapes_read().list.iter().filter(|s| s.1 == resource).count(); for n in 0..20_000u64 { let address = 0x6_0000_0000 + n * 0x100; create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f2aad9792..7af5fa056 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -5,7 +5,7 @@ //! writes it (view creation and descriptor copies) and again when a draw //! reads it through a table and finds the slot changed. -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; @@ -14,6 +14,9 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +mod dynamic; +pub(crate) use dynamic::Tables as DynamicTables; + /// Bound dynamic raw views to their host buffer. Set VICTORY_RAW_VIEW_CLAMP=0 /// to use the requested range without querying the host width. From /// fxceless/victory-fork pull request 1266 by lichenlang89 (dd5e8c9e), as @@ -121,13 +124,8 @@ impl Made { } } -static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); pub(crate) struct HostHeap { - /// Identity of this host heap instance, checked by [`release`] so a stale - /// list resetting after a title heap was replaced at the same address does - /// not free slots belonging to the new heap. - id: u64, pub(crate) buffer_sweep: Mutex<crate::draw::BufferSweep>, pub(crate) buffer_frame: std::sync::atomic::AtomicU64, pub(crate) heap: ID3D12DescriptorHeap, @@ -173,24 +171,8 @@ pub(crate) struct HostHeap { /// waited for most (5.6 % of their time, profile waits-1: each descriptor /// made for a draw takes it, and lets go of what the slot held under it). kept: Box<[Mutex<Option<ID3D12Resource>>]>, - /// Where the search for free dynamic slots starts, and which are taken - /// (by lists not yet reset). - next: Mutex<(u32, Vec<bool>)>, - /// How many dynamic slots are free (changed under `next`'s lock): with - /// fewer than a table needs, the search is not made. Once the world - /// had taken them all, every later table of the frame searched every - /// slot before it was refused. - free: std::sync::atomic::AtomicU32, - /// The shortest table that found no run of free slots since slots were - /// last given back (changed under `next`'s lock; `u32::MAX`: none). - /// Until something is given back the free runs only shrink, so a table - /// of that length or longer is refused without the search. Enough - /// slots were free, but in pieces, and every such table walked the - /// whole ring before it was refused: 0.33 ms each with 131,072 slots, - /// 1.0 s of the recording threads in a frame that refused 3,143 (run - /// 45), under the lock all of them need. (A free run that lies across - /// the place the search starts from is seen by neither.) - too_long: std::sync::atomic::AtomicU32, + /// Free ranges and ranges still referenced by recorded or submitted lists. + dynamic_slots: Arc<dynamic::Slots>, /// View heaps: the bytes per element of the buffer view at each title /// slot, for shaders that pick a buffer by an index they compute /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of @@ -1774,7 +1756,8 @@ pub(crate) fn slot_story(slot: u32) -> String { let mut text = if index < host.count { format!("title slot {index}, made from {}", host.describe_slot(index).unwrap_or_default()) } else { - let taken = host.next.lock().unwrap_or_else(|e| e.into_inner()).1.get((index - host.count) as usize).copied(); + let offset = index - host.count; + let taken = (offset < host.dynamic).then(|| host.dynamic_slots.taken(offset)); format!("dynamic slot {} (taken {taken:?})", index - host.count) }; if twin { @@ -1925,8 +1908,8 @@ pub(crate) fn probe_view_limit() { } /// Slots past the title's in a view heap, for tables a draw needs made -/// afresh (constant buffers copied per draw). A list holds the slots it -/// took until it is reset (its submissions have run) or released. +/// afresh (constant buffers copied per draw). A recording holds its slots +/// until it is discarded or the fence behind its GPU execution completes. /// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11; /// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views /// (NVIDIA) these come out of the title's slots, whose highest seen is @@ -1937,6 +1920,17 @@ pub(crate) fn probe_view_limit() { /// table past them is made afresh in these slots like any other. pub(crate) const DYNAMIC: u32 = 1 << 18; +/// Initial misses, misses with enough total space, waits, wait time, and final misses. +static DYNAMIC_PRESSURE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +pub(crate) fn dynamic_line(frames: f64) { + let [short, fragmented, waits, wait_us, refused] = DYNAMIC_PRESSURE.each_ref().map(|c| c.swap(0, Ordering::Relaxed)); + if short != 0 { + tracing::info!(short, fragmented, waits, wait_ms_per_frame = wait_us as f64 / (1000.0 * frames), refused, + "dynamic descriptor pressure"); + } +} + /// [`DYNAMIC`] for a heap of `count` title slots whose null slot is `null` /// (0: none): up to four times as many where the host heap has the room (a /// host that takes more than [`PORTABLE_VIEWS`]; `VICTORY_DYNAMIC_SLOTS` @@ -2047,7 +2041,6 @@ impl HostHeap { .flatten(); let marks = std::sync::Arc::new(QueueMarks::new(if sampler { 0 } else { count as usize })); let h = HostHeap { - id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), buffer_sweep: Mutex::default(), buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX), heap, @@ -2068,9 +2061,7 @@ impl HostHeap { waiting: Mutex::default(), away: Mutex::default(), kept: (0..count + extra).map(|_| Mutex::new(None)).collect(), - next: Mutex::new((0, vec![false; extra as usize])), - free: std::sync::atomic::AtomicU32::new(extra), - too_long: std::sync::atomic::AtomicU32::new(u32::MAX), + dynamic_slots: Arc::new(dynamic::Slots::new(extra)), strides, buffers: Slots::new(count as usize), changed: Slots::new(count as usize), @@ -2236,9 +2227,9 @@ impl HostHeap { self.marks.get(index).map(|write| write != 0) } - /// `n` consecutive free dynamic slots (view heaps only), taken until - /// [`HostHeap::release`]: the first's index. - pub(crate) fn dynamic(&self, n: u32) -> Option<u32> { + /// `n` consecutive slots, owned by this recording until it is discarded + /// or its host fence completes. + pub(crate) fn dynamic(&self, n: u32, tables: &mut Vec<DynamicTables>) -> Option<u32> { if self.sampler || n == 0 || n > self.dynamic { return None; } @@ -2246,52 +2237,89 @@ impl HostHeap { let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::DynamicAsked, 1); - let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let (next, taken) = &mut *guard; - let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n - && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); - let n = n as usize; - // Search from `next` on, then from the start (extending past cursor by - // n - 1 so contiguous runs crossing the cursor are not missed). - let cursor = *next as usize; - let end = self.dynamic as usize; - let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end); - let starts = (cursor..end).chain(0..second_end); - let mut run = 0; - let mut found = None; - let mut last = usize::MAX; - for at in starts.take(if enough { usize::MAX } else { 0 }) { - // A run cannot wrap past the end. - if at != last.wrapping_add(1) { - run = 0; - } - last = at; - run = if taken[at] { 0 } else { run + 1 }; - if run == n { - found = Some(at + 1 - n); - break; + let first = match self.dynamic_slots.take(n, None) { + dynamic::Take::Slot(first) => Some(first), + dynamic::Take::Short { free, largest, .. } => self.dynamic_after_completion(n, free, largest), + }; + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::DynamicNs, started.elapsed().as_nanos() as u64); + if first.is_none() { + add(C::DynamicRefused, 1); } } - let Some(first) = found else { - if enough { - self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); - } - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); - #[cfg(feature = "diagnostics")] - { - use crate::copystat::{C, add}; - add(C::DynamicRefused, 1); - add(C::DynamicNs, started.elapsed().as_nanos() as u64); + let first = first?; + DynamicTables::keep(tables, &self.dynamic_slots, first..first + n); + Some(self.count + first) + } + + fn dynamic_after_completion(&self, count: u32, free_before: u32, largest_before: u32) -> Option<u32> { + use std::time::{Duration, Instant}; + + DYNAMIC_PRESSURE[0].fetch_add(1, Ordering::Relaxed); + if free_before >= count { + DYNAMIC_PRESSURE[1].fetch_add(1, Ordering::Relaxed); + } + let began = Instant::now(); + let mut waited = false; + let first = loop { + let completed = crate::host::completed_descriptor_fence(); + match self.dynamic_slots.take(count, completed) { + dynamic::Take::Slot(first) => break Some(first), + // The earliest owner of slots on this heap is already submitted. + // Poll its fence without holding either the slot or submission lock. + // Bound the wait because Present can hold the underlying queue send. + dynamic::Take::Short { fence: Some(_), .. } + if completed.is_some() && began.elapsed() < Duration::from_millis(250) => + { + waited = true; + std::thread::sleep(Duration::from_millis(1)); + } + dynamic::Take::Short { free, largest, fence } => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(count, free, largest, ?fence, "no free dynamic descriptor range: a table is not made"); + }); + break None; + } } - return None; }; - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); - taken[first..first + n].fill(true); - self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); - *next = ((first + n) % end) as u32; - Some(self.count + first as u32) + if waited { + DYNAMIC_PRESSURE[2].fetch_add(1, Ordering::Relaxed); + DYNAMIC_PRESSURE[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if first.is_none() { + DYNAMIC_PRESSURE[4].fetch_add(1, Ordering::Relaxed); + } + if crate::host::render_trace::active() { + crate::host::render_trace::event( + "dynamic_descriptor_pressure", + format_args!( + "needed={count}\tfree={free_before}\tlargest={largest_before}\twaited={waited}\tduration_us={}\tallocated={}", + began.elapsed().as_micros(), first.is_some() + ), + ); + } + first + } + + pub(crate) fn reclaim_dynamic(&self, completed: u64) { + if self.dynamic != 0 { + self.dynamic_slots.reclaim(completed); + } + } + + /// Reserve permanent views (the by-address memory table) for this heap. + /// This caller holds the memory book, so it only reclaims known completions. + pub(crate) fn reserve_dynamic(&self, count: u32) -> Option<u32> { + if count == 0 || count > self.dynamic { + return None; + } + match self.dynamic_slots.take(count, crate::host::completed_descriptor_fence()) { + dynamic::Take::Slot(first) => Some(self.count + first), + dynamic::Take::Short { .. } => None, + } } /// The title slots this heap has host slots for; fewer than the title's @@ -3417,32 +3445,6 @@ impl HostHeap { } } - /// Identity of this host heap instance (see [`release`]). - pub(crate) fn id(&self) -> u64 { - self.id - } - - /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] - /// returned), only if `id` matches this host heap. - /// - /// [`dynamic`]: HostHeap::dynamic - pub(crate) fn release(&self, id: u64, first: u32, n: u32) { - if id != self.id { - return; - } - let Some(at) = first.checked_sub(self.count) else { - return; - }; - let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let end = (at + n).min(self.dynamic) as usize; - if let Some(slots) = guard.1.get_mut(at as usize..end) { - let given = slots.iter().filter(|taken| **taken).count() as u32; - self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); - self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); - slots.fill(false); - } - } - /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { @@ -3457,11 +3459,26 @@ impl HostHeap { } /// Makes slot `index` (a dynamic one) the view the record `words` names, - /// from this thread's descriptor of it if the recording `recording` has - /// made one, else as [`HostHeap::make_at`] does, and keeps that - /// ([`ListViews`]). What is known of the record in this recording; - /// `None` (the slot is not made): not a view kept so. + /// from this thread's persistent descriptor cache if valid, else as + /// [`HostHeap::make_at`] does, and keeps that ([`ListViews`]). What is + /// known of the record in this recording; `None` (the slot is not made): + /// not a view kept so. + #[cfg(test)] pub(crate) fn make_listed(&self, recording: u64, words: [u32; 3], index: u32) -> Option<Listed> { + self.use_listed(recording, words, index, |listed, _| *listed) + } + + /// As [`HostHeap::make_listed`], running `f` with the cached [`Listed`] + /// state and resolved [`ListedTarget`] inside the same [`LIST_VIEWS`] + /// borrow so callers avoid extra TLS lookups and redundant resource/shadow + /// resolution. + pub(crate) fn use_listed<R>( + &self, + recording: u64, + words: [u32; 3], + index: u32, + f: impl FnOnce(&mut Listed, &ListedTarget) -> R, + ) -> Option<R> { if self.sampler { return None; } @@ -3471,40 +3488,96 @@ impl HostHeap { *views = Some(ListViews::new()?); } let views = views.as_mut()?; - if views.recording != recording { - views.recording = recording; - views.made.clear(); + let frame = crate::frame::current(); + if views.last_sweep != frame { + views.last_sweep = frame; + views.evict_stale(frame); } let twins = self.twins.get(index as usize).is_some(); - if !views.made.contains_key(&words) { - let view = super::view_at(words[1], words[2])?; - let at = 2 * views.made.len() as u32; - // (A constant buffer's bytes are copied for each draw.) - if at >= ListViews::SLOTS || matches!(view, View::Constant(..)) { - return None; - } - let twin = twinned(&view); - let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; - let stride_word = view_stride_word(&view); - let listed = Listed { - kind: crate::draw::view_kind(&view), - texture: is_texture_view(&view), - ready: (0, 0, false), - tabled: None, + let (start, step) = (views.start, views.step); + let slot_at = |s: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + s as usize * step }; + if let Some(entry) = views.made.get_mut(&words) { + let same_recording = entry.recording == recording; + let refreshed = if same_recording { + Some(None) + } else if super::view_at(words[1], words[2]).is_some() { + list_view_valid_target(&entry.view, &entry.kept, entry.first_shown, entry.base) + } else { + None }; - views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed }); + if let Some(new_target) = refreshed { + entry.frame = frame; + if !same_recording { + entry.recording = recording; + entry.listed.ready = (0, 0, false); + entry.listed.tabled = None; + if let Some(target) = new_target { + entry.target = target; + } + } + let at = entry.at; + let twin = entry.twin; + let stride_word = entry.stride_word; + self.copy_from(index, slot_at(at)); + if twin && twins { + self.copy_from(self.raw + index, slot_at(at + 1)); + self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); + } else { + self.clear_twin(index); + } + self.write_stride(index, stride_word); + self.keep_ref(index, entry.kept.as_ref()); + return Some(f(&mut entry.listed, &entry.target)); + } + if let Some(stale) = views.made.remove(&words) { + views.free_slots.push(stale.at); + } + } + let view = super::view_at(words[1], words[2])?; + // (A constant buffer's bytes are copied for each draw.) + if matches!(view, View::Constant(..)) { + return None; } - let made = &views.made[&words]; - self.copy_from(index, views.slot(made.at)); - if made.twin && twins { - self.copy_from(self.raw + index, views.slot(made.at + 1)); + let at = views.alloc_pair()?; + let placed = placed_texture(&view); + let resolved = placed.as_ref().unwrap_or(&view); + let twin = twinned(resolved); + let Some(kept) = make_twinned(resolved, views.slot(at), Some(views.slot(at + 1))) else { + views.free_slots.push(at); + return None; + }; + let stride_word = view_stride_word(&view); + let (first_shown, base, target) = resolve_listed_state(resolved, placed.is_some()); + let listed = Listed { + kind: crate::draw::view_kind(&view), + texture: is_texture_view(&view), + ready: (0, 0, false), + tabled: None, + }; + self.copy_from(index, views.slot(at)); + if twin && twins { + self.copy_from(self.raw + index, views.slot(at + 1)); self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); } else { self.clear_twin(index); } - self.write_stride(index, made.stride_word); - self.keep(index, made.kept.clone()); - Some(made.listed) + self.write_stride(index, stride_word); + self.keep_ref(index, kept.as_ref()); + views.order.push_back(words); + let entry = views.made.entry(words).or_insert(ListView { + recording, + frame, + view, + at, + twin, + stride_word, + kept, + first_shown, + base, + listed, + target, + }); + Some(f(&mut entry.listed, &entry.target)) }) } @@ -3581,6 +3654,28 @@ impl HostHeap { } } + /// As [`HostHeap::keep`], borrowing `resource` so an unchanged slot does + /// not clone (`AddRef`) or drop (`Release`) it. + fn keep_ref(&self, index: u32, resource: Option<&ID3D12Resource>) { + let Some(slot) = self.kept.get(index as usize) else { + return; + }; + let old = { + use windows::core::Interface; + let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); + // The same again: nothing to retire, and zero COM AddRef/Release. + if slot.as_ref().map(Interface::as_raw) == resource.map(Interface::as_raw) { + return; + } + std::mem::replace(&mut *slot, resource.cloned()) + }; + // A running submission may still read the old resource through + // this slot. + if let Some(old) = old { + crate::host::retire_resource(old); + } + } + /// What slot `index` views. fn kept_in(&self, index: u32) -> Option<ID3D12Resource> { self.kept.get(index as usize)?.lock().unwrap_or_else(|e| e.into_inner()).clone() @@ -3618,7 +3713,7 @@ impl HostHeap { // (Bound by its handle, not read by index.) self.clear_twin(index); self.write_stride(index, 1); - self.keep(index, Some(buffer.clone())); + self.keep_ref(index, Some(buffer)); } /// Makes slot `index` (a dynamic one) a raw buffer view that reads @@ -3666,7 +3761,7 @@ impl HostHeap { self.put(index); self.clear_twin(index); self.write_stride(index, 1); - self.keep(index, Some(buffer.clone())); + self.keep_ref(index, Some(buffer)); } /// Makes slot `index` (a dynamic one) a raw unordered access view of @@ -3708,8 +3803,16 @@ impl HostHeap { } } - /// Makes slot `index` (a dynamic one) a constant buffer view of host - /// memory, `size` bytes at `gpu` of `buffer`, which the slot holds. + /// Makes slot `index` (a dynamic one) the view translated shaders read a + /// constant buffer through: a structured view of dwords (stride 4) of + /// host memory, `size` bytes at `gpu` of `buffer` (the size of the + /// title's CBV: rounded up to 256, at most 64 KiB, cut at the buffer's + /// end; reads past it give zeros), which the slot holds; its raw twin, a + /// raw view of the same bytes for programs that pick it from the heap + /// (`victory_shader::emit::raw_views`, where the heap has twins). A + /// structured view begins on any 4 bytes, where a CBV needs 256 and a raw + /// view 16: the title's constants are read where it wrote them + /// (`crate::port`) whatever their place. /// /// The list holds it too, until it is reset; the slot shows it until it /// is made again, and a shader that picks the slot by an index it @@ -3720,43 +3823,24 @@ impl HostHeap { pub(crate) fn constant_at(&self, index: u32, buffer: &ID3D12Resource, gpu: u64, size: u32) { static HOLDS: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); let holds = *HOLDS.get_or_init(|| std::env::var_os("VICTORY_SLOT_HOLDS").is_none_or(|v| v != "0")); - let Some(host) = host() else { return }; - let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { - BufferLocation: gpu, - SizeInBytes: constant_bytes(size), - }; - // SAFETY: a slot of our heap; the memory is the caller's. - unsafe { - host.device - .CreateConstantBufferView(Some(&desc), self.at(index)) - }; + let twin = self.twin(index); + let twinned = constant_views(buffer, gpu, size, self.at(index), twin); self.put(index); - // A program that reads it as raw bytes reads its twin. - let twin = self.twin(index).filter(|_| desc.SizeInBytes > 0); - if let Some(twin) = twin { - // SAFETY: a live buffer that holds the range. - let first = (gpu - unsafe { buffer.GetGPUVirtualAddress() }) / 4; - let raw = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: DXGI_FORMAT_R32_TYPELESS, - ViewDimension: D3D12_SRV_DIMENSION_BUFFER, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_SRV { - FirstElement: first, - NumElements: desc.SizeInBytes / 4, - StructureByteStride: 0, - Flags: D3D12_BUFFER_SRV_FLAG_RAW, - }, - }, - }; - // SAFETY: as above, and a slot of our heaps. - unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; - } - self.twin_made(index, twin.is_some()); + self.twin_made(index, twinned); self.write_stride(index, 0); // After the descriptor: what it showed is let go when nothing shows // it any more. - self.keep(index, holds.then(|| buffer.clone())); + self.keep_ref(index, holds.then_some(buffer)); + } + + /// Makes slot `index` (a dynamic one) a constant buffer that reads zeros + /// (a null structured view of dwords, the kind shaders read it as). + pub(crate) fn null_constant_at(&self, index: u32) { + null_constant_view(self.at(index)); + self.put(index); + self.clear_twin(index); + self.write_stride(index, 0); + self.keep(index, None); } /// Where a descriptor for slot `index` is made, then [`HostHeap::put`]: @@ -4415,6 +4499,20 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: /// these that could not be moved there (null). pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +/// Since the last frame line, of [`buffer_srv`] (the views a draw's table or the +/// buffer pass makes): typed/structured views created, their nanoseconds in +/// `CreateShaderResourceView`, raw twins created, theirs. Nanoseconds are +/// counted only with [`view_timing`]. Measures what a persistent descriptor +/// cache would save (`docs/performance/AGENT_REPORTS/03-descriptors.md`, B, E2). +pub(crate) static VIEW_MAKE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Whether [`VIEW_MAKE`] times the calls (`VICTORY_DESCRIPTOR_TIMING=0`: it only +/// counts them; a clock read is about 25 ns, twice per view). +fn view_timing() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DESCRIPTOR_TIMING").is_none_or(|v| v != "0")) +} + /// Moves the raw view at `at`, a slot of our heaps the card does not see, /// which shows `bytes` from `start` on (GPU address), `by` bytes on: for a /// twin whose view begins between two multiples of 16, where the host makes @@ -4545,10 +4643,15 @@ fn buffer_srv( } let host = host()?; // SAFETY: a live buffer and a slot of our heap. + let timed = view_timing().then(std::time::Instant::now); unsafe { host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; + if let Some(began) = timed { + VIEW_MAKE[1].fetch_add(began.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + } + VIEW_MAKE[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); if let Some(twin) = twin { let window = twin_window(desc.Format, first, count, stride, raw, width); if let Some((first, count, by)) = window { @@ -4560,11 +4663,16 @@ fn buffer_srv( Flags: D3D12_BUFFER_SRV_FLAG_RAW, }; // SAFETY: a live buffer and a slot of our heap. + let timed = view_timing().then(std::time::Instant::now); let start = unsafe { host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin); shadow.buffer.GetGPUVirtualAddress() + first * 4 }; + if let Some(began) = timed { + VIEW_MAKE[3].fetch_add(began.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + } + VIEW_MAKE[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) { TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); null_buffer_view(twin); @@ -4863,27 +4971,24 @@ fn make_twinned( let device = &host.device; match view { &View::Constant(address, size) => { - let shadow = crate::shadow::find(address, u64::from(size))?; - let gpu = shadow.gpu(address); - if gpu % 256 != 0 { + // A title slot: in place where `crate::port` may (it begins on + // any 4 bytes, `constant_views`), else the host copy. + let (gpu, buffer) = match crate::port::constants(address, u64::from(size), crate::port::Use::Mirror) { + Some((buffer, gpu)) => (gpu, buffer), + None => { + let shadow = crate::shadow::find(address, u64::from(size))?; + (shadow.gpu(address), shadow.buffer.clone()) + } + }; + if !gpu.is_multiple_of(4) { once!( address = format_args!("{address:#x}"), - "constant buffer not 256-byte aligned on the host" + "constant buffer not on 4 bytes on the host" ); return None; } - let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { - BufferLocation: gpu, - SizeInBytes: constant_bytes(size), - }; - // SAFETY: slots of our heap; the range lies in the host copy. - unsafe { - device.CreateConstantBufferView(Some(&desc), at); - if let Some(twin) = twin { - device.CreateConstantBufferView(Some(&desc), twin); - } - } - Some(Some(shadow.buffer.clone())) + constant_views(&buffer, gpu, size, at, twin); + Some(Some(buffer)) } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; @@ -5460,11 +5565,8 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { View::Placed(false, _, desc) => { return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); } - View::Constant(..) => { - let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); - // SAFETY: a slot of our heap; a zero location makes a null view. - return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; - } + // Shaders read constant buffers as structured buffers of dwords. + View::Constant(..) => return null_constant_view(at), _ => return null_view(at), }; let desc = if buffer { @@ -5529,6 +5631,97 @@ fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { /// A buffer view that reads zeros (raw, as translated shaders mostly read /// buffers). +/// The views of a constant buffer, `size` bytes (the title's CBV's: rounded +/// up to 256, at most 64 KiB) at `gpu` of `buffer`: at `at` a structured view +/// of dwords (stride 4), which translated shaders read constant buffers +/// through (`victory_shader::emit` `constant_view`: it begins on any 4 bytes, +/// where a CBV needs 256 and a raw view 16; reads past it give zeros); at +/// `twin`, if given, a raw view of the same bytes for programs that pick the +/// slot from the heap (a null raw view where it cannot begin, off 16 bytes). +/// Both are cut at the buffer's end; a null view where nothing is left. +/// Whether `twin` was written. +fn constant_views( + buffer: &ID3D12Resource, + gpu: u64, + size: u32, + at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option<D3D12_CPU_DESCRIPTOR_HANDLE>, +) -> bool { + let Some(host) = host() else { return false }; + let bytes = u64::from(constant_bytes(size)); + // SAFETY: a live buffer. + let (base, width) = unsafe { (buffer.GetGPUVirtualAddress(), buffer.GetDesc().Width) }; + let offset = gpu.wrapping_sub(base); + let elements = width.saturating_sub(offset).min(bytes) / 4; + if gpu < base || !offset.is_multiple_of(4) || elements == 0 { + null_constant_view(at); + } else { + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: offset / 4, + NumElements: elements as u32, + StructureByteStride: 4, + Flags: D3D12_BUFFER_SRV_FLAG_NONE, + }, + }, + }; + // SAFETY: a slot of our heaps and a live buffer covering the range. + unsafe { host.device.CreateShaderResourceView(buffer, Some(&desc), at) }; + } + let Some(twin) = twin else { return false }; + let range = (gpu >= base && bytes > 0) + .then(|| raw_view_range(buffer, offset, bytes, &RAW_SRV_CUTS)) + .flatten(); + match range { + Some(range) => { + let raw = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: range.first, + NumElements: range.elements, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: as above. + unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; + } + None => null_buffer_view(twin), + } + true +} + +/// A structured view of dwords that reads zeros: a constant buffer's null +/// view (`constant_views`). +fn null_constant_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + NumElements: 1, + StructureByteStride: 4, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -6014,7 +6207,8 @@ mod tests { assert_ne!(a.ptr, b.ptr); assert_ne!(Some(a.ptr), std::thread::spawn(|| staged(false, 0).map(|h| h.ptr)).join().unwrap()); let (buffer, _) = host.shared_buffer(1 << 16).unwrap(); - let index = heap.dynamic(1).unwrap(); + let mut tables = Vec::new(); + let index = heap.dynamic(1, &mut tables).unwrap(); let bytes = |at: D3D12_CPU_DESCRIPTOR_HANDLE| { let mut bytes = [0u8; 32]; crate::host::read_into(at.ptr as *const u8, &mut bytes).then_some(bytes) @@ -6743,14 +6937,17 @@ mod tests { let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; - let a = heap.dynamic(heap.dynamic - 100).unwrap(); - let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + let mut early = Vec::new(); + let mut later = Vec::new(); + let a = heap.dynamic(50, &mut early).unwrap(); + let b = heap.dynamic(heap.dynamic - 150, &mut later).unwrap(); + let c = heap.dynamic(60, &mut later).unwrap(); + assert_eq!((a, b, c), (4, 54, 4 + heap.dynamic - 100)); // 40 left at the end: 50 do not fit until something is given back. - assert_eq!(heap.dynamic(50), None); - heap.release(heap.id(), a, 50); - assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + assert_eq!(heap.dynamic(50, &mut later), None); + drop(early); + assert_eq!(heap.dynamic(50, &mut later), Some(4)); + assert_eq!(heap.dynamic(40, &mut later), Some(4 + heap.dynamic - 40)); } #[test] @@ -6758,44 +6955,44 @@ mod tests { let (Some(a), Some(b)) = (HostHeap::new(false, 4), HostHeap::new(false, 4)) else { return; // no host GPU }; - assert_ne!(a.id(), b.id()); - let first = a.dynamic(2).unwrap(); - let after_alloc = a.free.load(std::sync::atomic::Ordering::Relaxed); - a.release(b.id(), first, 2); - assert_eq!( - a.free.load(std::sync::atomic::Ordering::Relaxed), - after_alloc, - "releasing with another heap's identity must not free slots" - ); - a.release(a.id(), first, 2); - assert_eq!(a.free.load(std::sync::atomic::Ordering::Relaxed), after_alloc + 2); + let mut first = Vec::new(); + let mut second = Vec::new(); + assert_eq!(a.dynamic(a.dynamic, &mut first), Some(4)); + assert_eq!(b.dynamic(b.dynamic, &mut second), Some(4)); + drop(second); + assert_eq!(a.dynamic(2, &mut first), None); + assert_eq!(b.dynamic(b.dynamic, &mut Vec::new()), Some(4)); + drop(first); + assert_eq!(a.dynamic(a.dynamic, &mut Vec::new()), Some(4)); } #[test] - fn dynamic_search_can_find_a_run_across_the_cursor() { + fn dynamic_slots_merge_adjacent_ranges_without_wrapping() { let Some(heap) = HostHeap::new(false, 4) else { eprintln!("no host descriptor heap; skipped"); return; }; - let first = heap.dynamic(1).unwrap(); - let left = heap.dynamic(2).unwrap(); - let right = heap.dynamic(2).unwrap(); - let rest = heap.dynamic(heap.dynamic - 5).unwrap(); - assert_eq!((first, left, right, rest), (4, 5, 7, 9)); - - // Reallocating the left half puts the cursor back in the middle. - heap.release(heap.id(), left, 2); - assert_eq!(heap.dynamic(2), Some(left)); - heap.release(heap.id(), left, 2); - heap.release(heap.id(), right, 2); - assert_eq!(heap.dynamic(4), Some(left)); - assert_eq!(heap.dynamic(1), None); + let mut first = Vec::new(); + let mut left = Vec::new(); + let mut right = Vec::new(); + let mut middle = Vec::new(); + let mut last = Vec::new(); + assert_eq!(heap.dynamic(1, &mut first), Some(4)); + assert_eq!(heap.dynamic(2, &mut left), Some(5)); + assert_eq!(heap.dynamic(2, &mut right), Some(7)); + assert_eq!(heap.dynamic(heap.dynamic - 6, &mut middle), Some(9)); + assert_eq!(heap.dynamic(1, &mut last), Some(4 + heap.dynamic - 1)); + + drop(right); + assert_eq!(heap.dynamic(4, &mut middle), None); + drop(left); + assert_eq!(heap.dynamic(4, &mut middle), Some(5)); + assert_eq!(heap.dynamic(1, &mut middle), None); // A free slot at each physical end does not form a two-slot range. - heap.release(heap.id(), first, 1); - let last = first + heap.dynamic - 1; - heap.release(heap.id(), last, 1); - assert_eq!(heap.dynamic(2), None); + drop(first); + drop(last); + assert_eq!(heap.dynamic(2, &mut middle), None); } #[test] @@ -6827,7 +7024,8 @@ mod tests { View::Placed(uav, resource, desc) }; - let s0 = heap.dynamic(4).unwrap(); + let mut tables = Vec::new(); + let s0 = heap.dynamic(4, &mut tables).unwrap(); // R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER let u16x4 = placed_typed(true, 12, 64); heap.make_at(s0, &u16x4); @@ -6877,36 +7075,162 @@ pub(crate) struct Listed { pub(crate) tabled: Option<(u32, bool)>, } +/// Resolved backing target cached in [`ListView`] so `draw.rs` can bring a +/// tabled view up to date without re-resolving `placed_texture` or +/// `buffer_copy` (`shadow::find`). +pub(crate) enum ListedTarget { + Buffer { + shadow: std::sync::Arc<crate::shadow::Shadow>, + address: u64, + len: u64, + }, + ShaderTexture { + resource: usize, + placed: bool, + first_mip: u32, + uploadable: bool, + }, + UnorderedTexture { + resource: usize, + }, + None, +} + struct ListView { + recording: u64, + frame: u64, view: View, /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. at: u32, twin: bool, stride_word: u32, kept: Kept, + first_shown: Option<u32>, + base: u32, listed: Listed, + target: ListedTarget, +} + +fn resolve_listed_state(resolved: &View, placed: bool) -> (Option<u32>, u32, ListedTarget) { + match resolved { + View::Shader(resource, desc) => { + let r = *resource as crate::object::This; + if let Some(copy) = crate::resource::host_copy(r) { + let first_mip = if placed { + desc.as_ref().map_or(0, |d| crate::resource::first_mip(d)) + } else { + 0 + }; + return ( + crate::resource::first_shown(r), + copy.base, + ListedTarget::ShaderTexture { + resource: *resource, + placed, + first_mip, + uploadable: copy.flags() & 0x7 == 0, + }, + ); + } + if let Some((shadow, address, len)) = buffer_copy(resolved) { + return (None, 0, ListedTarget::Buffer { shadow, address, len }); + } + (None, 0, ListedTarget::None) + } + View::Unordered(resource, _, _) => { + let r = *resource as crate::object::This; + if crate::resource::host_resource(r).is_some() { + return (None, 0, ListedTarget::UnorderedTexture { resource: *resource }); + } + if let Some((shadow, address, len)) = buffer_copy(resolved) { + return (None, 0, ListedTarget::Buffer { shadow, address, len }); + } + (None, 0, ListedTarget::None) + } + View::Placed(..) => { + if let Some((shadow, address, len)) = buffer_copy(resolved) { + return (None, 0, ListedTarget::Buffer { shadow, address, len }); + } + (None, 0, ListedTarget::None) + } + _ => (None, 0, ListedTarget::None), + } } -/// The descriptors a thread made for one recording of a list, by the record -/// they were made from, in a heap the card does not see. +/// Validates a cached [`ListView`] across recordings. Returns `Some(None)` if +/// still valid with an unchanged target, `Some(Some(target))` if valid with a +/// refreshed buffer target, or `None` if stale. +fn list_view_valid_target( + view: &View, + kept: &Kept, + first_shown: Option<u32>, + base: u32, +) -> Option<Option<ListedTarget>> { + use windows::core::Interface; + let placed = placed_texture(view); + let view = placed.as_ref().unwrap_or(view); + let kept_raw = kept.as_ref().map(Interface::as_raw); + match view { + View::Shader(resource, _) => { + let resource = *resource as crate::object::This; + if let Some(copy) = crate::resource::host_copy(resource) { + return (kept_raw == Some(copy.texture.as_raw()) + && first_shown == crate::resource::first_shown(resource) + && base == copy.base) + .then_some(None); + } + if let Some((shadow, address, len)) = buffer_copy(view) { + return (kept_raw == Some(shadow.buffer.as_raw())) + .then(|| Some(ListedTarget::Buffer { shadow, address, len })); + } + None + } + View::Unordered(resource, _, _) => { + let resource = *resource as crate::object::This; + if let Some(texture) = crate::resource::host_resource(resource) { + let effective = crate::resource::twin_resource(resource) + .or_else(|| crate::resource::twin_plane_resource(resource)) + .unwrap_or(texture); + return (kept_raw == Some(effective.as_raw())).then_some(None); + } + if let Some((shadow, address, len)) = buffer_copy(view) { + return (kept_raw == Some(shadow.buffer.as_raw())) + .then(|| Some(ListedTarget::Buffer { shadow, address, len })); + } + None + } + View::Placed(..) => { + if let Some((shadow, address, len)) = buffer_copy(view) { + return (kept_raw == Some(shadow.buffer.as_raw())) + .then(|| Some(ListedTarget::Buffer { shadow, address, len })); + } + kept_raw.is_none().then_some(None) + } + _ => None, + } +} + +/// The descriptors a thread made across recordings and frames, by the record +/// they were made from, in a CPU-only heap the card does not see. /// -/// The title's culling and lighting dispatches each bind a table of their own -/// that differs in one constant buffer, and the same thirty views beside it: -/// each was found, checked, made and brought up to date anew for every -/// dispatch, some 2,500 indirect dispatches in the one recording job the -/// frame waits for last (timeline waits-2: 24 of 65 ms). Here a list makes a -/// view once, as it makes a table once (`crate::draw::State::tables`), and -/// copies its descriptor. +/// Clearing the cache on every list caused ~60,000 `CreateShaderResourceView` +/// calls per frame across the translation threads; keeping entries across +/// recordings and validating their underlying resource/copy cuts view creation +/// down to new/changed records only. struct ListViews { - recording: u64, heap: ID3D12DescriptorHeap, step: usize, start: usize, + last_sweep: u64, + next_slot: u32, + free_slots: Vec<u32>, + order: std::collections::VecDeque<[u32; 3]>, made: std::collections::HashMap<[u32; 3], ListView, std::hash::BuildHasherDefault<crate::host::AddressHash>>, } impl ListViews { - const SLOTS: u32 = 8192; + const SLOTS: u32 = 16384; + const IDLE_FRAMES: u64 = 8; fn new() -> Option<ListViews> { let host = host()?; @@ -6922,8 +7246,50 @@ impl ListViews { .ok()?; let step = host.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; let start = heap.GetCPUDescriptorHandleForHeapStart().ptr; - Some(ListViews { recording: 0, heap, step, start, made: Default::default() }) + Some(ListViews { + heap, + step, + start, + last_sweep: 0, + next_slot: 0, + free_slots: Vec::new(), + order: std::collections::VecDeque::new(), + made: Default::default(), + }) + } + } + + fn evict_stale(&mut self, frame: u64) { + let mut kept_order = std::collections::VecDeque::with_capacity(self.order.len()); + while let Some(key) = self.order.pop_front() { + if let Some(entry) = self.made.get(&key) { + if frame.saturating_sub(entry.frame) > Self::IDLE_FRAMES { + if let Some(evicted) = self.made.remove(&key) { + self.free_slots.push(evicted.at); + } + } else { + kept_order.push_back(key); + } + } + } + self.order = kept_order; + } + + fn alloc_pair(&mut self) -> Option<u32> { + if let Some(at) = self.free_slots.pop() { + return Some(at); } + if self.next_slot + 2 <= Self::SLOTS { + let at = self.next_slot; + self.next_slot += 2; + return Some(at); + } + while let Some(old_key) = self.order.pop_front() { + if let Some(evicted) = self.made.remove(&old_key) { + return Some(evicted.at); + } + } + None } fn slot(&self, i: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { @@ -6936,26 +7302,6 @@ thread_local! { static LIST_VIEWS: std::cell::RefCell<Option<ListViews>> = const { std::cell::RefCell::new(None) }; } -/// The view the record `words` names, as this thread made it for `recording`. -pub(crate) fn listed_view(recording: u64, words: [u32; 3]) -> Option<View> { - LIST_VIEWS.with(|views| { - let views = views.borrow(); - let views = views.as_ref().filter(|v| v.recording == recording)?; - views.made.get(&words).map(|m| m.view.clone()) - }) -} - -/// Notes what is known of the record `words` in `recording`. -pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) { - LIST_VIEWS.with(|views| { - if let Some(views) = views.borrow_mut().as_mut().filter(|v| v.recording == recording) - && let Some(made) = views.made.get_mut(&words) - { - made.listed = listed; - } - }); -} - /// Whether a list makes a view its tables hold once (`VICTORY_LIST_VIEWS=0`: /// for every table). pub(crate) fn list_views() -> bool { diff --git a/crates/victory-gpu/src/descriptor/host/dynamic.rs b/crates/victory-gpu/src/descriptor/host/dynamic.rs new file mode 100644 index 000000000..245fa68a6 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/dynamic.rs @@ -0,0 +1,353 @@ +//! Ranges in the dynamic part of one shader-visible descriptor heap. +//! A recording owns its ranges until it is discarded or its submission fence +//! completes. Descriptor reuse does not depend on CPU readback or list reset. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; + +pub(super) struct Slots { + state: Mutex<State>, + retired: Mutex<Retired>, + has_ready: AtomicBool, +} + +#[derive(Default)] +struct Retired { + by_fence: VecDeque<(u64, Vec<Range<u32>>)>, + ready: Vec<Vec<Range<u32>>>, +} + +impl Retired { + fn complete(&mut self, completed: u64) { + let count = self + .by_fence + .partition_point(|(fence, _)| *fence <= completed); + self.ready + .extend(self.by_fence.drain(..count).map(|(_, ranges)| ranges)); + } +} + +struct State { + by_start: BTreeMap<u32, u32>, + by_size: BTreeSet<(u32, u32)>, + free: u32, +} + +pub(super) enum Take { + Slot(u32), + Short { + free: u32, + largest: u32, + fence: Option<u64>, + }, +} + +impl Slots { + pub(super) fn new(capacity: u32) -> Self { + let mut state = State { + by_start: BTreeMap::new(), + by_size: BTreeSet::new(), + free: capacity, + }; + if capacity != 0 { + state.insert(0, capacity); + } + Self { + state: Mutex::new(state), + retired: Mutex::new(Retired::default()), + has_ready: AtomicBool::new(false), + } + } + + fn state(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn retired(&self) -> MutexGuard<'_, Retired> { + self.retired.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub(super) fn take(&self, count: u32, completed: Option<u64>) -> Take { + let mut state = self.state(); + if completed.is_none() + && !self.has_ready.load(Ordering::Acquire) + && let Some(first) = state.take(count) + { + return Take::Slot(first); + } + // Snapshot both queues together so a completed batch is visible + // either as ready ranges or through the fence an exhausted caller polls. + let (ready, fence) = { + let mut retired = self.retired(); + if let Some(completed) = completed { + retired.complete(completed); + } + self.has_ready.store(false, Ordering::Release); + ( + std::mem::take(&mut retired.ready), + retired.by_fence.front().map(|&(fence, _)| fence), + ) + }; + state.give_batches(ready); + match state.take(count) { + Some(first) => Take::Slot(first), + None => Take::Short { + free: state.free, + largest: state.by_size.last().map_or(0, |&(length, _)| length), + fence, + }, + } + } + + /// Publish completed batches for the next allocation. The relay moves + /// each batch as a whole and leaves the interval trees to the allocator. + pub(super) fn reclaim(&self, completed: u64) { + let mut retired = self.retired(); + retired.complete(completed); + if !retired.ready.is_empty() { + self.has_ready.store(true, Ordering::Release); + } + } + + #[cfg(feature = "diagnostics")] + pub(super) fn taken(&self, index: u32) -> bool { + self.state() + .by_start + .range(..=index) + .next_back() + .is_none_or(|(&first, &length)| index >= first + length) + } +} + +impl State { + fn take(&mut self, count: u32) -> Option<u32> { + let &(length, first) = self.by_size.range((count, 0)..).next()?; + self.erase(first, length); + if count < length { + self.insert(first + count, length - count); + } + self.free -= count; + Some(first) + } + + fn insert(&mut self, first: u32, length: u32) { + self.by_start.insert(first, length); + self.by_size.insert((length, first)); + } + + fn erase(&mut self, first: u32, length: u32) { + self.by_start.remove(&first); + self.by_size.remove(&(length, first)); + } + + fn give(&mut self, mut range: Range<u32>) { + self.free += range.end - range.start; + if let Some((&first, &length)) = self.by_start.range(..range.start).next_back() { + debug_assert!(first + length <= range.start); + if first + length == range.start { + self.erase(first, length); + range.start = first; + } + } + if let Some(length) = self.by_start.get(&range.end).copied() { + self.erase(range.end, length); + range.end += length; + } + self.insert(range.start, range.end - range.start); + } + + /// Combine adjacent returns before updating the two interval indexes. + fn give_batches(&mut self, batches: Vec<Vec<Range<u32>>>) { + let mut ranges: Vec<_> = batches.into_iter().flatten().collect(); + ranges.sort_unstable_by_key(|range| range.start); + let mut ranges = ranges.into_iter(); + if let Some(mut joined) = ranges.next() { + for range in ranges { + debug_assert!(joined.end <= range.start); + if joined.end == range.start { + joined.end = range.end; + } else { + self.give(joined); + joined = range; + } + } + self.give(joined); + } + } +} + +/// All ranges taken by consecutive allocations on one heap in a recording. +/// The owning pool stays distinct even if a new heap reuses the title address. +pub(crate) struct Tables { + slots: Arc<Slots>, + ranges: Vec<Range<u32>>, +} + +impl Tables { + pub(super) fn keep(all: &mut Vec<Self>, slots: &Arc<Slots>, range: Range<u32>) { + if let Some(tables) = all.last_mut().filter(|t| Arc::ptr_eq(&t.slots, slots)) { + if let Some(last) = tables + .ranges + .last_mut() + .filter(|last| last.end == range.start) + { + last.end = range.end; + } else { + tables.ranges.push(range); + } + } else { + all.push(Self { + slots: slots.clone(), + ranges: vec![range], + }); + } + } + + pub(crate) fn submitted(mut self, fence: u64) { + let mut retired = self.slots.retired(); + // Submissions register their ranges under the host submission lock. + debug_assert!( + retired + .by_fence + .back() + .is_none_or(|(last, _)| *last <= fence) + ); + retired + .by_fence + .push_back((fence, std::mem::take(&mut self.ranges))); + } +} + +impl Drop for Tables { + fn drop(&mut self) { + if !self.ranges.is_empty() { + let mut state = self.slots.state(); + for range in self.ranges.drain(..) { + state.give(range); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn publishing_a_fence_does_not_lock_the_allocator() { + let slots = Arc::new(Slots::new(1)); + assert!(matches!(slots.take(1, None), Take::Slot(0))); + let mut recording = Vec::new(); + Tables::keep(&mut recording, &slots, 0..1); + std::thread::scope(|scope| { + let tree = slots.state(); + let (sent, wait) = std::sync::mpsc::channel(); + scope.spawn(move || { + recording.pop().unwrap().submitted(3); + sent.send(()).unwrap(); + }); + wait.recv_timeout(std::time::Duration::from_secs(2)) + .unwrap(); + drop(tree); + }); + assert!(matches!(slots.take(1, Some(3)), Take::Slot(0))); + } + + #[test] + fn reuses_only_completed_tables_without_waiting_for_newer_submissions() { + let slots = Arc::new(Slots::new(12)); + let mut oldest = Vec::new(); + let mut newer = Vec::new(); + let mut recording = Vec::new(); + for (count, first, tables) in [ + (4, 0, &mut oldest), + (5, 4, &mut newer), + (3, 9, &mut recording), + ] { + assert!(matches!(slots.take(count, None), Take::Slot(slot) if slot == first)); + Tables::keep(tables, &slots, first..first + count); + } + oldest.pop().unwrap().submitted(10); + newer.pop().unwrap().submitted(20); + assert!(matches!( + slots.take(4, Some(9)), + Take::Short { + free: 0, + fence: Some(10), + .. + } + )); + assert!(matches!(slots.take(4, Some(10)), Take::Slot(0))); + assert!(matches!( + slots.take(1, Some(19)), + Take::Short { + free: 0, + fence: Some(20), + .. + } + )); + drop(recording); + assert!(matches!(slots.take(8, Some(20)), Take::Slot(4))); + } + + #[test] + fn a_concurrent_reclaim_keeps_completed_ranges_available() { + for _ in 0..32 { + let slots = Arc::new(Slots::new(12)); + let mut recording = Vec::new(); + for (first, fence) in [(0, 10), (4, 10), (8, 20)] { + assert!(matches!(slots.take(4, None), Take::Slot(slot) if slot == first)); + Tables::keep(&mut recording, &slots, first..first + 4); + recording.pop().unwrap().submitted(fence); + } + let start = std::sync::Barrier::new(2); + std::thread::scope(|scope| { + scope.spawn(|| { + start.wait(); + slots.reclaim(10); + }); + start.wait(); + assert!(matches!(slots.take(8, Some(10)), Take::Slot(0))); + }); + assert!(matches!( + slots.take(4, None), + Take::Short { + fence: Some(20), + .. + } + )); + slots.reclaim(20); + assert!(matches!(slots.take(4, None), Take::Slot(8))); + } + } + + #[test] + fn uses_smallest_fitting_range_and_coalesces_both_neighbors() { + let slots = Arc::new(Slots::new(16)); + for (size, first) in [(6, 0), (3, 6), (4, 9), (3, 13)] { + assert!(matches!(slots.take(size, None), Take::Slot(slot) if slot == first)); + } + { + let mut state = slots.state(); + state.give(0..6); + state.give(9..13); + } + assert!(matches!( + slots.take(7, None), + Take::Short { + free: 10, + largest: 6, + fence: None + } + )); + assert!(matches!(slots.take(4, None), Take::Slot(9))); + { + let mut state = slots.state(); + state.give(9..13); + state.give(6..9); + } + assert!(matches!(slots.take(13, None), Take::Slot(0))); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 0d7ea537e..c6cd542fb 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -543,9 +543,8 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault<crate::host::AddressHash>>, - /// The dynamic slots the list holds: title heap, host heap id, first, - /// count; given back when the list has run, is reset or released. - dynamic: Vec<(usize, u64, u32, u32)>, + /// The dynamic slots owned by this recording, grouped by host heap. + dynamic: Vec<crate::descriptor::host::DynamicTables>, /// Root SRVs bound as one-view tables in this list: (title heap, title /// address; 0 for none) → dynamic slot, and the host copy the slot /// shows: later draws of the list bring that one up to date, whatever @@ -562,15 +561,13 @@ pub(crate) struct State { rebinds: [u64; 2], } -impl Drop for State { - fn drop(&mut self) { - for &(heap, id, first, n) in &self.dynamic { - crate::descriptor::release_dynamic(heap, id, first, n); +impl State { + pub(crate) fn tables_submitted(&mut self, fence: u64) { + for tables in self.dynamic.drain(..) { + tables.submitted(fence); } } -} -impl State { /// The list's submission has run (submissions are waited for): the /// dynamic slots its tables were made in are given back, not kept /// until the title resets the list. A frame of the opening cutscene @@ -586,9 +583,7 @@ impl State { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back")); } - for (heap, id, first, n) in self.dynamic.drain(..) { - crate::descriptor::release_dynamic(heap, id, first, n); - } + self.dynamic.clear(); self.fresh_tables.clear(); self.recording = 0; self.root_srv_slots.clear(); @@ -650,11 +645,13 @@ fn mesh_kept(pipeline: usize) -> bool { } /// Draws recorded on the host GPU since the last frame line. -static DRAWN: AtomicU64 = AtomicU64::new(0); +/// (One place per thread, `crate::sharded`: every draw on every recording +/// and translating thread adds to it.) +static DRAWN: crate::sharded::Counter = crate::sharded::Counter::new(); /// Draws run on the host so far. pub(crate) fn drawn() -> u64 { - DRAWN.load(Ordering::Relaxed) + DRAWN.load() } /// The draws traced since the last present (diagnostics builds, with @@ -671,13 +668,13 @@ pub(crate) fn take_frame() -> Vec<String> { /// The draws dropped since [`take_dropped`]. #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub(crate) fn dropped_now() -> u64 { - DROPPED.load(Ordering::Relaxed) + DROPPED.load() } /// Draws, mesh dispatches and dispatches recorded but not run on the host /// (no host pipeline) since the last call. pub(crate) fn take_dropped() -> u64 { - DROPPED.swap(0, Ordering::Relaxed) + DROPPED.take() } /// A root SRV's dynamic slot in a list, and the host copy it shows. type RootSlot = (u32, Option<std::sync::Arc<crate::shadow::Shadow>>); @@ -841,6 +838,32 @@ pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0); /// memory is looked at again, each counted from the look before. const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; +/// The same waits in milliseconds, at about 20 frames a second: the title +/// fills memory by the clock, not by the frame, and at 3-10 frames a second +/// 400 frames were 40-130 s. A wait is the shorter of the two. +const RECHECK_MS: [u64; 5] = [200, 600, 2_000, 6_000, 20_000]; + +/// Frames after which look number `stage` (0 for the first) is made, with a +/// frame taking `frame_ms` lately. +fn recheck_in(stage: usize, frame_ms: u64) -> u64 { + RECHECK_FRAMES[stage].min((RECHECK_MS[stage] / frame_ms.max(1)).max(1)) +} + +/// Milliseconds a frame took over the last second or so (16 until known). +fn frame_ms(frame: u64, now: u64) -> u64 { + static WINDOW: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(16)]; + let (began, first) = (WINDOW[0].load(Ordering::Relaxed), WINDOW[1].load(Ordering::Relaxed)); + if first == 0 || frame < first { + WINDOW[0].store(now, Ordering::Relaxed); + WINDOW[1].store(frame, Ordering::Relaxed); + } else if frame > first && now.saturating_sub(began) >= 1000 { + WINDOW[2].store(((now - began) / (frame - first)).clamp(1, 1000), Ordering::Relaxed); + WINDOW[0].store(now, Ordering::Relaxed); + WINDOW[1].store(frame, Ordering::Relaxed); + } + WINDOW[2].load(Ordering::Relaxed) +} + /// Looks at uploaded textures picked by index that found the memory as it /// was, and that found it changed (uploaded again), since the start. pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; @@ -1083,7 +1106,7 @@ fn before<T>(slot: usize, f: impl FnOnce() -> T) -> T { /// bake draw), their loops' nanoseconds by kind, and the passes that stopped /// at their time and at their bytes. pub(crate) static HEAP_TEXTURE_PASSES: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; -static DROPPED: AtomicU64 = AtomicU64::new(0); +static DROPPED: crate::sharded::Counter = crate::sharded::Counter::new(); /// Marks the last traced draw as not run on the host. #[cfg(feature = "diagnostics")] @@ -1095,25 +1118,29 @@ fn dropped(pipeline: usize) { } /// Dispatches run on the host so far. -static DISPATCHED: AtomicU64 = AtomicU64::new(0); +static DISPATCHED: crate::sharded::Counter = crate::sharded::Counter::new(); pub(crate) fn dispatched() -> u64 { - DISPATCHED.load(Ordering::Relaxed) + DISPATCHED.load() } /// What a render target or depth view of the host is made from: the host /// texture, and [`crate::descriptor::RtvRecord::key`]. type TargetKey = (usize, (usize, [u32; 7])); -/// The host address of a root view: its buffer's host copy, or for a -/// constant buffer not 256-byte aligned there (the console needs 16) a -/// copy in upload memory. -/// shortcut: a root view has no size; constant buffers are taken as 64 KiB -/// (cut at their buffer's end), other views as all that is left of their -/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex -/// streams of a cutscene frame reach further, and what lay past the first -/// megabyte was never brought up to date - meshes without bodies, exploded -/// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.) +/// The host address of a root view: a raw root SRV's (constant buffers are +/// read as raw bytes too, `victory_shader::emit::HostShader::root_cbvs`), +/// which needs 4 bytes, not the 256 of a CBV. For constants: the title's +/// memory itself where `crate::port` reads them in place (nothing refreshed, +/// filled or waited for); else the buffer's host copy; a copy in upload +/// memory only for an address not on 4 bytes. +/// shortcut: a root view has no size: constant buffers are taken as 64 KiB +/// (cut at their buffer's end; the shader reads zeros past 64 KiB), other +/// views as all that is left of their buffer. (They were taken as 1 MiB: +/// 1,452 of the 2,021 mesh vertex streams of a cutscene frame reach further, +/// and what lay past the first megabyte was never brought up to date - +/// meshes without bodies, exploded triangles. `VICTORY_ROOT_VIEW_MB` sets a +/// limit again.) fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> { static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); let limit = *LIMIT.get_or_init(|| { @@ -1122,12 +1149,19 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> { .and_then(|v| v.parse::<u64>().ok()) .map_or(u64::MAX, |mb| mb << 20) }); + // Constants no shader writes, in the title's graphics heap: read where + // the title wrote them (`crate::port`), with nothing refreshed, filled + // or waited for. The list holds the buffer. + if !srv && let Some((buffer, gpu)) = crate::port::constants(address, 1 << 16, crate::port::Use::Root) { + list.keep(&buffer); + return Some(gpu); + } let shadow = crate::shadow::find(address, 1)?; let len = shadow .left(address) .min(if srv { limit } else { 1 << 16 }); let gpu = shadow.gpu(address); - if srv || gpu % 256 == 0 { + if srv || gpu % crate::port::ALIGN == 0 { shadow.refresh(list, address, len); #[cfg(feature = "diagnostics")] crate::book::root(gpu, len); @@ -1507,6 +1541,7 @@ impl State { self.host_targets = Some(now); let rtvs: Vec<_> = views.iter().map(|(texture, desc)| host.rtv(*texture, desc.as_ref())).collect(); let dsv = dsv.map(|(texture, record)| host.dsv(texture, record.depth_desc().as_ref())); + list.gpu_pass_break(); // SAFETY: an open list; the views were just made. unsafe { list.list.OMSetRenderTargets( @@ -1800,6 +1835,15 @@ impl State { if v.address == 0 || v.size == 0 { continue; } + if let Some((buffer, gpu)) = crate::port::stream_bytes(v.address, u64::from(v.size)) { + list.keep(&buffer); + *view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: v.size, + StrideInBytes: v.stride, + }; + continue; + } let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { continue; }; @@ -1818,25 +1862,85 @@ impl State { } if indexed { let v = self.index; - let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { - return false; + let (gpu, size) = if let Some((buffer, gpu)) = crate::port::stream_bytes(v.address, u64::from(v.size)) { + list.keep(&buffer); + (gpu, v.size) + } else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { + return false; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + ( + shadow.gpu(v.address), + v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)), + ) }; - shadow.refresh(list, v.address, u64::from(v.size)); let view = D3D12_INDEX_BUFFER_VIEW { - BufferLocation: shadow.gpu(v.address), - SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)), + BufferLocation: gpu, + SizeInBytes: size, Format: DXGI_FORMAT(v.format as i32), }; // SAFETY: an open list; the view names a live host buffer. unsafe { l.IASetIndexBuffer(Some(&view)) }; } + if self.depth != 0 { + // A depth texture shaders also write: what they wrote, first. + list.twin_use(self.depth as This, false, true); + } const RENDER_TARGET: u32 = 0x4; + // Batch all target and depth state transitions into a single ResourceBarrier call. + let mut barriers = [const { std::mem::MaybeUninit::<D3D12_RESOURCE_BARRIER>::uninit() }; 9]; + let mut barrier_count = 0usize; + let flush_barriers = |barriers: &mut [std::mem::MaybeUninit<D3D12_RESOURCE_BARRIER>; 9], count: &mut usize| { + if *count > 0 { + // SAFETY: `barriers[..*count]` were initialized below. + let slice = unsafe { std::slice::from_raw_parts(barriers.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(), *count) }; + // SAFETY: an open list and live textures. + unsafe { l.ResourceBarrier(slice) }; + *count = 0; + } + }; + let mut push_state = |resource: This, wanted: u32| { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + use windows::core::Interface; + if let Some((texture, before)) = list.transition(resource, wanted) { + let state = crate::host::legal_state(texture, wanted); + let raw = texture.as_raw(); + // SAFETY: `barriers[..barrier_count]` are initialized Transition barriers. + let existing = (0..barrier_count).find(|&i| unsafe { + barriers[i] + .assume_init_ref() + .Anonymous + .Transition + .pResource + .as_ref() + .map(Interface::as_raw) + == Some(raw) + }); + if let Some(i) = existing { + // Combine consecutive transitions of the same resource in this draw. + // SAFETY: initialized Transition barrier at `i`. + unsafe { + (*barriers[i].assume_init_mut().Anonymous.Transition).StateAfter = State(state as i32); + } + return; + } + if barrier_count == barriers.len() { + flush_barriers(&mut barriers, &mut barrier_count); + } + barriers[barrier_count].write(crate::host::transition( + texture, + State(before as i32), + State(state as i32), + )); + barrier_count += 1; + crate::host::count_gpu_step(crate::host::GpuStep::OurStates, 0); + } + }; for &t in &self.targets { - crate::list::ensure_state(list, t as This, RENDER_TARGET); + push_state(t as This, RENDER_TARGET); } if self.depth != 0 { - // A depth texture shaders also write: what they wrote, first. - list.twin_use(self.depth as This, false, true); // A view that writes neither plane keeps the texture readable: // the depth read state, together with the shader read states // if this draw's shaders read the same texture (the write state @@ -1852,8 +1956,9 @@ impl State { } else { DEPTH_WRITE }; - crate::list::ensure_state(list, self.depth as This, state); + push_state(self.depth as This, state); } + flush_barriers(&mut barriers, &mut barrier_count); true } @@ -1878,6 +1983,7 @@ impl State { && let Some(heap) = crate::descriptor::lent_heap() { once!("a dispatch without a view heap that needs one gets the title's"); + list.note_heap_picked(); self.heaps[0] = heap; } // Heaps first: a root signature with directly indexed heaps must be @@ -2112,13 +2218,14 @@ impl State { None, )); } + // Constant buffers too: the translation reads them as + // raw bytes through a root SRV (`root_view`). // SAFETY: an open list; the address is in live memory. unsafe { - match (compute, srv) { - (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), - (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), - (true, false) => l.SetComputeRootConstantBufferView(param, gpu), - (true, true) => l.SetComputeRootShaderResourceView(param, gpu), + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); } } } @@ -2194,13 +2301,17 @@ impl State { } Some(s) }; + let pipeline = self.pipeline; let ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| { let len = s.left(a).min(limit); s.refresh(list, a, len); if writes { #[cfg(feature = "diagnostics")] - crate::host::wide_write(a, len, self.pipeline); - s.gpu_writes(list, a, len); + crate::host::wide_write(a, len, pipeline); + // The footprint this pipeline's shader wrote through this + // parameter, once learned (`VICTORY_TIGHT_WRITES=1`). + let (from, n) = crate::tight::declare(pipeline, param, s.id(), s.span().0, a, len); + s.gpu_writes(list, a + from, n); } }; if !crate::pipeline::host::bounded_root_srvs() { @@ -2236,13 +2347,9 @@ impl State { Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { let shadow = address.and_then(|a| find(a).map(|s| (a, s))); - let Some(index) = host.dynamic(1).or_else(|| { - crate::host::settle_for_fence(); - host.dynamic(1) - }) else { + let Some(index) = host.dynamic(1, &mut self.dynamic) else { return false; }; - self.dynamic.push((key.0, host.id(), index, 1)); if let Some((a, s)) = &shadow { // SAFETY: a live buffer. let base = unsafe { s.buffer.GetGPUVirtualAddress() }; @@ -2310,13 +2417,9 @@ impl State { Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); - let Some(index) = host.dynamic(1).or_else(|| { - crate::host::settle_for_fence(); - host.dynamic(1) - }) else { + let Some(index) = host.dynamic(1, &mut self.dynamic) else { return false; }; - self.dynamic.push((key.0, host.id(), index, 1)); self.root_srv_slots .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); match &shadow { @@ -2376,6 +2479,7 @@ impl State { /// copy. A list refreshes them where it first runs such a shader; /// title writes recorded later in the same list are not seen. fn heap_buffers(&self, list: &HostList) -> Option<u64> { + list.note_heap_picked(); let heap = self .heaps .iter() @@ -2436,6 +2540,7 @@ impl State { /// running the bindless heap buffer/texture sweep (for shaders that only /// inspect descriptors already mirrored via their descriptor tables). fn heap_strides(&self, list: &HostList) -> Option<u64> { + list.note_heap_picked(); let heap = self .heaps .iter() @@ -2472,7 +2577,7 @@ impl State { let need_settle = host.needs_gpu_settle_for_bake(); if need_settle { settled = true; - crate::host::settle_for_fence(); + crate::host::settle_for_fence(crate::host::FenceDrain::BakeTextureFlip); } flipped += host.texture_views_remade(); flipped += host.texture_slots_flip(); @@ -2893,7 +2998,7 @@ impl State { gpu.execute_sync_internal(bake_list); bake_list.reset(); } else if !sync.publish.is_empty() { - crate::host::settle_for_fence(); + crate::host::settle_for_fence(crate::host::FenceDrain::BakePublish); } for (index, handle, key) in sync.publish { let _ = host.publish_uploaded_slot(index, handle, key); @@ -3062,7 +3167,7 @@ impl State { Some(mb) => mb << 20, None => { let base = staging_budget_per_frame(memory.map(|[budget, ..]| budget)); - if crate::residency::limited_host_ram() { + if crate::residency::textures_limited_by_ram() { base.min(128 << 20) } else { base @@ -3075,6 +3180,9 @@ impl State { if FRAME.swap(frame, Ordering::Relaxed) != frame { SPENT.store(0, Ordering::Relaxed); } + // The loading gate and the texture book's housekeeping (it limits + // itself to twice a second). + crate::texture::ledger::tick(frame, drawn()); // No more of them are made while the card has no room // (`resource::room`): by what is alive now, not by what was ever // staged (4 GB in all, after which later textures stayed empty for @@ -3159,6 +3267,8 @@ impl State { let now = crate::host::now_ms(); let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); let most = (4000 / took).clamp(16, 256); + // What a frame takes lately: the looks again are counted in time. + let per_frame_ms = frame_ms(frame, now); // What a table entry of a texture a shader samples says. let sampled = UsedResource { kind: ResourceType::Srv, @@ -3183,7 +3293,22 @@ impl State { // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); - let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + // While a backlog is due the pass is a loading pass: frames are 100-300 ms then, + // so a 16 ms slice drained 20,000 slots in minutes (measured, docs/performance). + // `VICTORY_TEXTURE_BACKLOG_MS` is the slice then (default 200); it falls back to + // the plain one under 1024 due slots. + let backlog = std::time::Duration::from_millis(200); + let (per_frame, span) = + if catchup && on_time >= 1024 { (per_frame * 3, (span * 3).max(backlog)) } else { (per_frame, span) }; + // On a loading screen (seen in the title's DirectStorage stream while + // it draws little: `texture::ledger::loading`) frames are not what + // matters: four times the bytes and a slice of at least 120 ms. The + // ceilings that follow (`prefetch_limit`, `room`, commit) still hold. + let (per_frame, span) = if !required && asked.is_none() && crate::texture::ledger::loading() { + (per_frame.saturating_mul(4), span.max(std::time::Duration::from_millis(120))) + } else { + (per_frame, span) + }; // A run made early (`State::early_textures`) has a budget of its // own: its bytes on top of what the frame has spent so far. // (Not `most`: that is the longest wait between looks, used below.) @@ -3202,7 +3327,7 @@ impl State { bytes_at_most, crate::residency::pressured(), crate::residency::critical_commit(), - crate::residency::limited_host_ram(), + crate::residency::textures_limited_by_ram(), crate::texture::live_staging_bytes(), ) }; @@ -3254,7 +3379,7 @@ impl State { // title paints all the time through another view of their pages // (all their blocks are shown at other addresses too), and each // was shown four frames late, over and over. - let mut again_in = RECHECK_FRAMES[0]; + let mut again_in = recheck_in(0, per_frame_ms); // What the queue knew of it when the slots due were taken, while // its marks say it holds the write handed out still; else (or with // `VICTORY_QUEUE_BATCH=0`) asked now. @@ -3267,7 +3392,8 @@ impl State { if looked == print { HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::UNCHANGED); - tells.tell(index, write, match RECHECK_FRAMES.get(usize::from(looks) + 1) { + let next = usize::from(looks) + 1; + tells.tell(index, write, match (next < RECHECK_FRAMES.len()).then(|| recheck_in(next, per_frame_ms)) { Some(wait) => Told::Recheck(frame + wait, (at, len), print, looks + 1, uploaded), None => Told::Done(None), }); @@ -3310,12 +3436,20 @@ impl State { if mapped == 0 { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); outcome(slot_outcome::AWAY); + // Not what the title kept (the texture book drops it). + crate::texture::ledger::gone(address); // Streamed out: what the slot showed is let go. rest(0, || host.texture_slot_gone(index)); tells.tell(index, write, Told::Later(frame, most)); continue; } rest(0, || host.texture_slot_here(index)); + // Named and all there: the texture book links the request + // that filled it to this description (and counts a texture it + // made ready as adopted). + if mapped >= len { + crate::texture::ledger::named(address, resource, first); + } there = Some(mapped); if mapped < len { if mapped <= rest(0, || host.texture_slot_mapped(index)) { @@ -3683,17 +3817,18 @@ impl State { /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: u32) { + let trace = crate::host::render_trace::DrawCall::begin(list, self.pipeline, crate::host::render_trace::Command("dispatch", [x.into(), y.into(), z.into(), flags.into(), 0])); // It may write the arguments a window holds clamped. self.window = None; #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); crate::pipeline::note_drop(self.pipeline as This); return; } // The ray-tracing structure builder's stages run all or none. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); #[cfg(feature = "diagnostics")] { crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned()); @@ -3706,7 +3841,7 @@ impl State { pipeline = format_args!("{:#x}", self.pipeline), "a dispatch without a host pipeline dropped" ); - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); #[cfg(feature = "diagnostics")] { crate::pipeline::note_drop(self.pipeline as This); @@ -3719,7 +3854,7 @@ impl State { return; } if !self.bind(list, p, true) { - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); // 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) { @@ -3751,10 +3886,13 @@ impl State { unsafe { list.list.SetComputeRoot32BitConstant(param, threads[0], word) }; } } + list.gpu_pass(true, self.pipeline, crate::host::render_trace::Command("dispatch", [x.into(), y.into(), z.into(), flags.into(), 0]), || p.name.clone()); + trace.recorded(); + list.gpu_uav_work(); // SAFETY: an open list with everything set. - unsafe { list.list.Dispatch(x, y, z) }; + list.water_dispatch(Some(p), || unsafe { list.list.Dispatch(x, y, z) }); self.buffers_written(); - DISPATCHED.fetch_add(1, Ordering::Relaxed); + DISPATCHED.add(1); if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient) && crate::ambient::on() && self.ambient(list, p, role) @@ -4275,6 +4413,7 @@ impl State { /// Runs a mesh dispatch of `x` groups on the host (the title's mesh /// programs are one-dimensional). pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) { + let trace = crate::host::render_trace::DrawCall::begin(list, self.pipeline, crate::host::render_trace::Command("dispatch_mesh", [x.into(), 1, 1, 0, 0])); self.window = None; #[cfg(feature = "diagnostics")] self.trace("mesh", x, 0); @@ -4295,17 +4434,19 @@ impl State { if x > 65_535 { once!(x, "a mesh dispatch of more groups than the host takes: cut"); } + list.gpu_pass(false, self.pipeline, crate::host::render_trace::Command("dispatch_mesh", [x.min(65_535).into(), 1, 1, 0, 0]), || gpu_pass_name(self.pipeline)); + trace.recorded(); // SAFETY: an open list with everything set. unsafe { l6.DispatchMesh(x.min(65_535), 1, 1) }; - self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); + self.drew(list, crate::pipeline::host_pipeline(self.pipeline as This)); self.mesh_scissor(list, false); - DRAWN.fetch_add(1, Ordering::Relaxed); + DRAWN.add(1); true } Err(_) => false, }; if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); #[cfg(feature = "diagnostics")] dropped(self.pipeline); } @@ -4410,10 +4551,12 @@ impl State { } /// The descriptors a shader reads through tables. Tables holding a - /// constant buffer are made afresh for the draw in dynamic slots, with - /// the constant data copied to upload memory when the list is - /// submitted: the host wants constant buffers 256-byte aligned, the - /// console only 16. Returns those tables' new byte offsets by root + /// constant buffer are made afresh for the draw in dynamic slots. The + /// shaders read constant buffers as structured buffers of dwords (any 4 + /// bytes, where a CBV needs 256 and the console only 16): one + /// in the title's graphics heap that no shader writes is shown where the + /// title wrote it (`crate::port`); any other has its data copied to + /// upload memory when the list is submitted. Returns those tables' new byte offsets by root /// parameter; the other tables' slots are made from the title's. /// /// Within a list, the same table holding the same descriptors is made @@ -4554,18 +4697,13 @@ impl State { made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n).or_else(|| { - crate::host::settle_for_fence(); - host.dynamic(n) - }) else { + let Some(first) = host.dynamic(n, &mut self.dynamic) else { // No room: the draw must not run with the title's own // offsets (slots never made for it); `bind` drops it. made.push((slot, u32::MAX)); continue; }; self.fresh_tables.insert(key, FreshTable { first, epoch: 0, ready: Vec::new() }); - self.dynamic - .push((std::ptr::from_ref(heap) as usize, host.id(), first, n)); // The title's own slots of this table: what the draw reads of // them it brings up to date here, in the dynamic slots. let title_first = heap.index(table).filter(|first| first + n <= host.count()); @@ -4591,56 +4729,67 @@ impl State { // and nothing more if nothing changed in the list since. if list_views && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) - && let Some(mut listed) = host.make_listed(recording, words, index) - { - let kind = group - .entry(k) - .map(|u| u.kind) - .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); - let was = (listed.ready, listed.tabled); - if let Some(kind) = kind { - let tested = TESTED_DEPTH.get(); - if kind == ResourceType::Srv && listed.ready.0 == list.epoch() && listed.ready.1 == tested.0 { - if listed.ready.2 { - TESTED_DEPTH.set((tested.0, true)); + && host + .use_listed(recording, words, index, |listed, target| { + let kind = group + .entry(k) + .map(|u| u.kind) + .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); + if let Some(kind) = kind { + let tested = TESTED_DEPTH.get(); + if kind == ResourceType::Srv && listed.ready.0 == list.epoch() && listed.ready.1 == tested.0 { + if listed.ready.2 { + TESTED_DEPTH.set((tested.0, true)); + } + } else { + let _ = crate::residency::take_staging_deferred(); + TESTED_DEPTH.set((tested.0, false)); + readable_listed(list, kind, target); + let depth = TESTED_DEPTH.get().1; + TESTED_DEPTH.set((tested.0, tested.1 || depth)); + if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() { + listed.ready = (list.epoch(), tested.0, depth); + } + } } - } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { - let _ = crate::residency::take_staging_deferred(); - TESTED_DEPTH.set((tested.0, false)); - readable(list, kind, &view); - let depth = TESTED_DEPTH.get().1; - TESTED_DEPTH.set((tested.0, tested.1 || depth)); - if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() { - listed.ready = (list.epoch(), tested.0, depth); + // (Told once per record and recording; with + // `VICTORY_TABLED_REREAD=1` also of a slot the queue + // holds again since: written after its first read.) + if let Some(title) = title_first + && listed.texture + && (listed.tabled != Some((title + k, kind.is_some())) + || (crate::descriptor::host::tabled_reread() + && kind.is_some() + && host.texture_slot_queued(title + k))) + { + listed.tabled = Some((title + k, kind.is_some())); + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror_after(list, title + k, table + u64::from(k) * 32); + } } - } - } - // (Told once per record and recording; with - // `VICTORY_TABLED_REREAD=1` also of a slot the queue - // holds again since: written after its first read.) - if let Some(title) = title_first - && listed.texture - && (listed.tabled != Some((title + k, kind.is_some())) - || (crate::descriptor::host::tabled_reread() - && kind.is_some() - && host.texture_slot_queued(title + k))) - { - listed.tabled = Some((title + k, kind.is_some())); - host.texture_slot_tabled(title + k, kind.is_some()); - if kind.is_some() { - host.mirror_after(list, title + k, table + u64::from(k) * 32); - } - } - if was != (listed.ready, listed.tabled) { - crate::descriptor::host::note_listed(recording, words, listed); - } + }) + .is_some() + { continue; } let used = group.entry(k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { + // In the title's graphics heap and written by no + // shader: the slot shows the title's bytes + // themselves (`crate::port`); the slot and the list + // hold the buffer. Else a fill of upload memory at + // submission, as before. Shaders read it as a + // structured buffer of dwords (`HostHeap::constant_at`), + // whose view begins on any 4 bytes. + if let Some((buffer, gpu)) = crate::port::constants(address, u64::from(size), crate::port::Use::Table) { + list.keep(&buffer); + host.constant_at(index, &buffer, gpu, size); + continue; + } let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { - host.make_null(index); + host.null_constant_at(index); continue; }; let slot = (std::ptr::from_ref(heap) as usize, index); @@ -4670,7 +4819,12 @@ impl State { } } None => { - host.make_null(index); + // Read as constants: a null view of their kind. + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + host.null_constant_at(index); + } else { + host.make_null(index); + } if used.is_some() { once!(slot, "a table entry without a view"); } @@ -4756,6 +4910,7 @@ impl State { first: u32, first_instance: u32, ) { + let trace = crate::host::render_trace::DrawCall::begin(list, self.pipeline, crate::host::render_trace::Command("draw", [vertices.into(), instances.into(), first.into(), first_instance.into(), 0])); self.window = None; #[cfg(feature = "diagnostics")] self.trace("draw", vertices, first); @@ -4780,6 +4935,8 @@ impl State { if let Some(viewport) = frontend { viewports(list, &[viewport]); } + list.gpu_pass(false, self.pipeline, crate::host::render_trace::Command("draw", [count.into(), instances.into(), from.into(), first_instance.into(), 0]), || gpu_pass_name(self.pipeline)); + trace.recorded(); // SAFETY: an open list with everything set. unsafe { list.list @@ -4788,11 +4945,11 @@ impl State { if frontend.is_some() { viewports(list, &self.viewports); } - self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); - DRAWN.fetch_add(1, Ordering::Relaxed); + self.drew(list, crate::pipeline::host_pipeline(self.pipeline as This)); + DRAWN.add(1); } if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); #[cfg(feature = "diagnostics")] dropped(self.pipeline); } @@ -4950,6 +5107,8 @@ impl State { base: i32, first_instance: u32, ) { + let command = crate::host::render_trace::Command("draw_indexed", [indices.into(), instances.into(), first.into(), base.into(), first_instance.into()]); + let trace = crate::host::render_trace::DrawCall::begin(list, self.pipeline, command); self.window = None; #[cfg(feature = "diagnostics")] self.trace("indexed", indices, first); @@ -4966,16 +5125,18 @@ impl State { if ran { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + list.gpu_pass(false, self.pipeline, command, || gpu_pass_name(self.pipeline)); + trace.recorded(); // SAFETY: an open list with everything set. unsafe { list.list .DrawIndexedInstanced(indices, instances, first, base, first_instance) }; - self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); - DRAWN.fetch_add(1, Ordering::Relaxed); + self.drew(list, crate::pipeline::host_pipeline(self.pipeline as This)); + DRAWN.add(1); } if !ran { - DROPPED.fetch_add(1, Ordering::Relaxed); + DROPPED.add(1); #[cfg(feature = "diagnostics")] dropped(self.pipeline); } @@ -4994,8 +5155,14 @@ impl State { /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] /// if its shaders can store to buffers). - fn drew(&mut self, p: Option<&HostPipeline>) { - if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { + fn drew(&mut self, list: &HostList, p: Option<&HostPipeline>) { + if p.is_none_or(|p| { + p.stages.iter().any(|stage| { + let t = stage.translated(); + t.stores || t.stores_by_address + }) + }) { + list.gpu_uav_work(); self.batch = None; } } @@ -5066,6 +5233,7 @@ impl State { arguments: u64, count: Option<u64>, ) -> bool { + let trace = crate::host::render_trace::DrawCall::begin(list, self.pipeline, crate::host::render_trace::Command("execute_indirect", [kind.into(), max.into(), arguments as i64, i64::from(count.is_some()), stride.into()])); // Skip before the argument clamp can mutate the indirect buffer. #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { @@ -5313,9 +5481,10 @@ impl State { if kind == MESH { self.mesh_scissor(list, true); } + list.gpu_pass(kind == DISPATCH, self.pipeline, crate::host::render_trace::Command("execute_indirect", [kind.into(), max.into(), at as i64, i64::from(counter.is_some()), 0]), || p.name.clone()); // SAFETY: an open list with everything set; the scratch buffer and // host copies are kept alive by the list, and the signature is cached. - unsafe { + list.water_dispatch((kind == DISPATCH).then_some(p), || unsafe { list.list.ExecuteIndirect( &signature, max, @@ -5324,7 +5493,7 @@ impl State { counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) - }; + }); if kind == MESH { self.mesh_scissor(list, false); } @@ -5338,9 +5507,10 @@ impl State { #[cfg(feature = "diagnostics")] list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user); if kind == DISPATCH { + list.gpu_uav_work(); self.buffers_written(); } else { - self.drew(Some(p)); + self.drew(list, Some(p)); } // The stand-in for reflections after the program that gives rays // that found nothing the sky (`crate::ambient`, `Role::Miss`): the @@ -5361,10 +5531,11 @@ impl State { // the window reads it with no barrier, and the next clamp moves it // back (`crate::indirect`). if kind == DISPATCH { - DISPATCHED.fetch_add(1, Ordering::Relaxed); + DISPATCHED.add(1); } else { - DRAWN.fetch_add(1, Ordering::Relaxed); + DRAWN.add(1); } + trace.recorded(); true } } @@ -5572,86 +5743,124 @@ impl RecordHash { } } -fn readable(list: &HostList, kind: ResourceType, view: &View) { +fn refresh_buffer_view( + list: &HostList, + kind: ResourceType, + shadow: &std::sync::Arc<crate::shadow::Shadow>, + address: u64, + len: u64, +) { + shadow.refresh(list, address, len); + if kind == ResourceType::Uav { + // A shader that cannot store to buffers leaves the range as + // the title has it: nothing to find afterwards. + if STORES.get() || !write_skip() { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(address, len, 0); + shadow.gpu_writes(list, address, len); + } else { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1); + crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len); + } + } + } +} + +fn readable_shader_texture(list: &HostList, resource: usize, first: u32, uploadable: Option<bool>) { + // A view the title placed, in another format, in the memory of + // a texture the host writes: that texture's texels, copied on + // the host (title memory does not have them). + let aliased = crate::resource::alias_of(resource as This) + .is_some_and(|source| crate::texture::alias(list, resource as This, source)); + let can_upload = uploadable.unwrap_or_else(|| { + crate::resource::host_copy(resource as This).is_some_and(|t| t.flags() & 0x7 == 0) + }); + if !aliased && can_upload { + // (A texture the title writes: no target, depth or unordered + // access, `crate::texture::title_written`.) + crate::texture::upload_from(list, resource as This, first); + } + // A depth texture shaders also write: what they wrote, first. + list.twin_use(resource as This, false, false); + // The depth target the draw only tests is read in both ways at + // once: both read states, which its preparation asks for too. + let (tested, _) = TESTED_DEPTH.get(); + let state = if tested != 0 && tested == resource { + TESTED_DEPTH.set((tested, true)); + DEPTH_READ | SHADER_RESOURCE + } else { + SHADER_RESOURCE + }; + crate::list::ensure_state(list, resource as This, state); + #[cfg(feature = "diagnostics")] + if tracing::enabled!(tracing::Level::DEBUG) + && let Some(t) = crate::resource::host_resource(resource as This) + { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + if d.Flags.0 & 7 == 0 { + tracing::debug!( + resource = format_args!("{resource:#x}"), + ?d, + "a shader reads a texture the title fills" + ); + } + } +} + +fn readable_unordered_texture(list: &HostList, resource: usize) { const UNORDERED_ACCESS: u32 = 0x8; + #[cfg(feature = "diagnostics")] + crate::capture::note_target(resource as This); + // Some compute-written textures are also read by the title CPU. + list.texture_written(resource as This); + // Unordered access to a depth texture is its colour twin's. + if !list.twin_use(resource as This, true, true) { + crate::list::ensure_state(list, resource as This, UNORDERED_ACCESS); + } +} + +fn readable_listed(list: &HostList, kind: ResourceType, target: &crate::descriptor::host::ListedTarget) { + use crate::descriptor::host::ListedTarget; + match target { + ListedTarget::Buffer { shadow, address, len } => { + refresh_buffer_view(list, kind, shadow, *address, *len); + } + ListedTarget::ShaderTexture { resource, placed, first_mip, uploadable } => { + if kind == ResourceType::Srv { + let first = if *placed { *first_mip } else { 0 }; + readable_shader_texture(list, *resource, first, Some(*uploadable)); + } + } + ListedTarget::UnorderedTexture { resource } => { + if kind == ResourceType::Uav { + readable_unordered_texture(list, *resource); + } + } + ListedTarget::None => {} + } +} + +fn readable(list: &HostList, kind: ResourceType, view: &View) { let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); // Buffer views read title memory: their range is copied at submission; // what shaders write through unordered access goes back to it after. if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) { - shadow.refresh(list, address, len); - if kind == ResourceType::Uav { - // A shader that cannot store to buffers leaves the range as - // the title has it: nothing to find afterwards. - if STORES.get() || !write_skip() { - #[cfg(feature = "diagnostics")] - crate::host::wide_write(address, len, 0); - shadow.gpu_writes(list, address, len); - } else { - #[cfg(feature = "diagnostics")] - { - crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1); - crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len); - } - } - } + refresh_buffer_view(list, kind, &shadow, address, len); } match (view, kind) { (View::Shader(resource, _), ResourceType::Srv) => { - // A view the title placed, in another format, in the memory of - // a texture the host writes: that texture's texels, copied on - // the host (title memory does not have them). - let aliased = crate::resource::alias_of(*resource as This) - .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); - if !aliased - && let Some(t) = crate::resource::host_copy(*resource as This) - && t.flags() & 0x7 == 0 - { - // (A texture the title writes: no target, depth or unordered - // access, `crate::texture::title_written`.) - // Of a texture the title placed, the levels the view shows. - let first = match (&placed, view) { - (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), - _ => 0, - }; - crate::texture::upload_from(list, *resource as This, first); - } - // A depth texture shaders also write: what they wrote, first. - list.twin_use(*resource as This, false, false); - // The depth target the draw only tests is read in both ways at - // once: both read states, which its preparation asks for too. - let (tested, _) = TESTED_DEPTH.get(); - let state = if tested != 0 && tested == *resource { - TESTED_DEPTH.set((tested, true)); - DEPTH_READ | SHADER_RESOURCE - } else { - SHADER_RESOURCE + let first = match (&placed, view) { + (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), + _ => 0, }; - crate::list::ensure_state(list, *resource as This, state); - #[cfg(feature = "diagnostics")] - if tracing::enabled!(tracing::Level::DEBUG) - && let Some(t) = crate::resource::host_resource(*resource as This) - { - // SAFETY: a live resource. - let d = unsafe { t.GetDesc() }; - if d.Flags.0 & 7 == 0 { - tracing::debug!( - resource = format_args!("{resource:#x}"), - ?d, - "a shader reads a texture the title fills" - ); - } - } + readable_shader_texture(list, *resource, first, None); } (View::Unordered(resource, _, _), ResourceType::Uav) => { - #[cfg(feature = "diagnostics")] - crate::capture::note_target(*resource as This); - // Some compute-written textures are also read by the title CPU. - list.texture_written(*resource as This); - // Unordered access to a depth texture is its colour twin's. - if !list.twin_use(*resource as This, true, true) { - crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); - } + readable_unordered_texture(list, *resource); } _ => {} } @@ -5958,3 +6167,9 @@ mod record_hash_tests { assert!(zeros.iter().all(|h| seen.insert(*h))); } } + +/// The name a GPU pass beginning with this pipeline is logged by (the +/// runtime's name of its shaders; `crate::host` `gpu_time`). +fn gpu_pass_name(pipeline: usize) -> String { + crate::pipeline::host_pipeline(pipeline as This).map_or_else(|| format!("pipeline {pipeline:#x}"), |p| p.name.clone()) +} diff --git a/crates/victory-gpu/src/external.rs b/crates/victory-gpu/src/external.rs index a52cafb65..026140c44 100644 --- a/crates/victory-gpu/src/external.rs +++ b/crates/victory-gpu/src/external.rs @@ -47,5 +47,5 @@ pub(crate) fn output_written(resource: This) { /// settles it, before a library lets go of resources the GPU may still use. pub(crate) fn finish_submitted() { crate::queue::before_sync(); - crate::host::settle_for_fence(); + crate::host::settle_for_fence(crate::host::FenceDrain::ExternalUpscaler); } diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 3ca3d4155..2befa7881 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -110,8 +110,11 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c #[cfg(windows)] if crate::host::late() { drop(waiters); + if crate::host::render_trace::active() { + crate::host::render_trace::event("title_fence_request", format_args!("fence={:#x}\tvalue={value}", this as usize)); + } crate::queue::before_sync(); - crate::host::settle_for_fence(); + crate::host::settle_for_fence(crate::host::FenceDrain::TitleFence); if fence.value.load(Ordering::Acquire) >= value { return S_OK; } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 185e61fcb..c669358a4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5,7 +5,7 @@ //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]); //! overlap them with per-submission fences once more than clears run. -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; @@ -18,6 +18,8 @@ use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObj use windows::Win32::UI::WindowsAndMessaging::*; use windows::core::{Interface, PCWSTR, w}; +use memory_samples::{Allocation, Kind, Step as ResidencyStep}; + /// Resource states without the console's own bits (compression hints from /// bit 25 up), which the host rejects. pub(crate) fn pc_state(state: u32) -> u32 { @@ -57,6 +59,7 @@ pub(crate) struct Host { /// The adapter the device is on, for its memory budget /// ([`Host::video_memory`]); `None` if the system does not name it. adapter: Option<IDXGIAdapter3>, + uav_residency: OnceLock<Option<uav_residency::Queue>>, /// 1-descriptor shader-visible fallback heaps bound when a command list /// omits a view or sampler heap while using directly-indexed root signatures. fallback_view: OnceLock<Option<ID3D12DescriptorHeap>>, @@ -75,7 +78,17 @@ unsafe impl Sync for Host {} /// releases reach the host at once, from its own threads, while the host /// runs a submission: freeing there is a GPU page fault on the freed /// texture (a device hang). -static RETIRED: Mutex<std::collections::VecDeque<(u64, Retired)>> = Mutex::new(std::collections::VecDeque::new()); +const RETIRED_SHARDS: usize = 32; +static RETIRED: [Mutex<std::collections::VecDeque<(u64, Retired)>>; RETIRED_SHARDS] = + [const { Mutex::new(std::collections::VecDeque::new()) }; RETIRED_SHARDS]; +static NEXT_RETIRED_SHARD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn retired_shard() -> usize { + thread_local! { + static SHARD: usize = NEXT_RETIRED_SHARD.fetch_add(1, Ordering::Relaxed) % RETIRED_SHARDS; + } + SHARD.with(|&s| s) +} /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -255,12 +268,30 @@ unsafe impl Send for Aside {} /// for so far are done, and waited for. (`MakeResident` came back before /// that: run n11 was lost as n08 was with it alone.) Best done off a hot /// path: a tenth of a millisecond to some. -pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> { - static ASIDE: Mutex<Option<Aside>> = Mutex::new(None); +fn mapped(device: &ID3D12Device, allocation: Allocation) -> windows::core::Result<()> { if !wait_resident() { return Ok(()); } let started = std::time::Instant::now(); + let result = wait_for_mapping(device); + let us = started.elapsed().as_micros() as u64; + memory_samples::record(allocation, ResidencyStep::WaitForMapping, us, result.is_err()); + result?; + MAPPED[1].fetch_add(us, Ordering::Relaxed); + MAPPED[2].fetch_max(us, Ordering::Relaxed); + let n = MAPPED[0].fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(200) { + tracing::info!( + "new card memory waited for until it is mapped (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms", + MAPPED[1].load(Ordering::Relaxed) as f64 / 1000.0, + MAPPED[2].load(Ordering::Relaxed) as f64 / 1000.0 + ); + } + Ok(()) +} + +fn wait_for_mapping(device: &ID3D12Device) -> windows::core::Result<()> { + static ASIDE: Mutex<Option<Aside>> = Mutex::new(None); let mut aside = ASIDE.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: plain object creation; the objects the list names are kept. unsafe { @@ -314,18 +345,6 @@ pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> { WaitForSingleObject(a.event, INFINITE); } } - let us = started.elapsed().as_micros() as u64; - MAPPED[0].fetch_add(1, Ordering::Relaxed); - MAPPED[1].fetch_add(us, Ordering::Relaxed); - MAPPED[2].fetch_max(us, Ordering::Relaxed); - let n = MAPPED[0].load(Ordering::Relaxed); - if n == 1 || n.is_multiple_of(200) { - tracing::info!( - "new card memory waited for until it is mapped (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms", - MAPPED[1].load(Ordering::Relaxed) as f64 / 1000.0, - MAPPED[2].load(Ordering::Relaxed) as f64 / 1000.0 - ); - } Ok(()) } @@ -333,15 +352,17 @@ pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> { static MAPPED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; /// New memory (made with [`not_resident`]) is resident when this returns. -pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> { +pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface, allocation: Allocation) -> windows::core::Result<()> { if !wait_resident() { return Ok(()); } let started = std::time::Instant::now(); - let object: ID3D12Pageable = object.cast()?; - // SAFETY: a live heap or resource of the device's. - let made = unsafe { device.MakeResident(&[Some(object)]) }; + let made = object.cast::<ID3D12Pageable>().and_then(|object| { + // SAFETY: a live heap or resource of the device's. + unsafe { device.MakeResident(&[Some(object)]) } + }); let us = started.elapsed().as_micros() as u64; + memory_samples::record(allocation, ResidencyStep::MakeResident, us, made.is_err()); RESIDENT[0].fetch_add(1, Ordering::Relaxed); RESIDENT[1].fetch_add(us, Ordering::Relaxed); RESIDENT[2].fetch_max(us, Ordering::Relaxed); @@ -358,6 +379,15 @@ pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> window made } +pub(crate) fn resident_and_mapped( + device: &ID3D12Device, + object: &impl Interface, + allocation: Allocation, +) -> windows::core::Result<()> { + resident(device, object, allocation)?; + mapped(device, allocation) +} + /// Times, microseconds and the longest of [`resident`]. static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; @@ -455,13 +485,23 @@ fn sweep() { if crate::residency::pressured() { trim_spare_chunks(); } - crate::pool::room(host().and_then(|h| h.video_memory())); + let memory = host().and_then(|h| h.video_memory()); + crate::pool::room(memory); + memory_samples::report(memory); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); crate::texture::let_go_idle(); crate::resource::let_go_idle(); } +/// Whether the periodic sweep behind flights drains them first, as it did +/// (`VICTORY_SWEEP_SETTLE=1`). Off by default: what the sweep drops is +/// retired by submission number. +fn sweep_settles() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_SWEEP_SETTLE")) +} + /// The number of the newest submission begun, and of the newest of which all /// before it have finished too. pub(crate) fn submissions() -> (u64, u64) { @@ -480,7 +520,7 @@ pub(crate) fn retire<T: 'static>(object: T) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED + RETIRED[retired_shard()] .lock() .unwrap_or_else(|e| e.into_inner()) .push_back((started, Retired::Any(Box::new(object)))); @@ -496,7 +536,10 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); + RETIRED[retired_shard()] + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -518,17 +561,65 @@ fn bury_lag() -> u64 { /// those is dropped a little later than it could be. fn bury(finished: u64) { let finished = finished.saturating_sub(bury_lag()); - let done: Vec<(u64, Retired)> = { - let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + let mut done: Vec<(u64, Retired)> = Vec::new(); + for shard in &RETIRED { + let mut retired = shard.lock().unwrap_or_else(|e| e.into_inner()); let n = retired.iter().take_while(|(at, _)| *at <= finished).count(); - if n == 0 { - return; + if n > 0 { + done.extend(retired.drain(..n)); } - retired.drain(..n).collect() - }; - drop(done); + } + if done.is_empty() { + return; + } + BURIED[0].fetch_add(done.len() as u64, Ordering::Relaxed); + // Dropping is where the time goes: the last reference to a resource + // frees its memory in the graphics kernel, tens of microseconds each, + // and a sweep lets go of thousands at once (run of 2026-11-27 16:05: + // 90 ms of the helper's time a frame in `bury`). The helper also + // resets the landed lists the submitting thread waits for, so the + // dropping goes to a thread of its own ([`burier`]). + match burier() { + Some(to) => { + if let Err(back) = to.send(done) { + drop(back.0); + } + } + None => drop(done), + } } +/// The thread that drops what [`bury`] let go (`VICTORY_BURY_THREAD=0`: +/// dropped where it is let go, as before). +fn burier() -> Option<&'static std::sync::mpsc::Sender<Vec<(u64, Retired)>>> { + static TO: OnceLock<Option<std::sync::mpsc::Sender<Vec<(u64, Retired)>>>> = OnceLock::new(); + TO.get_or_init(|| { + if std::env::var_os("VICTORY_BURY_THREAD").is_some_and(|v| v == "0") { + return None; + } + let (to, from) = std::sync::mpsc::channel::<Vec<(u64, Retired)>>(); + let spawned = std::thread::Builder::new().name("victory-bury".into()).spawn(move || { + for batch in from { + let started = std::time::Instant::now(); + drop(batch); + BURIED[1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + } + }); + match spawned { + Ok(_) => Some(to), + Err(e) => { + tracing::warn!(error = %e, "no thread to drop retired objects: dropped where they are let go"); + None + } + } + }) + .as_ref() +} + +/// Since the last frame-rate line: objects [`bury`] let go, and the +/// nanoseconds their dropping took. +static BURIED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Objects [`retire`] dropped at once (no submission was running) and /// kept until a running submission finished, since the start. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; @@ -623,16 +714,59 @@ pub(crate) fn removal_context() -> String { /// host device removed. pub(crate) fn log_removal_context() { static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) { + if SAID.swap(true, Ordering::Relaxed) { + return; + } + if let Some(host) = host() { + // SAFETY: a plain query. + let reason = unsafe { host.device.GetDeviceRemovedReason() }; + tracing::error!("device removed reason: {reason:?}; {}", features_on()); + } + if !(trail_on() || dred_any() || dred_release()) { return; } tracing::error!("when the host device went: {}", removal_context()); - if dred_any() { + if dred_any() || dred_release() { let data = host().map(|h| h.removal_data(&[])).unwrap_or_default(); tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data }); } } +/// The switches of ours that change what reaches the card or when, as they +/// were set in this run: said when the device is removed. +fn features_on() -> String { + let set = |name: &str| std::env::var(name).unwrap_or_else(|_| "(unset)".into()); + let names = [ + "VICTORY_PRESENT_THREAD", + "VICTORY_PRESENT_HOLD_MS", + "VICTORY_LINE_STALL_MS", + "VICTORY_WAIT_FORCE", + "VICTORY_MERGE_ACROSS", + "VICTORY_GPU_SUBMITS", + "VICTORY_GPU_PASSES", + "VICTORY_CPU_STAGES", + "VICTORY_CARD_TABLE", + "VICTORY_PREFETCH", + "VICTORY_TAKE_APART", + "VICTORY_RELAY", + "VICTORY_CARD_STEPS", + "VICTORY_ASYNC_SUBMIT", + "VICTORY_THIN", + "VICTORY_FRAMEGEN", + "VICTORY_DLSS", + "VICTORY_LIBRARY_STATIC_SAMPLERS", + "VICTORY_DRED", + ]; + let list: Vec<String> = names.iter().map(|n| format!("{n}={}", set(n))).collect(); + format!( + "features: present on its own thread {}, GPU timing of lists {}, relay {}; switches {}", + shown::on(), + std::env::var_os("VICTORY_GPU_SUBMITS").is_none_or(|v| v != "0"), + relay(), + list.join(" ") + ) +} + /// Time spent in submissions since the last frame-rate line, in /// microseconds: preparing them on the CPU (title memory copies, texture /// detiling), then waiting for the GPU. @@ -834,10 +968,22 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { static HOST: OnceLock<Option<Host>> = OnceLock::new(); +/// The host GPU if it is made already. +pub(crate) fn existing() -> Option<&'static Host> { + HOST.get()?.as_ref() +} + +/// The direct queue fence used to retire descriptors from detached lists. +pub(crate) fn completed_descriptor_fence() -> Option<u64> { + // SAFETY: a query on the live host fence. Device removal returns u64::MAX. + let completed = unsafe { existing()?.fence.GetCompletedValue() }; + (completed != u64::MAX).then_some(completed) +} + /// The host GPU if it is made already. #[cfg(feature = "diagnostics")] pub(crate) fn made_host() -> Option<&'static Host> { - HOST.get()?.as_ref() + existing() } /// The host GPU, created on first use; `None` without one (a run then @@ -884,19 +1030,19 @@ fn create() -> windows::core::Result<Host> { } // Diagnostics: device-removed data (the command that faulted, the // faulting address), read when the device is removed. - if dred_any() { + if dred_any() || dred_release() { let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None; if D3D12GetDebugInterface(&mut dred).is_ok() && let Some(dred) = dred { - if dred_on() || dred_light() { + if dred_on() || dred_light() || dred_release() { dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); } dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); tracing::info!( - breadcrumbs = dred_on() || dred_light(), + breadcrumbs = dred_on() || dred_light() || dred_release(), markers = dred_on(), - "crash tracing on (device-removed data)" + "crash tracing on (device-removed data; VICTORY_DRED=0 turns it off in release builds)" ); } else { tracing::warn!("crash tracing asked for and not there: no device-removed data settings"); @@ -919,6 +1065,9 @@ fn create() -> windows::core::Result<Host> { // Before anything is made with it (`VICTORY_RECORD`). #[cfg(feature = "diagnostics")] crate::replay::record::from_env(&device); + // The static samplers of earlier runs, in their order, before any + // other: pipelines with them then come from the library. + crate::pipeline::replay_static_samplers(&device); // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the // driver compiling shaders again on the "D3D Background Thread"s, // for minutes after pipelines were made or loaded) is switched off. @@ -999,6 +1148,7 @@ fn create() -> windows::core::Result<Host> { next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), adapter, + uav_residency: OnceLock::new(), fallback_view: OnceLock::new(), fallback_sampler: OnceLock::new(), }) @@ -1282,6 +1432,9 @@ pub(crate) struct HostList { /// The copy of the colour without the interface (`crate::streamline`) /// recorded in the list, noted likewise; 0 for none. hudless: std::sync::atomic::AtomicU64, + /// Whether any draw or dispatch recorded into this list picks + /// descriptors from the shader-visible heap (needs `sync_heaps`). + heap_picked: std::sync::atomic::AtomicBool, /// Left open and empty, as made or reset, for the title's next reset /// ([`HostList::leave_open`]): that reset finds nothing to undo. The /// list's title calls and epoch then, each plus one (0: not left open). @@ -1296,6 +1449,9 @@ pub(crate) struct HostList { /// and at the end, and where they are read back. #[cfg(feature = "diagnostics")] stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>, + water_timing: water_timing::List, + /// Its GPU timing ([`gpu_time`]): its start and end on the card, its passes. + gpu_time: gpu_time::List, } /// A list's prelude: an allocator and a closed list. @@ -1484,7 +1640,7 @@ pub(crate) fn compile( None, entry, target, - 0, + 1 << 15, 0, &mut code, Some(&mut errors), @@ -1791,6 +1947,23 @@ pub(crate) fn dred_light() -> bool { }) } +/// Release builds: breadcrumbs and page faults for the device-removed report, +/// unless `VICTORY_DRED=0` (no markers, no command texts: the runtime keeps +/// one 32-bit counter per list and the ops' kinds, cheap enough to leave on +/// while playing). Lists are named "victory host list <n>" so a stopped list +/// can be told and the pipelines it binds said. +pub(crate) fn dred_release() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| !cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_DRED").is_none_or(|v| v != "0")) +} + +/// The lists named for [`dred_release`], by their number, with the +/// pipelines they bind. +#[allow(clippy::type_complexity)] +#[cfg_attr(feature = "diagnostics", allow(dead_code))] +static RELEASE_LISTS: Mutex<std::collections::BTreeMap<u32, std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>>> = + Mutex::new(std::collections::BTreeMap::new()); + /// Any of the three. pub(crate) fn dred_any() -> bool { dred_on() || dred_light() || dred_faults() @@ -1824,7 +1997,6 @@ static LIST_NOTES: Mutex< /// The number in the name of a list of ours ("victory host list 7", which the /// debug layer ends with a note of its own in brackets). -#[cfg(feature = "diagnostics")] fn list_number(name: &str) -> Option<u32> { let rest = name.strip_prefix("victory host list ")?; let digits = rest.split(' ').next()?; @@ -1887,7 +2059,7 @@ fn name_it(object: &impl Interface, text: impl FnOnce() -> String) { } return; } - if dred_any() + if (dred_any() || dred_release()) && let Ok(object) = object.cast::<ID3D12Object>() { // SAFETY: a plain call on a live object. @@ -2012,6 +2184,118 @@ impl<T> Spare<T> { /// Scratch chunks no list holds. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new()); +/// A buffer of [`BUFFER_POOL`]: the buffer and, for an upload buffer, where +/// it is mapped (it stays mapped). +struct Pooled(ID3D12Resource, usize); +// SAFETY: free-threaded D3D12 objects; a mapping written only by the list +// that took the buffer, until it gives it back. +unsafe impl Send for Pooled {} + +/// The smallest size class of [`BUFFER_POOL`] (a buffer smaller than it +/// takes one of this size) and the number of classes, each twice the one +/// before: 64 KiB to 64 MiB. Larger buffers are made and dropped as before. +const POOL_CLASS_MIN: u64 = 64 << 10; +const POOL_CLASSES: usize = 11; + +/// Upload buffers of copies into textures and buffers (`HostList::upload`) +/// and read-back buffers (`HostList::defer_read_back`), by size class, that +/// lists which have run gave back: each was made with +/// `CreateCommittedResource` for one copy and freed at the list's reset, +/// on the threads that translate lists and the helper that resets them +/// (run of 2026-11-27 16:05, per frame by sampling: `upload_buffer` 280 +/// ms on the list threads, half of it waiting in the graphics kernel, +/// `read_back_buffer` 110 ms, and the frees in `HostList::reset` and +/// `bury`). `VICTORY_BUFFER_POOL=0`: made and dropped each time, as before. +struct BufferPool { + uploads: [Vec<Pooled>; POOL_CLASSES], + backs: [Vec<Pooled>; POOL_CLASSES], + bytes: u64, +} + +static BUFFER_POOL: Mutex<BufferPool> = Mutex::new(BufferPool { + uploads: [const { Vec::new() }; POOL_CLASSES], + backs: [const { Vec::new() }; POOL_CLASSES], + bytes: 0, +}); + +/// Since the last frame-rate line: buffers taken from [`BUFFER_POOL`], +/// made for it, given back, and dropped as the pool was full. +static POOL_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +fn buffer_pool_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BUFFER_POOL").is_none_or(|v| v != "0")) +} + +/// The most bytes [`BUFFER_POOL`] keeps. +fn buffer_pool_most() -> u64 { + if crate::residency::limited_host_ram() { 128 << 20 } else { 512 << 20 } +} + +/// The class of a buffer of `size` bytes and its bytes, if it has one. +fn pool_class(size: u64) -> Option<(usize, u64)> { + if !buffer_pool_on() { + return None; + } + let class = size.max(POOL_CLASS_MIN).checked_next_power_of_two()?; + let i = (class.trailing_zeros() - POOL_CLASS_MIN.trailing_zeros()) as usize; + (i < POOL_CLASSES).then_some((i, class)) +} + +/// Gives buffers of a list that has run back to [`BUFFER_POOL`] (uploads, +/// read-backs), past its limit dropped; one lock for all of them. +fn give_pooled(uploads: Vec<Pooled>, backs: Vec<ID3D12Resource>) { + if uploads.is_empty() && backs.is_empty() { + return; + } + let class_of = |b: &ID3D12Resource| { + // SAFETY: a plain query of a live buffer. + let width = unsafe { b.GetDesc() }.Width; + pool_class(width).filter(|&(_, class)| class == width) + }; + let backs: Vec<(Pooled, Option<(usize, u64)>)> = backs.into_iter().map(|b| { + let c = class_of(&b); + (Pooled(b, 0), c) + }).collect(); + let uploads: Vec<(Pooled, Option<(usize, u64)>)> = uploads.into_iter().map(|p| { + let c = class_of(&p.0); + (p, c) + }).collect(); + let mut dropped = Vec::new(); + { + let most = buffer_pool_most(); + let mut pool = BUFFER_POOL.lock().unwrap_or_else(|e| e.into_inner()); + for (upload, list) in [(true, uploads), (false, backs)] { + for (buffer, class) in list { + match class { + Some((i, bytes)) if pool.bytes + bytes <= most => { + pool.bytes += bytes; + if upload { pool.uploads[i].push(buffer) } else { pool.backs[i].push(buffer) } + POOL_STATS[2].fetch_add(1, Ordering::Relaxed); + } + _ => { + POOL_STATS[3].fetch_add(1, Ordering::Relaxed); + dropped.push(buffer); + } + } + } + } + } + // (Freed outside the lock.) + drop(dropped); +} + +/// A buffer of class `i` (`bytes` bytes) from [`BUFFER_POOL`], if one is kept. +fn take_pooled(i: usize, bytes: u64, upload: bool) -> Option<Pooled> { + let mut pool = BUFFER_POOL.lock().unwrap_or_else(|e| e.into_inner()); + let taken = if upload { pool.uploads[i].pop() } else { pool.backs[i].pop() }; + if taken.is_some() { + pool.bytes -= bytes; + POOL_STATS[0].fetch_add(1, Ordering::Relaxed); + } + taken +} + /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> { if scratch_pool() @@ -2142,7 +2426,10 @@ cbuffer Span : register(b0) { uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) uint pieces; uint out_at; // the first piece's dword in `differs`, in bytes - uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) + // Bits 0-1 — 0: the hashes are stored; else compared with those stored (2: and then + // stored). Bit 2: a table pass: group g's piece is the number the CPU put in its dword of + // `differs` (`first` unused), so one pass takes a copy's scattered pieces. + uint compare; }; ByteAddressBuffer now : register(t0); // 16 bytes per piece of the copy: the hash of its bytes when they were @@ -2150,10 +2437,18 @@ ByteAddressBuffer now : register(t0); RWByteAddressBuffer hashes : register(u0); RWByteAddressBuffer differs : register(u1); groupshared uint4 parts[64]; +groupshared uint g_piece; [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { - uint piece = first + id.x; + // (Thread 0 reads its table dword once and broadcasts via groupshared; + // thread 0 overwrites it only after all hashes met in `parts`.) + if (thread == 0u) { + g_piece = (compare & 4u) != 0u ? differs.Load(out_at + id.x * 4u) : first + id.x; + } + GroupMemoryBarrierWithGroupSync(); + uint piece = g_piece; + uint mode = compare & 3u; uint lo = piece * 65536u; lo = lo > skew ? lo - skew : 0u; uint hi = min((piece + 1u) * 65536u - skew, size); @@ -2196,20 +2491,24 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { } parts[thread] = h; GroupMemoryBarrierWithGroupSync(); - if (thread != 0u) return; - h = parts[0]; - [loop] - for (uint i = 1u; i < 64u; ++i) { - h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); + [unroll] + for (uint stride = 32u; stride > 0u; stride >>= 1u) { + if (thread < stride) { + uint4 other = parts[thread + stride]; + h = (h ^ other) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + parts[thread] = h; + } + GroupMemoryBarrierWithGroupSync(); } - if (compare != 0u) { + if (thread != 0u) return; + if (mode != 0u) { // The flag, and above it 31 bits of the hash (`torn`). uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u); differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u)); // With the copy-back on its own thread: the next compare of the // piece finds what is written from here on. - if (compare == 2u) hashes.Store4(piece * 16u, h); + if (mode == 2u) hashes.Store4(piece * 16u, h); } else { hashes.Store4(piece * 16u, h); } @@ -2244,6 +2543,48 @@ unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::Card } } +/// Whether a copy's scattered piece runs go to the card as one pass of +/// [`CARD_COMPARE`] over a table of their pieces (`VICTORY_CARD_TABLE`, on; +/// `=0`: a pass per run, as before). The table is the passes' own dwords of +/// `differs`, which the CPU fills with piece numbers before the list runs: +/// the hashes before a submission were some 200 passes a frame over 670 +/// pieces, the compares after it about 400 over 12,400, each a dispatch with +/// its own root constants, most of a group or two. +fn card_table() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_TABLE").is_none_or(|v| v != "0")) +} + +/// One table pass of [`CARD_COMPARE`] (see [`card_table`]): `pieces` of one +/// copy (whose start lies `skew` into its piece 0) are put from dword `slot` +/// of `differs` on, mapped at `data`, and hashed or compared there (`mode` as +/// the shader's `compare`, without its table bit). +/// +/// # Safety +/// The list is open with the compare's root signature, pipeline and buffers +/// set; `differs` holds `slot + pieces.len()` dwords, which no list in the air +/// reads or writes; the pieces lie in the buffer. +unsafe fn card_table_pass(list: &ID3D12GraphicsCommandList, data: usize, slot: u32, pieces: &[u32], skew: u32, size: u32, mode: u32) { + const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + let table = data as *mut u32; + for (i, &piece) in pieces.iter().enumerate() { + // SAFETY: the caller's: these dwords are the pass's. + unsafe { table.add(slot as usize + i).write_volatile(piece) }; + } + let n = pieces.len() as u32; + let mut done = 0; + while done < n { + let k = (n - done).min(MOST); + let constants = [0u32, skew, size, k, (slot + done) * 4, mode | 4]; + // SAFETY: the caller's. + unsafe { + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(k, 1, 1); + } + done += k; + } +} + /// Whether the pieces hashed again after ranges were sent up to a copy in /// the card's memory are hashed in runs of pieces that touch, each piece /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass @@ -2264,6 +2605,20 @@ fn rehash_runs() -> bool { /// hashed, and compare passes after the lists. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +/// Since the last frame-rate line, microseconds of [`Host::card_before`] by +/// part: what changed (the dirty lists and the copies made whole), taking +/// the bytes out (`send::take`), the list that sends them and hashes again +/// (recorded and sent), the compares planned and recorded. The preparing +/// line's "for copies in the card's memory" is their sum and a little more. +static CARD_TIME: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Adds the time since `from` to [`CARD_TIME`]`[part]`; the time now. +fn card_time(part: usize, from: std::time::Instant) -> std::time::Instant { + let now = std::time::Instant::now(); + CARD_TIME[part].fetch_add(now.duration_since(from).as_micros() as u64, Ordering::Relaxed); + now +} + /// Whether what shaders wrote to copies in the card's memory is merged /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by /// default). The pieces the card's compare found differing come down in @@ -2293,6 +2648,72 @@ struct CardRange { picked: bool, } +struct CardCompare { + /// First declaration using this dispatch, for its buffer and compare mode. + range: usize, + span: crate::shadow::CardSpan, + at: u32, +} + +/// Allocate results for a declared range. Declarations stay byte-exact for +/// landing, while the GPU hashes whole pieces. Overlapping or adjacent +/// piece runs in the same copy can share one dispatch and result interval. +fn queue_card_compare( + compares: &mut Vec<CardCompare>, + first_for_copy: usize, + range: usize, + span: crate::shadow::CardSpan, + next: &mut u32, + capacity: u64, +) -> Option<u32> { + if let Some(last) = compares[first_for_copy..].last_mut() + && span.first <= last.span.first + last.span.pieces + { + let pieces = last.span.pieces.max(span.first + span.pieces - last.span.first); + let extra = pieces - last.span.pieces; + if u64::from(*next + extra) > capacity { + return None; + } + last.span.pieces = pieces; + last.span.to = last.span.to.max(span.to); + *next += extra; + return Some(last.at + span.first - last.span.first); + } + if u64::from(*next + span.pieces) > capacity { + return None; + } + let at = *next; + compares.push(CardCompare { range, span, at }); + *next += span.pieces; + Some(at) +} + +#[cfg(test)] +mod card_compare_tests { + use super::queue_card_compare; + use crate::shadow::CardSpan; + + #[test] + fn declarations_share_flags_for_touching_pieces_of_the_same_copy() { + let span = |first, pieces| CardSpan { from: 0, to: 0, first, pieces, skew: 0 }; + let mut compares = Vec::new(); + let mut next = 4; + assert_eq!(queue_card_compare(&mut compares, 0, 0, span(3, 2), &mut next, 9), Some(4)); + assert_eq!(queue_card_compare(&mut compares, 0, 1, span(4, 2), &mut next, 9), Some(5)); + assert_eq!(queue_card_compare(&mut compares, 0, 2, span(6, 1), &mut next, 9), Some(7)); + assert_eq!(compares.len(), 1); + assert_eq!(compares[0].span.pieces, 4); + assert_eq!(next, 8); + // A failed allocation leaves the earlier dispatch intact. + assert_eq!(queue_card_compare(&mut compares, 0, 3, span(7, 2), &mut next, 9), None); + assert_eq!(compares[0].span.pieces, 4); + // A different buffer gets its own flags, even at the same offset. + assert_eq!(queue_card_compare(&mut compares, 1, 4, span(4, 1), &mut next, 9), Some(8)); + assert_eq!(compares.len(), 2); + assert_eq!(next, 9); + } +} + impl CardPlan { /// `crate::picked` is told where what it looked at changed, by the /// compare's results. @@ -2324,6 +2745,8 @@ struct CardPlan { looks: Option<upcheck::Looks>, /// With [`send`]: the memory its sends come from. sends: Option<send::Memory>, + /// With [`prefetch`]: where the pieces its compare flagged came down. + prefetch: Option<prefetch::Spill>, } /// One piece of submission-time work, in recorded order. @@ -2401,6 +2824,9 @@ struct Deferred { back_wanted: Vec<crate::texback::Target>, /// Those copies, whose texels go to title memory once the list has run. texture_backs: Vec<crate::texback::Back>, + /// Upload buffers taken from [`BUFFER_POOL`] for this recording, given + /// back to it when the list is reset ([`HostList::upload`]). + pooled_uploads: Vec<Pooled>, /// Whether the indirect-work budget is zeroed for this recording (a /// step on the CPU, or in the list for the card's copy). budget_zeroed: bool, @@ -2409,6 +2835,9 @@ struct Deferred { /// indirect arguments; 0 if none. It stays readable until the next /// clamp into it ([`HostList::indirect_state`]). indirect_readable: usize, + /// The buffer of ours that constants read behind copies at their place + /// go into, and the bytes of it used ([`HostList::placed_constants`]). + constants: Option<(ID3D12Resource, u64)>, } impl Deferred { @@ -2428,6 +2857,31 @@ impl Deferred { self.gpu_written.clear(); self.filled.clear(); } + + /// Empties all lists and sets in place, keeping their backing capacity. + fn clear(&mut self) { + give_chunks(std::mem::take(&mut self.plane_uploads)); + ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); + ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); + self.copies.clear(); + self.uploads.clear(); + self.prelude_uploads.clear(); + self.upload_bytes = 0; + self.kept.clear(); + self.bound.clear(); + self.refreshed.clear(); + self.gpu_written.clear(); + self.filled.clear(); + self.textures.clear(); + self.writes.clear(); + self.backs.clear(); + self.back_wanted.clear(); + self.texture_backs.clear(); + self.pooled_uploads.clear(); + self.budget_zeroed = false; + self.indirect_readable = 0; + self.constants = None; + } } impl Drop for Deferred { @@ -2844,7 +3298,12 @@ const WHY_FENCE: usize = 10; /// bottom-of-pipe write; fence signals set behind flights. /// Then: the settles for title memory read, by what read it (a buffer /// copy, a fill of upload memory, a texture). -static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; +static LATE_STATS: [std::sync::atomic::AtomicU64; 20] = [const { std::sync::atomic::AtomicU64::new(0) }; 20]; +/// [`LATE_STATS`] 18 and 19: settles for title memory read by a step that reads the +/// destination of a copy at its place ([`place::reads`]), and by a refresh, host step or plane +/// reading the destination of a copy done on the card ([`card_steps::copied_read`]). +const READ_PLACED: usize = 18; +const READ_REFRESH: usize = 19; /// Since the last frame-rate line: the microseconds settles waited for the /// card, by why they settled (the `WHY_` places). @@ -2896,12 +3355,21 @@ fn late_blocked(runs: &[&HostList]) -> Option<usize> { } (line.written.clone(), card_steps::copies(&line)) }; - blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ)) + blocked_by(&written, runs, true).or_else(|| { + card_steps::copied_read(&copies, runs).then(|| { + LATE_STATS[READ_REFRESH].fetch_add(1, Ordering::Relaxed); + WHY_READ + }) + }) } /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for /// flights when the title itself wrote the memory since they were given it -/// (`VICTORY_FILL_TITLE=1`; off by default). +/// (always; the switch `VICTORY_FILL_TITLE` is gone. It was off until the +/// 480-byte constants ring was found to drain the card once a frame: 43-59 ms of a +/// 70-84 ms frame, docs/performance/AGENT_REPORTS/06-cpu-threading.md). Constants +/// 256-aligned in the title's graphics heap are no fill at all any more: they +/// are read in place (`crate::port::constants`); this is for the rest. /// /// The title's 174 MB heap is declared written as a whole (a root view has /// no size), and the title keeps a ring of constants in it: one fill of 480 @@ -2920,9 +3388,7 @@ fn late_blocked(runs: &[&HostList]) -> Option<usize> { /// for the first time, is read as it was before that flight. fn fill_is_titles(src: usize, len: usize) -> bool { const SMALL: usize = 64 << 10; - static ON: OnceLock<bool> = OnceLock::new(); - let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1")); - on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600)) + len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600)) } /// Diagnostics: the waits for flights, by what waited, why it was not done @@ -3071,10 +3537,18 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op if written.is_empty() { return None; } - // Destinations of copies at their place, if a step reads them. + // Destinations of copies at their place that stand ahead of the step looked + // at, if the step reads them: the copy's bytes are not in title memory when + // the flights are not waited for (steps ahead of the copy read what was there). let mut placed: Vec<(usize, usize)> = Vec::new(); for list in runs { for step in &list.deferred().copies { + if !placed.is_empty() && place::reads(step, &placed) { + if count { + LATE_STATS[READ_PLACED].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } match step { &Step::Copy(dst, src, len) => { if let Some(_read) = copy_blocked(written, dst, src, len) { @@ -3138,7 +3612,7 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op } } } - (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ) + None } /// With flights in the air, after the submission's write-watch asking: @@ -3173,6 +3647,16 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow: stale_of(spans) } +/// From this many copies on, [`stale_of`] merges them on several threads. +const MERGE_ACROSS_FROM: usize = 2; + +/// Whether [`stale_of`] merges copies on several threads (`VICTORY_MERGE_ACROSS=0`: +/// one after the other on the submitting thread, as before). +fn merge_across() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MERGE_ACROSS").is_none_or(|v| v != "0")) +} + /// Of `spans` (a copy shaders may be writing, and the span of what a /// submission refreshes of it), those [`stale_under_flights`] answers. fn stale_of( @@ -3186,6 +3670,32 @@ fn stale_of( // title's ring of constants come here too, which were waited for // before: hundreds of short runs each, at about 1.5 us a run. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 }; + if spans.len() >= MERGE_ACROSS_FROM && merge_across() { + // Copies apart, on several threads (each copy takes its own + // locks; what they share, the write watch's journal and the + // count of runs, is safe to share). The count may go a little + // past its line between two copies' takings: it is a line of + // cost, not of correctness. + use std::sync::atomic::{AtomicBool, AtomicI64}; + let left = AtomicI64::new(runs_left as i64); + let keep: Vec<AtomicBool> = spans.iter().map(|_| AtomicBool::new(false)).collect(); + let spans_ref = &spans; + crate::land::each_merge(spans.len(), &|i| { + let (shadow, from, to) = &spans_ref[i]; + let mut mine = left.load(Ordering::Relaxed).max(0) as usize; + let had = mine; + let settle = crate::shadow::merge_across(|| shadow.merge_under_writes(*from, *to - *from, &mut mine)); + left.fetch_sub(had.saturating_sub(mine) as i64, Ordering::Relaxed); + keep[i].store(settle, Ordering::Relaxed); + }); + let mut i = 0; + spans.retain(|_| { + let k = keep[i].load(Ordering::Relaxed); + i += 1; + k + }); + return spans; + } spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); return spans; } @@ -3380,24 +3890,79 @@ pub(crate) fn tiles_mapped_on(queue: &ID3D12CommandQueue) { /// Settles the flights in the air, if any ([`Host::settle`]), for reason /// `why` (one of the `WHY_` places). Not from inside a submission. pub(crate) fn settle_now(why: usize) { + settle_now_for(why, None); +} + +fn settle_now_for(why: usize, reason: Option<FenceDrain>) { if !late() { return; } let Some(host) = host() else { return; }; + let began = reason.map(|_| now_us()); let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let acquired = began.map(|_| now_us()); + let value = *submitted; host.settle(&mut submitted, why); + drop(submitted); + if let (Some(reason), Some(began), Some(acquired)) = (reason, began, acquired) { + let lock = acquired.saturating_sub(began); + let drain = now_us().saturating_sub(acquired); + let [calls, lock_us, drain_us] = &FENCE_DRAINS[reason as usize]; + calls.fetch_add(1, Ordering::Relaxed); + lock_us.fetch_add(lock, Ordering::Relaxed); + drain_us.fetch_add(drain, Ordering::Relaxed); + if render_trace::active() { + render_trace::event("fence_drain", format_args!("reason={}\tstart_us={began}\tlock_us={lock}\tdrain_us={drain}\thost_fence={value}", reason.name())); + } + } } /// [`settle_now`] at a present, and for a fence the title blocks on. pub(crate) fn settle_for_present() { settle_now(WHY_SYNC); } -pub(crate) fn settle_for_fence() { - settle_now(WHY_FENCE); +#[derive(Clone, Copy)] +pub(crate) enum FenceDrain { + TitleFence, + BakeTextureFlip, + BakePublish, + ExternalUpscaler, +} + +impl FenceDrain { + const ALL: [Self; 4] = [Self::TitleFence, Self::BakeTextureFlip, Self::BakePublish, Self::ExternalUpscaler]; + + fn name(self) -> &'static str { + match self { + Self::TitleFence => "title_fence", + Self::BakeTextureFlip => "bake_texture_flip", + Self::BakePublish => "bake_publish", + Self::ExternalUpscaler => "external_upscaler", + } + } +} + +static FENCE_DRAINS: [[AtomicU64; 3]; FenceDrain::ALL.len()] = [const { [const { AtomicU64::new(0) }; 3] }; FenceDrain::ALL.len()]; + +pub(crate) fn settle_for_fence(reason: FenceDrain) { + settle_now_for(WHY_FENCE, Some(reason)); +} + +/// Whether the submitting thread is currently preparing a submission. +pub(crate) fn submitting_active() -> bool { + SUBMITTING[0].load(Ordering::Relaxed) == 1 } +/// Landed flights (beyond [`bury_lag`]) past which the submitting thread +/// resets their lists itself instead of leaving them to [`late_helper`]. +const LAND_INLINE: usize = 256; + +/// Since the last frame-rate line: times the submitting thread reset landed +/// lists itself ([`LAND_INLINE`]). +static LANDED_INLINE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// Resets the host lists of settled flights and keeps them for reuse, as /// a queue does for the lists it ran (`crate::list::recycle`). fn land() { @@ -3411,6 +3976,8 @@ fn land() { } } +static RELAY_HELPER_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// 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 @@ -3426,6 +3993,10 @@ fn late_helper() { tracing::warn!("no event for the thread that settles submissions sent ahead"); return; }; + let relayed = relay(); + if relayed { + RELAY_HELPER_READY.store(true, Ordering::Release); + } loop { let target = { let mut line = line(); @@ -3435,7 +4006,7 @@ fn late_helper() { break None; } // (With the relay the flights are another thread's.) - if !relay() && !line.line.is_empty() && !line.settling { + if !relayed && !line.line.is_empty() && !line.settling { break Some(line.target); } line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); @@ -3446,6 +4017,10 @@ fn late_helper() { land(); helping.next("helper: looking at what queues hold"); crate::queue::release_held(false); + if relayed { + helping.next("helper: dropping retired resources"); + bury(FINISHED.load(Ordering::Acquire)); + } continue; }; // The card first, without the submission lock: the submitting @@ -3734,7 +4309,8 @@ fn late_line(frames: f64) { "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ - a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \ + a texture {:.1}, a step that reads where a copy at its place writes {:.1}, a refresh or host read of where a copy done on the card writes {:.1}), \ + a step of ours {:.1}, {} lists in the air {:.1}, \ bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights", s[0], @@ -3749,6 +4325,8 @@ fn late_line(frames: f64) { s[15], s[16], s[17], + s[READ_PLACED], + s[READ_REFRESH], s[WHY_RUN], late_most(), s[WHY_MOST], @@ -3788,14 +4366,16 @@ fn late_line(frames: f64) { r[4] / 1000.0, ); if send::own() { - let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let t = send::STATS.each_ref().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames); tracing::info!( "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \ - taking them out of the CPU sides", + taking them out of the CPU sides; {:.1} MB sent directly, {:.1} MB via VRAM staging", t[0] / (1 << 20) as f64, t[1], t[2], t[3] / 1000.0, + t[4] / (1 << 20) as f64, + t[5] / (1 << 20) as f64, ); } let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); @@ -3809,18 +4389,32 @@ fn late_line(frames: f64) { } } crate::land::log(frames); + prefetch::log(frames); + water_timing::log(frames); + gpu_time::log(frames); + crate::descriptor::host::dynamic_line(frames); + for reason in FenceDrain::ALL { + let [calls, lock_us, drain_us] = FENCE_DRAINS[reason as usize].each_ref().map(|c| c.swap(0, Ordering::Relaxed)); + if calls != 0 { + tracing::info!(reason = reason.name(), calls, calls_per_frame = calls as f64 / frames, + lock_ms_per_frame = lock_us as f64 / (1000.0 * frames), drain_ms_per_frame = drain_us as f64 / (1000.0 * frames), + "blocking fence by origin"); + } + } if place::on() { let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); tracing::info!( - "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote", + "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote; {:.1} constants read on the card behind them", t[0], t[1] / 1024.0, t[2], t[3], + t[4], ); } card_steps::log(frames); crate::port::log(frames); + crate::demand::log(frames); crate::picked::log(frames); #[cfg(feature = "diagnostics")] log_blame(frames); @@ -3838,12 +4432,18 @@ pub(crate) mod aside; pub(crate) mod awake; mod card_steps; pub(crate) mod indirects; +pub(crate) mod memory_samples; +mod uav_residency; mod font; mod menu; mod panel; mod place; +mod prefetch; +#[cfg(test)] +pub(crate) use prefetch::{CARD_SPILL, STRIDE as SPILL_STRIDE}; mod send; pub(crate) use send::{goes_as_words, words_under}; +mod shown; #[cfg(feature = "diagnostics")] pub(crate) mod spans; mod torn; @@ -3853,6 +4453,10 @@ pub(crate) mod two_queues; pub(crate) mod upcheck; #[cfg(feature = "diagnostics")] mod stamps; +mod water_timing; +mod gpu_time; +pub(crate) mod render_trace; +pub(crate) use gpu_time::{Step as GpuStep, count_barriers as count_gpu_barriers, count_step as count_gpu_step}; #[cfg(feature = "diagnostics")] pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps}; @@ -4003,6 +4607,7 @@ pub(crate) fn walls_trace() -> bool { /// without it, so the title read a buffer nobody wrote, as before read-backs /// were made (the exposure metering's two small float targets, every frame). fn read_backs(list: &HostList) { + list.water_timing.collect(); // Textures shaders wrote that the title reads on the CPU // ([`crate::texback`]). for back in &list.deferred().texture_backs { @@ -4248,6 +4853,20 @@ impl Host { ), ); } + #[cfg(not(feature = "diagnostics"))] + if dred_release() { + static NUMBER: AtomicU32 = AtomicU32::new(0); + let number = NUMBER.fetch_add(1, Ordering::Relaxed); + name(&list, || format!("victory host list {number}")); + let mut all = RELEASE_LISTS.lock().unwrap_or_else(|e| e.into_inner()); + if number.is_multiple_of(256) { + all.retain(|_, l| l.strong_count() > 0); + } + all.insert(number, std::sync::Arc::downgrade(&pipelines)); + } + // (made open: it is recorded from here on) + let gpu_time = gpu_time::List::default(); + gpu_time.start(&list); Ok(HostList { allocator, list, @@ -4270,12 +4889,15 @@ impl Host { holding: std::sync::atomic::AtomicBool::new(false), upscale: std::sync::atomic::AtomicU64::new(0), hudless: std::sync::atomic::AtomicU64::new(0), + heap_picked: std::sync::atomic::AtomicBool::new(false), left_open: [const { std::sync::atomic::AtomicU64::new(0) }; 2], _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, #[cfg(feature = "diagnostics")] stamps: OnceLock::new(), + water_timing: water_timing::List::default(), + gpu_time, }) } } @@ -4312,8 +4934,8 @@ impl Host { }; let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); state.0 += 1; - // SAFETY: our queue and the clock's fence. - let _ = unsafe { self.queue.Signal(&clock.fence, state.0) }; + // (Behind what was sent, also when that is held behind a present: [`shown`].) + let _ = self.queue_send(&[], &[], Some((&clock.fence, state.0))); if let Some((since, worked_then)) = state.1.take() { CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed); @@ -4354,7 +4976,7 @@ impl Host { None, windows::core::s!("main"), windows::core::s!("cs_5_1"), - 0, + 1 << 15, 0, &mut code, None, @@ -4365,7 +4987,7 @@ impl Host { // A megabyte of results: 262,144 pieces, 16 GB of declared ranges // in one submission. const RESULTS: u64 = 1 << 20; - let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; + let (differs, data) = self.shared_buffer_cpu(RESULTS).ok_or_else(windows::core::Error::empty)?; name(&differs, || "card compare results".into()); // SAFETY: the blob's own bytes; the root signature is inside the // shader. @@ -4430,9 +5052,11 @@ impl Host { None => 0, }; let gathering = crate::timeline::span("copies in the card's memory: what changed"); + let began = std::time::Instant::now(); let mut dirty = crate::shadow::card_dirty(sent_as); gathering.end(); if declared.is_empty() && dirty.is_empty() && looked.is_empty() { + card_time(0, began); return None; } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); @@ -4442,7 +5066,7 @@ impl Host { let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new(); for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) { if shadow.card_make_before(|size| { - let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; + let before = self.uav_buffer_for(crate::shadow::card_hash_bytes(size), Kind::UavShadow)?; name(&before, || "title buffer on the card, hashes of its pieces".into()); Some(before) }) { @@ -4455,9 +5079,16 @@ impl Host { let mut used: Vec<(bool, Prelude)> = Vec::new(); let mut looks = None; // The bytes as they are now, whatever later submissions put there. + let mark = card_time(0, began); let taking = crate::timeline::span("copies in the card's memory: taken"); let own = if send::own() { send::take(self, &dirty) } else { None }; taking.end(); + let mark = card_time(1, mark); + // Dwords of `differs` the hash passes' tables take (`card_table`), ahead of the + // compare's results: given back with them. + let mut hash_slot = work.taken; + let capacity = work.differs.2 / 4; + let differs_data = work.differs.1; if !dirty.is_empty() { let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list to bring host copies in the card's memory up to date")); @@ -4471,6 +5102,7 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + let mut timed = gpu_time::Ours::begin(list, "ours: title bytes sent up to the card's copies, then hashed"); if upcheck::on() { looks = upcheck::record(self, list, &dirty); } @@ -4511,6 +5143,7 @@ impl Host { if !sent.is_empty() { list.ResourceBarrier(&sent); } + timed.pass(list, "ours: hashes of the pieces sent up"); list.SetComputeRootSignature(&work.root); list.SetPipelineState(&work.pso); list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); @@ -4543,14 +5176,29 @@ impl Host { }; // The same pieces in fewer passes (`rehash_runs`). let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs }; - CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); - CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed); - for run in runs { - card_pass(list, &run, size as u32, 0, 0); + let pieces: u32 = runs.iter().map(|r| r.pieces).sum(); + CARD_PASSES[1].fetch_add(u64::from(pieces), Ordering::Relaxed); + // Scattered runs of the copy: one table pass (`card_table`), in + // dwords of `differs` taken ahead of the compare's results. + let table = card_table() + && runs.len() > 1 + && runs.iter().all(|r| r.skew == runs[0].skew) + && u64::from(hash_slot) + u64::from(pieces) <= capacity; + if table { + let numbers: Vec<u32> = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + card_table_pass(list, differs_data, hash_slot, &numbers, runs[0].skew, size as u32, 0); + hash_slot += pieces; + CARD_PASSES[0].fetch_add(1, Ordering::Relaxed); + } else { + CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); + for run in runs { + card_pass(list, &run, size as u32, 0, 0); + } } } + timed.end(list); list.Close()?; - self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.queue_send(&[Some(list.cast()?)], &[], None)?; Ok(()) })() }; @@ -4560,6 +5208,7 @@ impl Host { used.push((false, sync)); } drop(order); + let mark = card_time(2, mark); let mut plan = CardPlan { ranges: Vec::new(), check: None, @@ -4568,10 +5217,14 @@ impl Host { sent_as, looks, sends: own.map(send::Own::memory), + prefetch: None, }; + work.taken = hash_slot; // Each byte once, as the copy-back joins the declared ranges. The // results go behind those of plans still in the air. let mut at = work.taken; + let first_result = at; + let mut compares = Vec::new(); for (shadow, ranges) in &declared { let mut sorted = ranges.clone(); sorted.sort_unstable(); @@ -4582,31 +5235,32 @@ impl Host { _ => spans.push((from, to)), } } - let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let twin = shadow.card_has_before(); + let first_for_copy = compares.len(); for (from, to) in spans { let Some(span) = shadow.card_span(from, to) else { continue; }; - let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; + let compared = twin.then(|| { + queue_card_compare(&mut compares, first_for_copy, plan.ranges.len(), span, &mut at, capacity) + }).flatten(); plan.ranges.push(CardRange { shadow: shadow.clone(), declared: (from, to), span, - at, - compared, + at: compared.unwrap_or(0), + compared: compared.is_some(), picked: false, }); - if compared { - at += span.pieces; - } } } for (shadow, from, len) in looked { - let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let twin = shadow.card_has_before(); if let Some(span) = shadow.card_span(*from, from + len) && twin - && u64::from(at + span.pieces) * 4 <= work.differs.2 + && u64::from(at + span.pieces) <= capacity { + compares.push(CardCompare { range: plan.ranges.len(), span, at }); plan.ranges.push(CardRange { shadow: shadow.clone(), declared: (*from, from + len), @@ -4619,7 +5273,7 @@ impl Host { } } work.taken = at; - if plan.ranges.iter().any(|r| r.compared) { + if !compares.is_empty() { let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list for the compare of host copies in the card's memory")); }; @@ -4631,6 +5285,7 @@ impl Host { (|| -> windows::core::Result<ID3D12CommandList> { allocator.Reset()?; list.Reset(allocator, None)?; + let mut timed = gpu_time::Ours::begin(list, "ours: compares of the card's copies after the lists"); // What the submission's shaders wrote, first. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -4644,17 +5299,53 @@ impl Host { list.SetComputeRootSignature(&work.root); list.SetPipelineState(&work.pso); list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); - for r in plan.ranges.iter().filter(|r| r.compared) { + let mut i = 0; + while i < compares.len() { + let pass = &compares[i]; + let r = &plan.ranges[pass.range]; + // (What is only looked at keeps its hashes: what + // changed there is the next declared range's to land.) + let mode = if flown && !r.picked { 2 } else { 1 }; let (Some((_, Some(before), _)), size) = (r.shadow.card_sides(), r.shadow.card_hash_size()) else { + i += 1; continue; }; list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - // (What is only looked at keeps its hashes: what - // changed there is the next declared range's to land.) - card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 }); + // The compares after it of the same copy, mode and skew whose results + // follow its own: one table pass (`card_table`). + let mut j = i + 1; + if card_table() { + while j < compares.len() { + let (q, p) = (&compares[j], &compares[j - 1]); + let s = &plan.ranges[q.range]; + let same_mode = (if flown && !s.picked { 2 } else { 1 }) == mode; + if Arc::ptr_eq(&s.shadow, &r.shadow) + && same_mode + && q.span.skew == pass.span.skew + && q.at == p.at + p.span.pieces + { + j += 1; + } else { + break; + } + } + } + if j - i > 1 { + let numbers: Vec<u32> = + compares[i..j].iter().flat_map(|c| c.span.first..c.span.first + c.span.pieces).collect(); + card_table_pass(list, work.differs.1, pass.at, &numbers, pass.span.skew, size as u32, mode); + } else { + card_pass(list, &pass.span, size as u32, pass.at, mode); + } CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); + i = j; } + if flown && prefetch::on() { + timed.pass(list, "ours: flagged pieces copied down (prefetch)"); + plan.prefetch = prefetch::record(self, list, &plan.ranges, &compares, &work.differs.0, first_result, at); + } + timed.end(list); list.Close()?; list.cast() })() @@ -4666,6 +5357,7 @@ impl Host { plan.lists.push((true, check)); } work.out += 1; + card_time(3, mark); Some(plan) } @@ -4691,6 +5383,9 @@ impl Host { if let Some(memory) = plan.sends { send::give_back(memory); } + if let Some(spill) = plan.prefetch { + prefetch::give_back(spill); + } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); let Some(work) = work.as_mut() else { return; @@ -4706,6 +5401,108 @@ impl Host { } } + /// Fetches `len` bytes from a carded resource at `offset` into `out` + /// synchronously for C2 demand landing (`crate::demand`). + pub(crate) fn demand_fetch(&self, src: &ID3D12Resource, offset: u64, len: usize, out: &mut Vec<u8>) -> bool { + struct DemandFetch { + list: Prelude, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + event: HANDLE, + sent: u64, + staging: Option<(ID3D12Resource, usize, u64)>, + } + // SAFETY: serialized behind `DEMAND_FETCH`; its D3D12 objects and event + // handle may move across threads under that mutex. + unsafe impl Send for DemandFetch {} + static DEMAND_FETCH: Mutex<Option<DemandFetch>> = Mutex::new(None); + if len == 0 { + out.clear(); + return true; + } + let mut guard = DEMAND_FETCH.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + // SAFETY: creating dedicated copy/fallback objects on live `self.device`. + let created = unsafe { + (|| -> windows::core::Result<DemandFetch> { + let copying = (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> { + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + list.Close()?; + let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0, + ..Default::default() + })?; + Ok(((allocator, list), queue)) + })(); + let (list, queue) = match copying { + Ok(pair) => pair, + Err(_) => { + let Some(list) = self.make_prelude() else { + return Err(windows::core::Error::from(windows::Win32::Foundation::E_FAIL)); + }; + (list, self.queue.clone()) + } + }; + let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let staging = self.shared_buffer_cpu(256 << 10).map(|(r, p)| (r, p as usize, 256 << 10)); + Ok(DemandFetch { + list, + queue, + fence, + event, + sent: 0, + staging, + }) + })() + }; + let Ok(df) = created else { + return false; + }; + *guard = Some(df); + } + let Some(df) = guard.as_mut() else { + return false; + }; + let need = len as u64; + if df.staging.as_ref().is_none_or(|b| b.2 < need) { + let size = need.next_multiple_of(64 << 10); + df.staging = self.shared_buffer_cpu(size).map(|(r, p)| (r, p as usize, size)); + } + let Some((staging, data, _)) = df.staging.clone() else { + return false; + }; + df.sent += 1; + let sent = df.sent; + let (allocator, list) = &df.list; + // SAFETY: `df` is exclusively held and waited for `df.sent - 1`; live buffers. + let ok = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + list.CopyBufferRegion(&staging, 0, src, offset, need); + list.Close()?; + let lists = [Some(list.cast::<ID3D12CommandList>()?)]; + df.queue.ExecuteCommandLists(&lists); + df.queue.Signal(&df.fence, sent)?; + df.fence.SetEventOnCompletion(sent, df.event)?; + WaitForSingleObject(df.event, INFINITE); + Ok(()) + })() + } + .is_ok(); + if !ok { + return false; + } + out.resize(len, 0); + // SAFETY: staging buffer holds `len` bytes written by the completed copy. + unsafe { std::ptr::copy_nonoverlapping(data as *const u8, out.as_mut_ptr(), len) }; + true + } + /// The relay's own list, fence, event for [`Host::relay_card_back`]. fn make_relay_fetch(&self) -> Option<RelayFetch> { // SAFETY: plain object creation. @@ -4762,13 +5559,20 @@ impl Host { /// there is one. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) { use crate::land; + /// Where a piece's bytes are: fetched now (offset in the fetch's + /// memory), or come down with a flight (address, and the send that + /// flight ran behind). + #[derive(Clone, Copy)] + enum From { + Fetch(u64), + Slot(usize, u64), + } let gathering = std::time::Instant::now(); let differs = { let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) }; - let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new(); - let mut total = 0u64; + let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, From)> = Vec::new(); if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) { fetch.had.landing(first); } @@ -4776,6 +5580,9 @@ impl Host { // have run, and their dwords are given to no other plan before these // are done with (`card_done`). let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }); + // Per piece (copy, number): where the last flight of the landing + // that wants it left it (`prefetch`), or nowhere (fetched). + let mut slots: std::collections::HashMap<(usize, u32), Option<(usize, u64)>> = std::collections::HashMap::new(); if let Some(differs) = differs { // Pieces caught while a later flight was at them (`torn`). let suspects = fetch.as_ref().map(|f| &f.suspects); @@ -4795,6 +5602,27 @@ impl Host { }) .collect(); let fetched = flagged_pieces(&flags); + // What came down with this flight: any range's result of + // the piece may hold its slot (the first compare of it that + // flagged it). + if let Some(spill) = &plan.prefetch { + let mut came: std::collections::HashMap<(usize, u32), usize> = std::collections::HashMap::new(); + for r in plan.ranges.iter().filter(|r| r.compared && !r.picked) { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + if let Some(at) = spill.slot(r.at + p) { + came.entry((copy, r.span.first + p)).or_insert(at); + } + } + } + for piece in &fetched { + slots.insert(*piece, came.get(piece).map(|&at| (at, plan.sent_as))); + } + } else { + for piece in &fetched { + slots.insert(*piece, None); + } + } for r in plan.ranges.iter().filter(|r| !r.picked) { let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; if upcheck::on() { @@ -4814,12 +5642,14 @@ impl Host { continue; } } + if crate::demand::park(&r.shadow, lo, hi, plan.sent_as) { + continue; + } if upcheck::on() { upcheck::fetched(r.shadow.id(), lo); } seen.insert((copy, lo, hi)); - pieces.push((r.shadow.clone(), lo, hi, total)); - total += (hi - lo) as u64; + pieces.push((r.shadow.clone(), lo, hi, From::Fetch(0))); } } crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); @@ -4827,32 +5657,62 @@ impl Host { } } if land::on() { - // In the order they are landed, each byte of a copy once. + // In the order they are landed, each byte of a copy once. (Parts + // joined are of one piece: they come from the same place.) let keys: Vec<land::Piece> = pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect(); - total = 0; pieces = land::ordered(&keys) .into_iter() .map(|(i, title, len)| { let shadow = &pieces[i].0; let lo = title - shadow.span().0 as usize; - let at = total; - total += len as u64; - (shadow.clone(), lo, lo + len, at) + (shadow.clone(), lo, lo + len, From::Fetch(0)) }) .collect(); } + // Where each comes from, by the last flight that wanted its piece. + for (shadow, lo, hi, from) in &mut pieces { + let number = shadow.card_piece_of(*lo); + let slot = slots.get(&(std::sync::Arc::as_ptr(shadow) as usize, number)).copied().flatten(); + if let Some((at, sent_as)) = slot { + let hashed = shadow.card_hashed(number).0; + if hashed <= *lo { + *from = From::Slot(at + (*lo - hashed), sent_as); + } + } + if prefetch::on() { + prefetch::landed(matches!(from, From::Slot(..)), (*hi - *lo) as u64); + } + } + // What is fetched now: those with no slot, one after the other. + let mut fetching: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new(); + let mut fetched_as: Vec<Option<usize>> = Vec::with_capacity(pieces.len()); + let mut total = 0u64; + for (shadow, lo, hi, from) in &pieces { + if let From::Fetch(_) = from { + fetched_as.push(Some(fetching.len())); + fetching.push((shadow.clone(), *lo, *hi, total)); + total += (hi - lo) as u64; + } else { + fetched_as.push(None); + } + } land::spent(land::stat::GATHER, gathering); if fetch.is_none() { *fetch = self.make_relay_fetch(); } // On the copy queue a later flight may be at a piece while it is // fetched: the pieces come down whole, to be hashed. - let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some())) - .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces)); + let check = (torn::on() && !fetching.is_empty() && fetch.as_ref().is_some_and(|f| f.queue.is_some())) + .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut fetching)); if let Some(check) = &check { total = check.total; } + for (i, k) in fetched_as.iter().enumerate() { + if let Some(k) = *k { + pieces[i].3 = From::Fetch(fetching[k].3); + } + } #[cfg(feature = "diagnostics")] for (shadow, lo, hi, _) in &pieces { traffic::moved(traffic::FETCHED, shadow.span(), std::iter::once((*lo, *hi))); @@ -4860,88 +5720,108 @@ impl Host { // The sends these flights ran behind, all a fetch on the copy queue // is known to have run behind. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0); + // Every send so far is older than the next fetch, if that goes to + // the queue the sends went to. With slots, flights in the air ran + // behind sends after `behind` and are merged with those: the notes + // of sends up to `behind` alone go. + let older = |fetch: &Option<RelayFetch>| match prefetch::on() || fetch.as_ref().is_some_and(|f| f.queue.is_some()) { + true => behind, + false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + }; if pieces.is_empty() { - // Nothing to fetch: every send so far is older than the next - // fetch, if that goes to the queue the sends went to. - let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) { - true => behind, - false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + crate::shadow::relay_fetched(older(fetch)); + return; + } + let (mut data, mut after) = (0usize, older(fetch)); + if !fetching.is_empty() { + let Some(f) = fetch.as_mut() else { + fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); + }; + if f.buffer.as_ref().is_none_or(|b| b.2 < total) { + let size = total.next_multiple_of(16 << 20); + f.buffer = self.shared_buffer_cpu(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((buffer, mapped, _)) = f.buffer.clone() else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); + }; + data = mapped; + f.sent += 1; + let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let copy_queue = f.queue.clone(); + let waiting = std::time::Instant::now(); + // The flights the fetch runs behind: those in the line by now + // have been given to the queue. On the copy queue, those landed + // here. + let ahead = match copy_queue { + Some(_) => 0, + None => line().target, }; - crate::shadow::relay_fetched(after); - return; - } - let Some(f) = fetch.as_mut() else { - fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); - }; - if f.buffer.as_ref().is_none_or(|b| b.2 < total) { - let size = total.next_multiple_of(16 << 20); - f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); - } - let Some((buffer, data, _)) = f.buffer.clone() else { - fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); - }; - f.sent += 1; - let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); - let copy_queue = f.queue.clone(); - let waiting = std::time::Instant::now(); - // The flights the fetch runs behind: those in the line by now have - // been given to the queue. On the copy queue, those landed here. - let ahead = match copy_queue { - Some(_) => 0, - None => line().target, - }; - // SAFETY: the list's last run was waited for by this thread; live - // buffers (the copies are held by the plans); the fence and the - // event are this thread's. - let ran = unsafe { - (|| -> windows::core::Result<u64> { - allocator.Reset()?; - list.Reset(&allocator, None)?; - for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) { - list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); - } - list.Close()?; - let lists = [Some(list.cast::<ID3D12CommandList>()?)]; - let _fetching = crate::timeline::span("landing: fetching pieces"); - if let Some(queue) = ©_queue { - queue.ExecuteCommandLists(&lists); - queue.Signal(&fence, sent)?; + // SAFETY: the list's last run was waited for by this thread; + // live buffers (the copies are held by the plans); the fence and + // the event are this thread's. + let ran = unsafe { + (|| -> windows::core::Result<u64> { + allocator.Reset()?; + list.Reset(&allocator, None)?; + // (timed on the host queue only: a copy queue's clock is another) + let timed = copy_queue.is_none().then(|| gpu_time::Ours::begin(&list, "ours: the relay's fetch of what shaders wrote")); + for (shadow, lo, hi, at) in check.as_ref().map_or(&fetching, |c| &c.copies) { + list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + } + if let Some(timed) = timed { + timed.end(&list); + } + list.Close()?; + let lists = [Some(list.cast::<ID3D12CommandList>()?)]; + let _fetching = crate::timeline::span("landing: fetching pieces"); + if let Some(queue) = ©_queue { + queue.ExecuteCommandLists(&lists); + queue.Signal(&fence, sent)?; + meanwhile(); + fence.SetEventOnCompletion(sent, event)?; + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(None); + WaitForSingleObject(event, INFINITE); + return Ok(behind); + } + // In the order of the queue: the sends of title bytes so + // far are ahead of this fetch, every later one behind it. + let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + self.queue_send(&lists, &[], Some((&fence, sent)))?; + let after = *order; + drop(order); + self.card_sent(); meanwhile(); fence.SetEventOnCompletion(sent, event)?; #[cfg(feature = "diagnostics")] let _card = crate::timeline::card_wait(None); WaitForSingleObject(event, INFINITE); - return Ok(behind); - } - // In the order of the queue: the sends of title bytes so - // far are ahead of this fetch, every later one behind it. - let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); - self.queue.ExecuteCommandLists(&lists); - let after = *order; - drop(order); - self.card_sent(); - self.queue.Signal(&fence, sent)?; - meanwhile(); - fence.SetEventOnCompletion(sent, event)?; - #[cfg(feature = "diagnostics")] - let _card = crate::timeline::card_wait(None); - WaitForSingleObject(event, INFINITE); - Ok(after) - })() - }; - let after = match ran { - Ok(after) => after, - Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), - }; - let us = waiting.elapsed().as_micros() as u64; - RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); - { - use crate::shadow::CARD_STATS; - CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); - CARD_STATS[4].fetch_add(total, Ordering::Relaxed); - CARD_STATS[5].fetch_add(1, Ordering::Relaxed); - CARD_STATS[6].fetch_add(us, Ordering::Relaxed); + Ok(after) + })() + }; + after = match ran { + Ok(after) => after, + Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), + }; + let us = waiting.elapsed().as_micros() as u64; + RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(fetching.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(us, Ordering::Relaxed); + } + f.had.fetched( + ahead, + fetching.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)), + ); } + // Each piece: where its bytes are, and the send they ran behind. + let source = |from: From| match from { + From::Fetch(at) => (data + at as usize, after), + From::Slot(at, sent_as) => (at, sent_as), + }; let merging = std::time::Instant::now(); let _merging = crate::timeline::span("landing: merging fetched pieces"); let mut written = 0; @@ -4954,18 +5834,22 @@ impl Host { let working = std::time::Instant::now(); if let Some(check) = &check { for i in jobs[j].clone() { - // SAFETY: as below. - unsafe { check.look(i, data) }; + if let Some(k) = fetched_as[i] { + // SAFETY: as below. + unsafe { check.look(k, data) }; + } } } let mut notes = land::Notes::default(); - for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) { - let addressed: Vec<(usize, usize, usize)> = - run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect(); - // SAFETY: the mapping of the fetched bytes, `total` of - // them; the copy into it has run, and the next waits - // for this call. - put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed); + let job = &pieces[jobs[j].clone()]; + for run in job.chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0) && source(a.3).1 == source(b.3).1) { + let (_, merged_after) = source(run[0].3); + let addressed: Vec<(usize, usize, usize)> = run.iter().map(|(_, lo, hi, from)| (*lo, *hi, source(*from).0)).collect(); + // SAFETY: the mapping of the fetched bytes (`total` of + // them; the copy into it has run, and the next waits for + // this call), or of a plan's slots (its flight has run, + // and the plan is done with after this). + put.fetch_add(unsafe { run[0].0.land_card(&addressed, merged_after, &mut notes) }, Ordering::Relaxed); } notes.flush(); land::spent(land::stat::CARD_ALL, working); @@ -4974,32 +5858,27 @@ impl Host { written = put.into_inner(); } else { let mut title = Vec::new(); - for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() { - if let Some(check) = &check { + for (i, (shadow, lo, hi, from)) in pieces.iter().enumerate() { + if let (Some(check), Some(k)) = (&check, fetched_as[i]) { // SAFETY: as below. - unsafe { check.look(i, data) }; + unsafe { check.look(k, data) }; } - // SAFETY: the mapping of the fetched bytes, `total` of them; - // the copy into it has run. - let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; - let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + let (at, merged_after) = source(*from); + // SAFETY: as above: the fetched bytes or a plan's slot. + let gpu = unsafe { std::slice::from_raw_parts(at as *const u8, hi - lo) }; + let merged = shadow.card_merge_relay(*lo, gpu, merged_after, &mut title); shadow.walls_merged(gpu.len(), merged); written += merged as u64; } } land::spent(land::stat::CARD, merging); COPY_BACK[1].fetch_add(written, Ordering::Relaxed); - if let Some(f) = fetch.as_mut() { - if let Some(check) = &check { - check.done(&mut f.suspects); - } - f.had.fetched( - ahead, - pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)), - ); + if let (Some(f), Some(check)) = (fetch.as_mut(), &check) { + check.done(&mut f.suspects); } - // Sends up to `after` are of no use to any later merge. - crate::shadow::relay_fetched(after); + // Sends up to `after` are of no use to any later merge (with slots: + // up to `behind`, as above). + crate::shadow::relay_fetched(if prefetch::on() { after.min(behind) } else { after }); } /// [`relay`], on the thread that lands flights: `items` are the first @@ -5012,6 +5891,7 @@ impl Host { /// is complete before the title is told anything. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) { let landing = std::time::Instant::now(); + let trace_start = render_trace::active().then(now_us); let mut stage = crate::timeline::span("landing: what is to be looked through"); { let flights: Vec<&Flight> = items @@ -5033,6 +5913,9 @@ impl Host { last_notes(&runs) )); } + if let Some(flight) = flights.last() { + crate::descriptor::reclaim_dynamic(flight.fence); + } let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect(); // (Each byte once: the ranges are joined.) let mut back: Vec<Declared> = Vec::new(); @@ -5078,6 +5961,9 @@ impl Host { telling = match item { Late::Run(mut flight) => { last = flight.number; + if trace_start.is_some() { + render_trace::event("relay_readback", format_args!("submission={}\thost_fence={}\tlists={}", flight.number, flight.fence, flight.order.len())); + } for &i in &flight.order { read_backs(flight.lists[i].host()); } @@ -5099,18 +5985,28 @@ impl Host { } Late::Signal(fence, value) => { crate::fence::set(fence as crate::object::This, value); + if trace_start.is_some() { + render_trace::event("title_fence_published", format_args!("fence={fence:#x}\tvalue={value}")); + } crate::land::spent(crate::land::stat::TOLD, telling) } }; } if last > 0 { FINISHED.store(last, Ordering::Release); - bury(last); + // Driver releases can stall. Keep them off the thread that + // publishes completions and unblocks the in-flight list limit. + if !RELAY_HELPER_READY.load(Ordering::Acquire) { + bury(last); + } } stage.next("landing: the rest"); self.log_messages(); crate::land::spent(crate::land::stat::REST, telling); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + if let Some(start) = trace_start { + render_trace::event("relay_complete", format_args!("last_submission={last}\tstart_us={start}\tduration_us={}", landing.elapsed().as_micros())); + } { let mut line = line(); let Line { @@ -5140,8 +6036,8 @@ impl Host { } join_ranges(written, ranges); *settling = false; - // The landed lists are reset, and what queues hold looked at, - // by the helper thread (they take locks a waiter may hold). + // The helper resets the lists and releases retired resources + // after the waiters can make progress. *poke = true; } LINE_MOVED.notify_all(); @@ -5193,7 +6089,7 @@ impl Host { if !pieces.is_empty() { if work.fetched.as_ref().is_none_or(|f| f.2 < total) { let size = total.next_multiple_of(16 << 20); - work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + work.fetched = self.shared_buffer_cpu(size).map(|(buffer, data)| (buffer, data as usize, size)); } let Some((fetched, data, _)) = &work.fetched else { fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); @@ -5206,14 +6102,15 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + let timed = gpu_time::Ours::begin(list, "ours: pieces of the card's copies fetched"); for &(i, lo, hi, at) in &pieces { list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); } + timed.end(list); list.Close()?; - self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); - self.card_sent(); *submitted += 1; - self.queue.Signal(&self.fence, *submitted)?; + self.queue_send(&[Some(list.cast()?)], &[], Some((&self.fence, *submitted)))?; + self.card_sent(); self.fence.SetEventOnCompletion(*submitted, self.event)?; let was_working = working(false); WaitForSingleObject(self.event, INFINITE); @@ -5336,7 +6233,7 @@ impl Host { self.send_late(lists, order, parts); } - fn send_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) { + fn send_late(&self, mut lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) { let sent = { let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); self.submit(&runs, parts, true) @@ -5347,6 +6244,9 @@ impl Host { return; }; let after = std::time::Instant::now(); + for list in &mut lists { + list.tables_submitted(*submitted); + } let told = !sent.writes.is_empty(); let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); let most = { @@ -5376,6 +6276,8 @@ impl Host { }; LATE_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_MOVED.notify_one(); + let noted = std::time::Instant::now(); + AFTER_PARTS[1].fetch_add((noted - after).as_nanos() as u64, Ordering::Relaxed); if told && !late_writes() { self.settle(&mut submitted, WHY_WRITES); } else if sizes { @@ -5385,12 +6287,29 @@ impl Host { relay_wait(WHY_MOST, |line| line.lists < late_most()); } else if most { self.settle(&mut submitted, WHY_MOST); - } else { - LINE_MOVED.notify_one(); } drop(submitted); - let _landing = crate::timeline::span("landed lists reset and given back"); - land(); + let waited = std::time::Instant::now(); + AFTER_PARTS[2].fetch_add((waited - noted).as_nanos() as u64, Ordering::Relaxed); + // The landed lists are reset and given back by the helper thread + // ([`late_helper`], which does so when poked), not here: resetting + // some 230 host lists a frame was most of the submitting thread's + // time after each sending, which is the critical path. A backlog + // past [`LAND_INLINE`] is still done here so the pool of idle lists + // never runs dry behind a helper that fell behind. + let backlog = { + let mut line = line(); + line.poke = true; + line.landed.len() + }; + LINE_MOVED.notify_one(); + if backlog > bury_lag() as usize + LAND_INLINE { + let _landing = crate::timeline::span("landed lists reset and given back"); + let landing = std::time::Instant::now(); + land(); + AFTER_PARTS[3].fetch_add(landing.elapsed().as_nanos() as u64, Ordering::Relaxed); + LANDED_INLINE.fetch_add(1, Ordering::Relaxed); + } AFTER_SEND.fetch_add(after.elapsed().as_nanos() as u64, Ordering::Relaxed); } @@ -5528,6 +6447,9 @@ impl Host { )); } submitting(3, flights); + if let Some(completed) = completed_descriptor_fence() { + crate::descriptor::reclaim_dynamic(completed); + } let copying = std::time::Instant::now(); let mut seen = std::collections::HashSet::new(); let mut back: Vec<Declared> = Vec::new(); @@ -5639,6 +6561,7 @@ impl Host { /// other, as they would have. fn submit<'a>(&'a self, runs: &[&HostList], parts: &[usize], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { let called = std::time::Instant::now(); + let trace_start = render_trace::active().then(now_us); #[cfg(feature = "diagnostics")] crate::copystat::submission_begins(); // One submission at a time from preparation to copy-back: snapshots @@ -5662,9 +6585,10 @@ impl Host { // The round of the heaps' records asked for when the title submitted // these lists, if that is known (`crate::heap_marks`, 0: not). let heaps_mark = if late { crate::heap_marks::needed() } else { 0 }; + let needs_heaps = late && runs.iter().any(|l| l.heap_picked()); // Else with [`heap_sync_first`]: the heaps' records begun now, beside // the planning of steps done on the card and the look at flights. - let first_heaps = (late && heaps_mark == 0 && heap_sync_first()).then(crate::descriptor::begin_sync_heaps); + let first_heaps = (needs_heaps && heaps_mark == 0 && heap_sync_first()).then(crate::descriptor::begin_sync_heaps); let ahead = Split::begin(); SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); stage.next("submit: steps given to the card"); @@ -5699,22 +6623,26 @@ impl Host { // as the round began here saw them; the first is not waited for.) // With a mark (`crate::heap_marks`): that round, unless the // submission waited for flights, whose landings came after it. - let heaps_synced = match first_heaps { - Some(first) if !waited_for_flights => { - HEAP_SYNC_FIRST[0].fetch_add(1, Ordering::Relaxed); - first - } - first => { - if let Some(first) = first { - HEAP_SYNC_FIRST[1].fetch_add(1, Ordering::Relaxed); - std::mem::forget(first); - } - if heaps_mark != 0 && !waited_for_flights { - crate::descriptor::begin_sync_heaps_after(heaps_mark) - } else { - crate::descriptor::begin_sync_heaps() + let heaps_synced = if !needs_heaps { + None + } else { + Some(match first_heaps { + Some(first) if !waited_for_flights => { + HEAP_SYNC_FIRST[0].fetch_add(1, Ordering::Relaxed); + first + } + first => { + if let Some(first) = first { + HEAP_SYNC_FIRST[1].fetch_add(1, Ordering::Relaxed); + std::mem::forget(first); + } + if heaps_mark != 0 && !waited_for_flights { + crate::descriptor::begin_sync_heaps_after(heaps_mark) + } else { + crate::descriptor::begin_sync_heaps() + } } - } + }) }; // That list runs first, and is one of the submission's from here on. let with: Vec<&HostList>; @@ -5744,8 +6672,16 @@ impl Host { SWEPT.store(now_ms(), Ordering::Relaxed); } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { // With the present sent ahead nothing else brings a moment - // with nothing in the air: one is made for the sweep. - self.settle(&mut submitted, WHY_SYNC); + // with nothing in the air. What the sweep lets go of goes + // through [`retire`], which holds it until every submission + // started so far has finished (the submission numbers are the + // fence values), and what only a list names has a count above + // one while the list is in a flight; so no drain is needed + // (`VICTORY_SWEEP_SETTLE=1`, or the up-check, which needs a + // card at rest: as before, 10 to 30 ms every 1.5 s). + if sweep_settles() || upcheck::on() { + self.settle(&mut submitted, WHY_SYNC); + } if upcheck::on() { upcheck::at_rest(self); } @@ -5755,6 +6691,9 @@ impl Host { let behind = late && flying(); stage.next("submit: gathering what to ask about"); let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; + if let Some(start) = trace_start { + render_trace::event("submission_preparing", format_args!("submission={this_submission}\tstart_us={start}\tlists={}\tparts={}\tasynchronous={late}", runs.len(), parts.len())); + } // The ranges shaders write are counted for it (with the relay). crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); @@ -5767,15 +6706,19 @@ impl Host { // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::reused(); - let split = Split::begin(); + let split = Split::begin().trace(trace_start.map(|_| this_submission)); // The time a settle of flights takes inside this preparing: the // wait for the card and the copy-back have their own places on the // frame line (run 92 showed them twice, "preparing" 250 ms for 135). let mut settled = std::time::Duration::ZERO; // One write-watch asking for everything the submission refreshes // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. - if crate::watch::once() { - batch.copy_spans(runs); + let once = crate::watch::once(); + let front = refresh_front(); + if once || front { + batch.copy_spans(runs, front.then_some(parts.as_slice())); + } + if once { let Batch { spans, ranges, .. } = &mut batch; ranges.clear(); ranges.extend(spans.iter().filter(|s| s.0.asked_ahead()).map(|s| (s.1, s.2))); @@ -5809,8 +6752,8 @@ impl Host { // What flights in the air may write. let air = line().written.clone(); stage.next("submit: refreshes ahead of writes"); - if refresh_front() { - batch.refresh_front(runs, &parts); + if front { + batch.refresh_front(); } else if ahead_of_writes() { batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i))); } @@ -5896,6 +6839,9 @@ impl Host { } #[cfg(feature = "diagnostics")] let sending = crate::timeline::ticks(); + if let Some(start) = trace_start { + render_trace::event("submission_ready", format_args!("submission={this_submission}\tstart_us={start}\tprepare_us={}\tsettled_us={}\tlists={}\tnext_host_fence={}", called.elapsed().as_micros(), settled.as_micros(), lists.len(), *submitted + 1)); + } if late { *submitted += 1; #[cfg(feature = "diagnostics")] @@ -5904,16 +6850,10 @@ impl Host { lists.push(Some(behind)); firsts.iter_mut().for_each(|first| *first += 1); } - let cuts: Vec<usize> = parts.iter().filter_map(|&n| firsts.get(n).copied()).collect(); - // SAFETY: closed lists; the fence is ours. - let signalled = unsafe { - let mut from = 0; - for to in cuts.into_iter().chain([lists.len()]) { - self.queue.ExecuteCommandLists(&lists[from..to]); - from = to; - } - self.queue.Signal(&self.fence, *submitted) - }; + // All lists of this submission are already ordered on the host queue + // and refreshed ahead of them; submit them in one ExecuteCommandLists call. + let _ = &parts; + let signalled = self.queue_send(&lists, &[], Some((&self.fence, *submitted))); awake::sent(&self.device); #[cfg(feature = "diagnostics")] crate::timeline::sent(sending, *submitted, stamp, two_queues::title_kind() == Some(two_queues::COMPUTE)); @@ -5923,6 +6863,8 @@ impl Host { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } split.part(5); + // (Counted with the time after the sending: it was on no line before.) + let tail = std::time::Instant::now(); let back = crate::picked::with(declared, &picked.written); let mut texture_back_ranges = Vec::new(); for list in runs { @@ -5943,6 +6885,9 @@ impl Host { }; batch.give_back(); working(was_working); + let tail = tail.elapsed().as_nanos() as u64; + AFTER_SEND.fetch_add(tail, Ordering::Relaxed); + AFTER_PARTS[0].fetch_add(tail, Ordering::Relaxed); return Some((submitted, sent)); } // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). @@ -5964,12 +6909,9 @@ impl Host { let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { - self.queue.ExecuteCommandLists(group); + let sent = self.queue_send(group, &[], Some((&self.fence, *submitted))); self.card_sent(); - let waited = self - .queue - .Signal(&self.fence, *submitted) - .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + let waited = sent.and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); #[cfg(feature = "diagnostics")] crate::timeline::sent(sending, *submitted, stamp, two_queues::title_kind() == Some(two_queues::COMPUTE)); match waited { @@ -6201,7 +7143,11 @@ impl Host { }); #[cfg(not(feature = "diagnostics"))] #[allow(clippy::type_complexity)] - let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None; + let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = + list_number(&named).and_then(|n| { + let all = RELEASE_LISTS.lock().unwrap_or_else(|e| e.into_inner()); + all.get(&n).map(|pipelines| (None, pipelines.upgrade())) + }); #[cfg(feature = "diagnostics")] let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone())); let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone())); @@ -6386,6 +7332,77 @@ impl Host { } impl HostList { + /// The draws and dispatches recorded next: a new GPU pass where the + /// work's key changes ([`gpu_time`]): draws keep one until the render + /// targets change ([`Self::gpu_pass_break`]), each compute pipeline's + /// run of dispatches is one. `name` is asked only for a new pass. + pub(crate) fn gpu_pass(&self, compute: bool, pipeline: usize, command: render_trace::Command, name: impl FnOnce() -> String) { + self.gpu_time.work(); + let (key, kind) = if compute { (pipeline as u64 | 1, gpu_time::COMPUTE) } else { (2, gpu_time::DRAW) }; + self.gpu_time.pass(&self.list, key, kind, command, name); + } + + /// The render targets changed: the next draw begins a GPU pass. + pub(crate) fn gpu_pass_break(&self) { + // (counted as work: what setting targets records stands between two + // waits for shader writes) + self.gpu_time.work(); + self.gpu_time.break_pass(); + self.trace_gpu_pass("render targets changed", [0; 5]); + } + + /// A pass of ours in this list (`n` tells them apart). + fn gpu_pass_ours(&self, n: u64, name: &'static str) { + self.gpu_time.work(); + self.gpu_time.pass(&self.list, u64::MAX - n, gpu_time::OURS, render_trace::Command("host_pass", [0; 5]), || name.to_owned()); + } + + pub(crate) fn trace_gpu_pass(&self, name: &'static str, args: [i64; 5]) { + if render_trace::active() { + self.gpu_time.pass(&self.list, u64::MAX, gpu_time::OURS, render_trace::Command("host_pass", args), || name.to_owned()); + } + } + + /// A step that is not a draw or dispatch is recorded next (the title's + /// copies, clears, resolves, barriers): counted, and timed on the card as + /// a pass of its kind if the list has drawn nothing yet. Anything but a + /// barrier is work ([`Self::gpu_work`]). + pub(crate) fn gpu_step(&self, kind: gpu_time::Step, bytes: u64) { + if !matches!(kind, gpu_time::Step::Transitions | gpu_time::Step::ShaderWrites) { + self.gpu_time.work(); + } + if matches!(kind, gpu_time::Step::BufferCopies | gpu_time::Step::TextureCopies | gpu_time::Step::MemoryCopies) { + self.gpu_time.uav_work(); + } + gpu_time::count_step(kind, bytes); + self.gpu_time.step(&self.list, kind, bytes); + } + + /// Work was recorded into the list (for list start timing). + pub(crate) fn gpu_work(&self) { + self.gpu_time.work(); + } + + /// Shader or copy UAV-producing work was recorded into the list (for [`Self::wait_for_writes`]). + pub(crate) fn gpu_uav_work(&self) { + self.gpu_time.uav_work(); + } + + /// Whether a wait for every shader write (a UAV barrier on no resource) + /// is to be recorded now: not where no shader/copy UAV work ran since + /// the last one in this list (`VICTORY_MERGE_BARRIERS=0`: always). + pub(crate) fn wait_for_writes(&self) -> bool { + self.gpu_time.wait_for_uav_writes() + } + + pub(crate) fn water_dispatch(&self, pipeline: Option<&crate::pipeline::host::HostPipeline>, dispatch: impl FnOnce()) { + let index = pipeline.and_then(water_timing::kind).and_then(|kind| self.water_timing.begin(&self.list, kind)); + dispatch(); + if let Some(index) = index { + self.water_timing.end(&self.list, index); + } + } + /// The timestamp heap and its read-back buffer (diagnostics, timing on). #[cfg(feature = "diagnostics")] fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> { @@ -6466,15 +7483,29 @@ impl HostList { let _closing = crate::timeline::span("closing a host list"); self.left_open[0].store(0, Ordering::Release); self.flush_indirect(); - self.twins_to_depth(); - self.textures_back(); + if self.twins.lock().unwrap_or_else(|e| e.into_inner()).values().any(|u| u.behind[0] == Some(true) || u.late) { + self.gpu_pass_ours(1, "ours: depth twins at the list's end"); + self.twins_to_depth(); + } + if !self.deferred().back_wanted.is_empty() { + self.gpu_pass_ours(2, "ours: textures copied back at the list's end"); + self.textures_back(); + } let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); - if let Some((scratch, _)) = scratch { + if let Some((scratch, _)) = scratch + && self.deferred().indirect_readable == scratch.as_raw() as usize + { + self.gpu_pass_ours(3, "ours: indirect argument clamps"); self.indirect_common(&scratch); } - self.batches_common(); + if self.batch_args.lock().unwrap_or_else(|e| e.into_inner()).1 > 0 { + self.gpu_pass_ours(4, "ours: indirect argument clamps in batches"); + self.batches_common(); + } self.card_budget_out(); self.take_coming(); + self.water_timing.resolve(&self.list); + self.gpu_time.end(&self.list); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -6578,8 +7609,24 @@ impl HostList { self._alive.used(); self.upscale.store(0, Ordering::Relaxed); self.hudless.store(0, Ordering::Relaxed); + self.heap_picked.store(false, Ordering::Relaxed); + self.water_timing.reset(); *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None; - *self.deferred() = Deferred::default(); + { + // Every submission of the list has run: its pooled upload buffers + // and its read-back buffers (read when it landed) go back to + // [`BUFFER_POOL`] for the next lists. + let mut deferred = self.deferred(); + let uploads = std::mem::take(&mut deferred.pooled_uploads); + let mut backs: Vec<ID3D12Resource> = + if buffer_pool_on() { deferred.backs.drain(..).map(|(b, _, _)| b).collect() } else { Vec::new() }; + if buffer_pool_on() { + backs.extend(deferred.texture_backs.drain(..).filter_map(|mut b| b.take_buffer())); + } + deferred.clear(); + drop(deferred); + give_pooled(uploads, backs); + } self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -6610,6 +7657,7 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } + self.gpu_time.start(&self.list); } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); @@ -6622,6 +7670,14 @@ impl HostList { self.epoch.store(next_epoch(), Ordering::Relaxed); } + pub(crate) fn note_heap_picked(&self) { + self.heap_picked.store(true, Ordering::Relaxed); + } + + pub(crate) fn heap_picked(&self) -> bool { + self.heap_picked.load(Ordering::Relaxed) + } + /// See [`HostList::changed_something`]. pub(crate) fn epoch(&self) -> u64 { self.epoch.load(Ordering::Relaxed) @@ -6658,6 +7714,12 @@ impl HostList { && let Some(held) = held.take() { self.holding.store(false, Ordering::Relaxed); + // (an indirect execution: shader work) + if render_trace::active() { + self.gpu_pass(run.kind == 2, run.pipeline, render_trace::Command("execute_indirect_merged", [run.kind.into(), run.records.into(), run.at as i64, 0, run.step.into()]), || format!("indirect pipeline {:#x}", run.pipeline)); + } else { + self.gpu_time.work(); + } held.record(&self.list, run); } } @@ -7056,6 +8118,7 @@ impl HostList { let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; + let mut timed = gpu_time::Ours::begin(list, "ours: a list's state prelude (states, depth twins)"); if !aliasing.is_empty() { list.ResourceBarrier(&aliasing); } @@ -7065,12 +8128,16 @@ impl HostList { for (depth, twin, colour) in &syncs { record_twin_copy(list, &depth.texture, twin, *colour); } + if !uploads.is_empty() { + timed.pass(list, "ours: texture uploads in a list's prelude"); + } for (upload, _) in uploads { upload.record(list); } if !barriers.is_empty() { list.ResourceBarrier(&barriers); } + timed.end(list); list.Close() }) }; @@ -7185,6 +8252,9 @@ impl HostList { /// Copies `len` bytes from `src` to `dst` when the list is submitted. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { + // `card_steps` may do it on the card, landing after the flight: + // constants there are not read in place meanwhile (`crate::port`). + crate::port::copy_bound(dst as usize, len); let mut deferred = self.deferred(); COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed); // A copy that goes on where the one recorded just before it ended, @@ -7218,6 +8288,10 @@ impl HostList { /// memory at `src` as of the list's submission: one fill for every ask /// until the list next writes title memory. pub(crate) fn fill_scratch(&self, src: *const u8, len: u64) -> Option<u64> { + // Behind a copy at its place: read on the card, not waited for. + if let Some((_, gpu)) = self.placed_constants(src as usize, len as usize) { + return Some(gpu); + } let key = (src as usize, len as usize); let known = self.deferred().filled.get(&key).copied(); if known.is_some() { @@ -7232,6 +8306,10 @@ impl HostList { /// As [`HostList::defer_fill`], for upload memory that only `slot` (a /// title heap's address, and the slot) shows. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { + // Behind a copy at its place: read on the card, not waited for. + if self.place_constants_slot(src as usize, len, slot) { + return; + } self.deferred() .copies .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1)))); @@ -7285,6 +8363,8 @@ impl HostList { /// to title memory at `dst`, pitched `pitch`. The buffer lives until /// the list is reset. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) { + // The card's bytes go there: not constants read in place (`crate::port`). + crate::port::gpu_bound(dst as usize, rows.saturating_sub(1).saturating_mul(pitch).saturating_add(row)); self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch])); } @@ -7293,15 +8373,35 @@ impl HostList { self.deferred().writes.push((dst as usize, what, bytes)); } - /// A mapped upload buffer of `size` bytes, alive until the list is - /// reset. - /// - /// shortcut: one buffer per copy; pool them once uploads are frequent. + /// A mapped upload buffer of `size` bytes or more, alive until the list + /// is reset: one of [`BUFFER_POOL`]'s, given back then. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { // With [`card_steps`] the card may be the one that fills it. - let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? }; - name(&buffer, || format!("list upload {size:#x}")); - self.deferred().hold_upload(buffer.clone(), size); + if card_steps::stage() > 1 { + let (buffer, data) = host.shared_buffer_cpu(size)?; + name(&buffer, || format!("list upload {size:#x}")); + self.deferred().hold_upload(buffer.clone(), size); + return Some((buffer, data)); + } + let Some((i, class)) = pool_class(size) else { + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || format!("list upload {size:#x}")); + self.deferred().hold_upload(buffer.clone(), size); + return Some((buffer, data)); + }; + // One kept from a list that has run, or a new one of the class. + let (buffer, data) = match take_pooled(i, class, true) { + Some(Pooled(buffer, data)) => (buffer, data as *mut u8), + None => { + POOL_STATS[1].fetch_add(1, Ordering::Relaxed); + let (buffer, data) = host.upload_buffer(class)?; + name(&buffer, || format!("list upload (pooled) {class:#x}")); + (buffer, data) + } + }; + let mut deferred = self.deferred(); + deferred.hold_upload(buffer.clone(), class); + deferred.pooled_uploads.push(Pooled(buffer.clone(), data as usize)); Some((buffer, data)) } @@ -7368,7 +8468,7 @@ impl HostList { let (buffer, data) = self .budget .get_or_init(|| { - let (b, d) = host()?.shared_buffer(256)?; + let (b, d) = host()?.shared_buffer_cpu(256)?; Some((b, d as usize)) }) .as_ref()?; @@ -7412,7 +8512,7 @@ impl HostList { return None; } self.list.cast::<ID3D12GraphicsCommandList2>().ok()?; - let buffer = host()?.uav_buffer(256)?; + let buffer = host()?.uav_buffer_for(256, Kind::UavIndirectBudget)?; name(&buffer, || "indirect budget".to_owned()); Some(buffer) } @@ -7493,7 +8593,7 @@ impl HostList { .saturating_mul(2) .max(needed) .next_multiple_of(64 << 10); - let buffer = host()?.uav_buffer(alloc)?; + let buffer = host()?.uav_buffer_for(alloc, Kind::UavIndirectScratch)?; name(&buffer, || format!("indirect arguments {alloc:#x}")); let old = slot.replace((buffer.clone(), alloc)); drop(slot); @@ -7515,7 +8615,7 @@ impl HostList { let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES); if buffer == args.0.len() { let size = u64::from(BATCHES * JOBS * SLOT); - let made = host()?.uav_buffer(size)?; + let made = host()?.uav_buffer_for(size, Kind::UavIndirectScratch)?; name(&made, || format!("indirect batches {size:#x}")); args.0.push(made); } @@ -7857,10 +8957,17 @@ impl HostList { } } -/// The numbers of [`HostList::epoch`]. +/// The numbers of [`HostList::epoch`]: unique, never 0. Only compared for +/// equality, so each thread takes them from a block of its own +/// (`crate::sharded::Numbers`): a list's epoch moves at state changes of +/// the draws every translating thread records, and one count for all of +/// them was a line the threads took from each other at each. fn next_epoch() -> u64 { - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - NEXT.fetch_add(1, Ordering::Relaxed) + static NEXT: crate::sharded::Numbers = crate::sharded::Numbers::new(1); + thread_local! { + static OWN: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; + } + OWN.try_with(|own| NEXT.next(own)).unwrap_or_else(|_| NEXT.one()) } /// A table by a copy's address. @@ -7918,6 +9025,14 @@ static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic:: /// reset and given back. static AFTER_SEND: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// [`AFTER_SEND`] by part, nanoseconds since the last frame-rate line: the +/// submission's tail on the submitting thread (what its lists' shaders and +/// read-backs write, noted for the flight; its batch given back), the +/// flight noted in the line, the waits for the card that followed (a settle +/// or a wait for fewer lists in the air: the card's time showing through, +/// not work), and landed lists reset here behind a helper that fell behind. +static AFTER_PARTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + /// Whether a submission sent ahead begins the round of the heaps' records /// (`crate::descriptor::begin_sync_heaps`) as soon as it holds the /// submission lock, before the steps done on the card are planned and @@ -7944,11 +9059,16 @@ fn heap_sync_first() -> bool { static HEAP_SYNC_FIRST: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// Counts into [`SPLIT`]. -struct Split(std::cell::Cell<std::time::Instant>); +struct Split(std::cell::Cell<std::time::Instant>, Option<u64>); impl Split { fn begin() -> Split { - Split(std::cell::Cell::new(std::time::Instant::now())) + Split(std::cell::Cell::new(std::time::Instant::now()), None) + } + + fn trace(mut self, submission: Option<u64>) -> Self { + self.1 = submission; + self } /// Nanoseconds since the last part. @@ -7959,7 +9079,21 @@ impl Split { /// What came since the last part was part `i`. fn part(&self, i: usize) { let now = std::time::Instant::now(); - SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed); + let elapsed = now - self.0.replace(now); + SPLIT[i].fetch_add(elapsed.as_nanos() as u64, Ordering::Relaxed); + if let Some(submission) = self.1 { + let phase = match i { + 0 => "write_watch", + 1 => "writes_under_flights", + 2 => "refresh_and_deferred_steps", + 3 => "snapshots", + 4 => "card_copies", + 5 => "queue_send", + 15 => "heap_records", + _ => "other", + }; + render_trace::event("submission_stage", format_args!("submission={submission}\tphase={phase}\tduration_us={}", elapsed.as_micros())); + } } } @@ -7971,6 +9105,8 @@ fn submit_split_line(frames: f64) { let ms: [f64; 16] = std::array::from_fn(|i| SPLIT[i].swap(0, Ordering::Relaxed) as f64 / 1e6 / frames); let f: [f64; 4] = std::array::from_fn(|i| FLUSHES[i].swap(0, Ordering::Relaxed) as f64 / frames); let after = AFTER_SEND.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; + let parts: [f64; 4] = std::array::from_fn(|i| AFTER_PARTS[i].swap(0, Ordering::Relaxed) as f64 / 1e6 / frames); + let inline = LANDED_INLINE.swap(0, Ordering::Relaxed) as f64 / frames; let all: f64 = [0, 1, 2, 3, 4, 5, 11, 12, 13, 14, 15].iter().map(|&i| ms[i]).sum(); if all + after <= 0.0 { return; @@ -7983,7 +9119,7 @@ fn submit_split_line(frames: f64) { in the card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the \ submission lock, {:.1} planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is \ swept; at the end {:.1} waiting for the heaps' records; after the sending {after:.1} (the flight noted, landed lists \ - reset and given back)", + reset and given back: {:.1} the submission's tail, {:.1} the flight noted, {:.1} waiting for the card (settles, fewer lists in the air), {:.1} lists reset here in {:.1} times behind a helper that fell behind)", ms[0], ms[8], ms[1], @@ -8005,6 +9141,29 @@ fn submit_split_line(frames: f64) { ms[13], ms[14], ms[15], + parts[0], + parts[1], + parts[2], + parts[3], + inline, + ); + let pool: [f64; 4] = std::array::from_fn(|i| POOL_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + let kept_mb = BUFFER_POOL.lock().unwrap_or_else(|e| e.into_inner()).bytes as f64 / (1 << 20) as f64; + let [buried, burying] = [0, 1].map(|i| BURIED[i].swap(0, Ordering::Relaxed) as f64 / frames); + let [reset, resetting] = + [0, 1].map(|i| crate::list::RECYCLED[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "host lists' buffers and resets per frame: upload and read-back buffers {:.1} taken from the pool, {:.1} made for it, \ + {:.1} given back, {:.1} let go past its {:.0} MB (VICTORY_BUFFER_POOL; {kept_mb:.0} MB kept); lists reset {reset:.1} \ + in {:.2} ms (VICTORY_RESET_WIDE); retired objects {buried:.0} dropped on a thread of their own in {:.2} ms \ + (VICTORY_BURY_THREAD)", + pool[0], + pool[1], + pool[2], + pool[3], + buffer_pool_most() as f64 / (1 << 20) as f64, + resetting / 1e6, + burying / 1e6, ); let [first, again] = [0, 1].map(|i| HEAP_SYNC_FIRST[i].swap(0, Ordering::Relaxed) as f64 / frames); if first + again > 0.0 { @@ -8146,10 +9305,14 @@ struct Batch { /// copy (by address) is in it. spans: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>, spans_at: ByCopy<usize>, - /// Room for the submission's one asking's ranges, and for - /// [`Batch::refresh_front`]'s walk over the steps. + /// Room for the submission's one asking's ranges and for the ranges + /// that can be refreshed before running the deferred steps. ranges: Vec<(usize, usize)>, - touches: Vec<Touch>, + front_spans: FrontSpans, + /// The submission's one asking's ranges, copied once per asking: every + /// refresh step asks whether they cover it ([`crate::watch::kept_covers_cached`]), + /// some 13,000 a frame, each of which took the journal's lock. + kept: crate::watch::KeptView, } thread_local! { @@ -8192,50 +9355,59 @@ fn refresh_front() -> bool { /// Per copy what is refreshed in front of a submission's steps, as /// [`written_spans`]'s but of all copies, up to the copy's first write by -/// shaders in each part of the submission (`Touch::Part`: another begins). +/// shaders in each part of the submission. /// What a part refreshes of a copy it has given to its shaders stays where it /// stands: around what they write. What a later part refreshes is the /// title's bytes of before either. +#[derive(Default)] +struct FrontSpans { + at: ByCopy<usize>, + // (Copy, from, to, last part that gave the copy to shaders). + spans: Vec<(usize, usize, usize, Option<usize>)>, + last: usize, +} + +impl FrontSpans { + fn span(&mut self, copy: usize) -> &mut (usize, usize, usize, Option<usize>) { + if !self.spans.get(self.last).is_some_and(|span| span.0 == copy) { + self.last = *self.at.entry(copy).or_insert_with(|| { + self.spans.push((copy, usize::MAX, 0, None)); + self.spans.len() - 1 + }); + } + &mut self.spans[self.last] + } + + fn refresh(&mut self, copy: usize, from: usize, to: usize, part: usize) { + let span = self.span(copy); + if span.3 != Some(part) { + (span.1, span.2) = (span.1.min(from), span.2.max(to)); + } + } + + fn write(&mut self, copy: usize, part: usize) { + self.span(copy).3 = Some(part); + } + + fn take(&mut self) -> impl Iterator<Item = (usize, usize, usize)> + '_ { + self.at.clear(); + self.spans.drain(..).filter_map(|(key, from, to, _)| (from < to).then_some((key, from, to))) + } +} + +#[cfg(test)] fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> { - let mut at: ByCopy<usize> = ByCopy::default(); - // (Copy, from, to), in the order they come, and the part that gave it to - // shaders last. - let mut spans: Vec<(usize, usize, usize)> = Vec::new(); - let mut given: Vec<u32> = Vec::new(); - let (mut part, mut last) = (1, usize::MAX); + let mut spans = FrontSpans::default(); + let mut part = 0; for step in steps { match step { - Touch::Refresh(copy, from, to) => { - // (Most come several times on end.) - let i = if spans.get(last).is_some_and(|s| s.0 == copy) { - last - } else { - *at.entry(copy).or_insert_with(|| { - spans.push((copy, usize::MAX, 0)); - given.push(0); - spans.len() - 1 - }) - }; - last = i; - if given[i] != part { - let span = &mut spans[i]; - (span.1, span.2) = (span.1.min(from), span.2.max(to)); - } - } - Touch::Write(copy) => { - let i = *at.entry(copy).or_insert_with(|| { - spans.push((copy, usize::MAX, 0)); - given.push(0); - spans.len() - 1 - }); - given[i] = part; - } + Touch::Refresh(copy, from, to) => spans.refresh(copy, from, to, part), + Touch::Write(copy) => spans.write(copy, part), Touch::Part => part += 1, Touch::Title | Touch::Nothing => {} } } - spans.retain(|s| s.1 < s.2); - spans + spans.take().collect() } /// What a step is to the copies' refreshes, for [`written_spans`]. @@ -8248,6 +9420,7 @@ enum Touch { Title, Nothing, /// Another part of the submission begins. + #[cfg(test)] Part, } @@ -8271,7 +9444,9 @@ fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize } } Touch::Title => break, - Touch::Nothing | Touch::Part => {} + Touch::Nothing => {} + #[cfg(test)] + Touch::Part => {} } } spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect() @@ -8397,7 +9572,6 @@ impl Batch { self.spans.clear(); self.spans_at.clear(); self.ranges.clear(); - self.touches.clear(); SPARE_BATCH.set(Some(self)); } @@ -8405,20 +9579,38 @@ impl Batch { /// [`Batch::spans`]: the submission's one asking asks about those /// ([`crate::watch::ask_once`]), and behind flights those of copies /// shaders may be writing are looked at ([`Batch::stale_under_flights`]). - /// One walk over the steps for both, where there were two, each with a - /// table of its own. - fn copy_spans(&mut self, runs: &[&HostList]) { + /// With `front` also find which ranges can be refreshed before running + /// the deferred steps and which textures they will need. + fn copy_spans(&mut self, runs: &[&HostList], front: Option<&[usize]>) { self.spans.clear(); self.spans_at.clear(); - // (Most come several times on end.) + let textures = front.is_some() && wide_textures(); + let mut part = 0; let mut last = (0, 0); - for list in runs { + for (n, list) in runs.iter().enumerate() { + if front.is_some_and(|parts| parts.contains(&n)) { + part += 1; + } for step in &list.deferred().copies { - let Step::Refresh(shadow, address, len) = step else { - continue; + let (shadow, address, len) = match step { + Step::Refresh(shadow, address, len) => (shadow, address, len), + Step::GpuWrite(shadow, ..) if front.is_some() => { + self.front_spans.write(std::sync::Arc::as_ptr(shadow) as usize, part); + continue; + } + Step::Texture(staging) if textures => { + if self.texture_due(staging) { + self.due.push(staging.clone()); + } + continue; + } + _ => continue, }; let (from, to) = (*address, *address + *len); let key = std::sync::Arc::as_ptr(shadow) as usize; + if front.is_some() { + self.front_spans.refresh(key, from, to, part); + } let at = if last.0 == key && key != 0 { last.1 } else { @@ -8451,6 +9643,14 @@ impl Batch { if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) { return; } + if crate::watch::light() { + let kept = &mut self.kept; + if shadow.fast_nothing_new_known(address, len, |from, to| crate::watch::kept_covers_cached(kept, from, to)) { + FLUSHES[1].fetch_add(1, Ordering::Relaxed); + FLUSHES[2].fetch_add(1, Ordering::Relaxed); + return; + } + } match self.index.get(&key) { Some(&at) => { let r = &mut self.refreshes[at]; @@ -8515,38 +9715,10 @@ impl Batch { self.textures.clear(); } - /// Before the steps of `runs` ([`refresh_front`]), a new part of the - /// submission beginning at each of `parts`. - fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) { - // The copies refreshed, by address: as the submission's one asking - // found them, or found here. - if self.spans.is_empty() { - self.copy_spans(runs); - } - let mut due = Vec::new(); - self.touches.clear(); - for (n, list) in runs.iter().enumerate() { - if parts.contains(&n) { - self.touches.push(Touch::Part); - } - for step in &list.deferred().copies { - match step { - Step::Refresh(shadow, at, len) => { - self.touches.push(Touch::Refresh(std::sync::Arc::as_ptr(shadow) as usize, *at, *at + *len)); - } - Step::GpuWrite(shadow, ..) => self.touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)), - Step::Texture(staging) if wide_textures() => { - if self.texture_due(staging) { - due.push(staging.clone()); - } - } - _ => {} - } - } - } - let found = front_spans(self.touches.drain(..)); - let spans: Vec<_> = found - .into_iter() + /// Bring the planned front spans and textures up to date in parallel. + fn refresh_front(&mut self) { + let due = std::mem::take(&mut self.due); + let spans: Vec<_> = self.front_spans.take() .filter_map(|(key, from, to)| Some((self.spans.get(*self.spans_at.get(&key)?)?.0.clone(), from, to))) .collect(); self.front = true; @@ -8558,43 +9730,70 @@ impl Batch { let _flush = crate::timeline::span("refreshes of copies"); let started = std::time::Instant::now(); let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)); - // Those known to copy nothing are said so here, unless they are very - // many: then beside the others. + // With a standing write-watch answer there is no second kernel ask + // to plan. Check the known-clean spans in the same worker jobs that + // perform the updates, instead of walking them on the submitter first. const FEW: usize = 256; let mut spans = spans; + let light = crate::watch::light(); + let worker_kept = if light && spans.len() > FEW { self.kept.snapshot() } else { None }; + if light && worker_kept.is_none() { + let all = spans.len(); + let kept = &mut self.kept; + spans.retain(|(shadow, from, to)| { + !shadow.fast_nothing_new_known(*from, *to - *from, |a, b| crate::watch::kept_covers_cached(kept, a, b)) + }); + FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); + } let many = spans.len() > FEW; if !many { let all = spans.len(); spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); } - let ahead = spans.len() > 1; + let ahead = spans.len() > 1 && !crate::watch::kept(); if ahead { let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); crate::watch::ask_ahead(&ranges); } FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); - crate::shadow::wide_each(spans.len() + due.len(), move |i| { + // Claim short groups of buffer checks together. In the large + // flushes most checks do no copying, so claiming and counting + // them one at a time makes the workers contend on two counters. + const GROUP: usize = 8; + let group = if many { GROUP } else { 1 }; + crate::shadow::wide_each(spans.len().div_ceil(group) + due.len(), move |i| { // The textures first: they are the longer pieces. let Some(i) = i.checked_sub(due.len()) else { due[i].refresh(); return; }; - let (shadow, from, to) = &spans[i]; - if many && shadow.nothing_new(*from, *to - *from) { - FLUSHES[2].fetch_add(1, Ordering::Relaxed); - return; + let from_index = i * group; + let mut clean = 0; + for (shadow, from, to) in &spans[from_index..(from_index + group).min(spans.len())] { + let len = *to - *from; + let known = worker_kept.as_ref().is_some_and(|kept| { + shadow.fast_nothing_new_known(*from, len, |a, b| kept.covers_current(a, b)) + }); + if known || (many && shadow.nothing_new(*from, len)) { + clean += 1; + } else { + Self::update(shadow, *from, *to); + } + } + if clean != 0 { + FLUSHES[2].fetch_add(clean, Ordering::Relaxed); } - Self::update(shadow, *from, *to); }); if ahead { crate::watch::ask_ahead_done(); } // The time counted is the time it took, not the threads' sum. let took = started.elapsed().as_micros() as u64; - let summed = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)).iter().zip(before).map(|(now, was)| now.saturating_sub(was)).collect::<Vec<_>>(); - PREPARING[2].fetch_sub(summed[1], Ordering::Relaxed); - PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed); + let copies = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before[0]); + let textures = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before[1]); + PREPARING[2].fetch_sub(textures, Ordering::Relaxed); + PREPARING[0].fetch_sub(copies, Ordering::Relaxed); PREPARING[0].fetch_add(took, Ordering::Relaxed); SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); } @@ -8705,16 +9904,22 @@ impl Batch { // once a frame: on the threads, below.) const FEW: usize = 256; let light = crate::watch::light(); - if light && self.refreshes.len() <= FEW { + if light { let started = std::time::Instant::now(); let all = self.refreshes.len(); - self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + let kept = &mut self.kept; + self.refreshes.retain(|(shadow, from, to)| { + !shadow.fast_nothing_new_known(*from, *to - *from, |a, b| crate::watch::kept_covers_cached(kept, a, b)) + }); + if self.refreshes.len() <= FEW { + self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + } PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); } // One write-watch asking for the copies that lie close together, - // not one per copy. - let ahead = self.refreshes.len() > 1; + // not one per copy (`ask_once` already covers the submission when `kept`). + let ahead = self.refreshes.len() > 1 && !crate::watch::kept(); if ahead { let started = std::time::Instant::now(); let ranges: Vec<(usize, usize)> = self @@ -8734,15 +9939,26 @@ impl Batch { let before = PREPARING[0].load(Ordering::Relaxed); FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed); if light { - // A number to a free thread, not a job to each copy. + // A number to a free thread, not a job to each copy; in a + // big flush (most of whose copies turn out as they were) a + // short group of them, as `refresh_front` claims them: one + // claim of the shared counter, one count of the clean ones. + const GROUP: usize = 8; let refreshes = std::mem::take(&mut self.refreshes); - crate::shadow::wide_each(refreshes.len(), move |i| { - let (shadow, from, to) = &refreshes[i]; - if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { - FLUSHES[2].fetch_add(1, Ordering::Relaxed); - return; + let many = refreshes.len() > FEW; + let group = if many { GROUP } else { 1 }; + crate::shadow::wide_each(refreshes.len().div_ceil(group), move |i| { + let mut clean = 0; + for (shadow, from, to) in &refreshes[i * group..((i + 1) * group).min(refreshes.len())] { + if many && shadow.nothing_new(*from, *to - *from) { + clean += 1; + continue; + } + Self::update(shadow, *from, *to); + } + if clean != 0 { + FLUSHES[2].fetch_add(clean, Ordering::Relaxed); } - Self::update(shadow, *from, *to); }); } else { let jobs: Vec<Box<dyn FnOnce() + Send>> = self @@ -8765,6 +9981,37 @@ impl Batch { } } +/// `victory bench`: submissions' refreshes run as a submission runs them. +/// Each of `submissions` (copy, title address, bytes per refresh step, in +/// step order) asks the write watch once for all it refreshes +/// ([`crate::watch::ask_once`]), then its steps go into a [`Batch`] (those +/// known to copy nothing are told so as they come) and the batch is flushed: +/// what is left is checked and copied on the refreshing threads. Returns the +/// milliseconds of the askings and of the refreshes. +pub(crate) fn bench_refreshes( + submissions: &[Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>], +) -> (f64, f64) { + let (mut asking, mut refreshing) = (0.0, 0.0); + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for steps in submissions { + ranges.clear(); + ranges.extend(steps.iter().map(|s| (s.1, s.1 + s.2))); + let started = std::time::Instant::now(); + crate::watch::ask_once(&ranges); + asking += started.elapsed().as_secs_f64() * 1e3; + let started = std::time::Instant::now(); + let mut batch = Batch::reused(); + for (shadow, at, len) in steps { + batch.add(shadow, *at, *len); + } + batch.flush(); + batch.give_back(); + refreshing += started.elapsed().as_secs_f64() * 1e3; + crate::watch::ask_once_end(); + } + (asking, refreshing) +} + /// Copies title memory at submission. The ranges were checked against their /// resources when recorded, but the title may since have unmapped pages of /// them (tiled memory, page mappings), which read as zeros here; a title @@ -8873,6 +10120,12 @@ fn read_sparse(src: *const u8, dst: *mut u8, len: usize) { read_pieces(at, to, remaining); break; } + if info.State == MEM_COMMIT + && info.Protect == PAGE_NOACCESS + && crate::demand::fulfill_range(at as usize, n, false) + { + continue; + } if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Unmapped, n as u64); @@ -9149,6 +10402,20 @@ impl Host { } } + /// [`Host::read_back_buffer`] of `size` bytes or more, from + /// [`BUFFER_POOL`] when it keeps one of the size's class (given back + /// when the list that holds it is reset, `HostList::defer_read_back`). + pub(crate) fn read_back_pooled(&self, size: u64) -> Option<ID3D12Resource> { + let Some((i, class)) = pool_class(size) else { + return self.read_back_buffer(size); + }; + if let Some(Pooled(buffer, _)) = take_pooled(i, class, false) { + return Some(buffer); + } + POOL_STATS[1].fetch_add(1, Ordering::Relaxed); + self.read_back_buffer(class) + } + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { MADE[0].fetch_add(1, Ordering::Relaxed); MADE[1].fetch_add(size, Ordering::Relaxed); @@ -9176,7 +10443,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - not_resident(), + D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, @@ -9184,7 +10451,6 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; b.Map(0, None, Some(&mut data)) }) }; @@ -9248,7 +10514,10 @@ pub(crate) static METER_FPS_TENTHS: std::sync::atomic::AtomicU32 = std::sync::at struct Meter { since: std::time::Instant, + previous_sample: Option<(std::time::Instant, u64)>, frames: u32, + #[cfg(target_arch = "x86_64")] + stage_frames: u64, #[cfg(feature = "diagnostics")] copy_stats_frames: u64, drawn: u64, @@ -9260,12 +10529,16 @@ struct Meter { impl Meter { fn new() -> Self { let now = std::time::Instant::now(); + let drawn = crate::draw::drawn(); Meter { since: now, + previous_sample: crate::switch::on("VICTORY_FRAMETIME_SAMPLES").then_some((now, drawn)), frames: 0, + #[cfg(target_arch = "x86_64")] + stage_frames: 0, #[cfg(feature = "diagnostics")] copy_stats_frames: 0, - drawn: crate::draw::drawn(), + drawn, logged: now, caption: None, } @@ -9278,6 +10551,20 @@ impl Meter { /// Counts a presented frame. fn frame(&mut self, hwnd: HWND) { + if let Some((previous, previous_drawn)) = self.previous_sample { + let now = std::time::Instant::now(); + let drawn = crate::draw::drawn(); + self.previous_sample = Some((now, drawn)); + // SAFETY: this queries the foreground window without changing focus. + let focused = unsafe { GetForegroundWindow() } == hwnd; + tracing::info!( + target: "victory_gpu::frametime", + elapsed_us = now.duration_since(previous).as_micros() as u64, + draws = drawn.saturating_sub(previous_drawn), + focused, + "rendered frame" + ); + } #[cfg(feature = "diagnostics")] tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); #[cfg(feature = "diagnostics")] @@ -9293,6 +10580,10 @@ impl Meter { } let drawn = crate::draw::drawn(); let frames = f64::from(self.frames); + #[cfg(target_arch = "x86_64")] + { + self.stage_frames += u64::from(self.frames); + } let fps = frames / elapsed.as_secs_f64(); let ms = elapsed.as_secs_f64() * 1000.0 / frames; METER_FPS_TENTHS.store((fps * 10.0).round() as u32, Ordering::Relaxed); @@ -9324,6 +10615,7 @@ impl Meter { crate::descriptor::sync_line(frames); late_line(frames); crate::queue::behind_line(frames); + shown::line(frames); crate::streamline::line(frames); card_clock_line(frames, ms); two_queues::line(frames); @@ -9346,6 +10638,14 @@ impl Meter { if rehash_runs() { "on" } else { "off" } ); } + let [changed, taken, sent, compared] = [0, 1, 2, 3].map(|i| CARD_TIME[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + if changed + taken + sent + compared > 0.0 { + tracing::info!( + "copies in the card's memory, the submitting thread per frame: {changed:.2} ms what changed, {taken:.2} taking \ + the bytes out, {sent:.2} the list that sends and hashes again (recorded and sent), {compared:.2} the \ + compares planned and recorded" + ); + } } { let [own, asking, still, all] = @@ -9434,18 +10734,7 @@ impl Meter { crate::descriptor::host::STALE[4].load(Ordering::Relaxed) ); // What the queue's room test (`crate::resource::room`) weighs. - if let Some([budget, used, blocks, buffers, targets, line]) = - crate::resource::room_terms(host().and_then(|h| h.video_memory())) - { - let weighed = used.saturating_sub(blocks) + buffers + targets; - tracing::info!( - "the texture queue's room: {used} MB in use - {blocks} MB free in texture blocks + {buffers} MB kept for \ - card copies of title buffers + {targets} MB kept for render targets = {weighed} MB against a line of \ - {line} MB ({:.1} % of a budget of {budget} MB): {}", - line as f64 * 100.0 / budget.max(1) as f64, - if weighed < line { "room" } else { "no room, new textures wait" } - ); - } + crate::resource::log_room(host().and_then(|h| h.video_memory())); let [looks, mapped, same, staged, all, made, views] = [0, 1, 2, 3, 4, 5, 6].map(|i| crate::draw::HEAP_TEXTURE_NANOS[i].swap(0, Ordering::Relaxed) / 1_000_000); let rest = all.saturating_sub(looks + mapped + same + staged + made + views); @@ -9642,6 +10931,7 @@ impl Meter { per_frame(6) / 1e3 ); } + crate::copystat_footprint::log(); let [raw_srv, raw_uav] = crate::descriptor::host::raw_view_counts(); tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ @@ -9674,6 +10964,9 @@ impl Meter { placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) ); + // Where every thread's time went since the last line (`VICTORY_CPU_STAGES`). + #[cfg(target_arch = "x86_64")] + crate::stages::frame_line(std::mem::take(&mut self.stage_frames)); #[cfg(feature = "diagnostics")] { let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); @@ -9753,6 +11046,10 @@ impl Host { overlay: Option<(&ID3D12Resource, u32)>, frame: u64, ) -> Option<bool> { + // The present before is over (its Present may be on the presenting thread, + // [`shown`]): the swap chain, its back buffer index and the frame's markers go in + // order. + self.present_wait(); // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let planes = overlay.and_then(|(over, over_state)| { @@ -9873,6 +11170,7 @@ impl Host { let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes { copy.keep(over); if let Some(composer) = p.composer.as_mut() { + copy.trace_gpu_pass("present: composite display planes", [width.into(), height.into(), 0, 0, 0]); let mut pre = Vec::with_capacity(3); if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); @@ -9929,6 +11227,9 @@ impl Host { false }; if !composed { + if render_trace::active() { + copy.gpu_pass_ours(5, "present: copy to the swap chain"); + } let mut pre = Vec::with_capacity(2); if state != D3D12_RESOURCE_STATE_COPY_SOURCE { pre.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE)); @@ -9974,6 +11275,9 @@ impl Host { } else { crate::popwatch::take(&self.device, list, texture) }; + if render_trace::active() { + copy.gpu_pass_ours(6, "present: performance panel and menu"); + } p.panel.draw(self, copy, &back, (width, height), format); p.notice.draw(self, copy, &back, (width, height), format); p.menu.draw(self, copy, &back, (width, height), format); @@ -10042,8 +11346,27 @@ impl Host { size: [width, height], }, ); + // The Present on the presenting thread ([`shown`]): with frame generation it + // blocks while frames are paced, and this thread prepares the next frame's + // submissions meanwhile (they reach the queue after it, in order). Only with the + // copy sent ahead, which nothing here waits for. + if shown::on() && slot.is_some() { + showing.end(); + let job = shown::Job { swap_chain: p.swap_chain.clone(), presenting, frame }; + drop(back); + drop(presenter); + shown::hand_over(job); + #[cfg(feature = "diagnostics")] + return Some(probe.is_some_and(|b| crate::capture::black(&b))); + #[cfg(not(feature = "diagnostics"))] + return Some(false); + } let called = crate::streamline::present_called(&presenting); - let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + let trace_start = render_trace::active().then(now_us); + let result = p.swap_chain.Present(0, DXGI_PRESENT(0)); + if let Some(start) = trace_start { + render_trace::event("present", format_args!("present_frame={frame}\tstart_us={start}\tduration_us={}\tstatus={:#x}\tasync=false", now_us().saturating_sub(start), result.0)); + } crate::streamline::present_returned(called); crate::streamline::present_ends(presenting); showing.next("the frame meter"); @@ -10062,6 +11385,7 @@ impl Host { /// sent has run (`victory upscaler-check`: before Streamline is shut /// down; nothing presents afterwards). pub(crate) fn drop_presenter(&self) { + self.present_wait(); settle_now(WHY_SYNC); *self.presenter.lock().unwrap_or_else(|e| e.into_inner()) = None; } @@ -10281,6 +11605,17 @@ impl Host { /// memory that shaders write, which upload memory cannot be. Starts in /// the common state (buffers move out of it implicitly). pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.shared_buffer_with(size, true) + } + + /// Like [`Host::shared_buffer`], without synchronous `MakeResident` / + /// copy-queue `mapped()` waits for CPU staging, readback, and relay buffers + /// that are only referenced by command lists submitted after creation. + pub(crate) fn shared_buffer_cpu(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.shared_buffer_with(size, false) + } + + fn shared_buffer_with(&self, size: u64, wait_map: bool) -> Option<(ID3D12Resource, *mut u8)> { MADE[2].fetch_add(1, Ordering::Relaxed); MADE[3].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { @@ -10310,7 +11645,7 @@ impl Host { self.device .CreateCommittedResource( &heap, - not_resident(), + if wait_map { not_resident() } else { D3D12_HEAP_FLAG_NONE }, &desc, D3D12_RESOURCE_STATE_COMMON, None, @@ -10318,8 +11653,9 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - mapped(&self.device)?; + if wait_map { + resident_and_mapped(&self.device, b, Allocation(Kind::SharedBuffer, desc.Width))?; + } b.Map(0, None, Some(&mut data)) }) }; @@ -10407,8 +11743,7 @@ impl Host { ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - mapped(&self.device)?; + resident_and_mapped(&self.device, b, Allocation(Kind::MappedLocalBuffer, desc.Width))?; b.Map(0, None, Some(&mut data)) }) }; @@ -10424,6 +11759,10 @@ impl Host { /// A device-local buffer shaders may write (unordered access) and indirect /// execution may read, starting in the common state. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> { + self.uav_buffer_for(size, Kind::LocalUavBuffer) + } + + pub(crate) fn uav_buffer_for(&self, size: u64, kind: Kind) -> Option<ID3D12Resource> { MADE[4].fetch_add(1, Ordering::Relaxed); MADE[5].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { @@ -10460,7 +11799,20 @@ impl Host { if let Some(b) = &buffer { crate::book::made(b, || "an unordered access buffer".into()); } - let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device)); + let allocation = Allocation(kind, desc.Width); + let made = made.and_then(|()| match buffer.as_ref() { + Some(buffer) => { + if wait_resident() + && kind != Kind::UavTextureSupport + && uav_residency::enabled() + && let Some(queue) = uav_residency::Queue::get(&self.uav_residency, &self.device)? + { + return queue.make_resident(buffer, allocation); + } + resident_and_mapped(&self.device, buffer, allocation) + } + None => mapped(&self.device, allocation), + }); match made { Ok(()) => buffer, Err(e) => { diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 166addd30..8c8b01eeb 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -537,6 +537,94 @@ enum To { Buffer(ID3D12Resource), } +/// One copy command: buffer, offset in it, offset in the buffer between, bytes. +type Run<'a> = (&'a ID3D12Resource, u64, u64, u64); + +/// `runs` as fewer commands that leave the same bytes in the same places +/// (`VICTORY_JOIN_STEPS=0`: one command each, as before). See [`join_runs`]. +fn joined<'a>(runs: &[Run<'a>], reads: bool) -> Vec<Run<'a>> { + static ON: OnceLock<bool> = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_STEPS").is_none_or(|v| v != "0")) { + return runs.to_vec(); + } + let keyed: Vec<(usize, u64, u64, u64)> = runs.iter().map(|r| (r.0.as_raw() as usize, r.1, r.2, r.3)).collect(); + // (The buffers by address: one of each is at hand for every key.) + let by_key: std::collections::HashMap<usize, &ID3D12Resource> = runs.iter().map(|r| (r.0.as_raw() as usize, r.0)).collect(); + join_runs(&keyed, reads) + .into_iter() + .map(|(key, offset, at, len)| (by_key[&key], offset, at, len)) + .collect() +} + +/// Joins runs (buffer key, offset, offset in between, bytes): one that starts +/// where the one before it ended, in both buffers, goes on in the same +/// command. Reads each have a place of their own between, so they may be taken +/// in the order of their sources, and where the gap between two in the source +/// is the gap in `between` (under 256 bytes: the padding of a place) the +/// command reads across it, which puts source bytes into padding nothing +/// reads. Writes keep their order and join only where they touch. +fn join_runs(runs: &[(usize, u64, u64, u64)], reads: bool) -> Vec<(usize, u64, u64, u64)> { + let mut sorted = runs.to_vec(); + if reads { + sorted.sort_by_key(|&(key, offset, ..)| (key, offset)); + } + let mut out: Vec<(usize, u64, u64, u64)> = Vec::with_capacity(sorted.len()); + for run in sorted { + if let Some(last) = out.last_mut() + && last.0 == run.0 + && run.1 >= last.1 + last.3 + && run.2 >= last.2 + last.3 + { + let (gap, at_gap) = (run.1 - (last.1 + last.3), run.2 - (last.2 + last.3)); + if gap == at_gap && (gap == 0 || (reads && gap < 256)) { + last.3 += gap + run.3; + continue; + } + } + out.push(run); + } + out +} + +#[cfg(test)] +mod join_tests { + use super::join_runs; + + #[test] + fn touching_runs_join_in_order() { + let runs = [(1, 0, 0, 16), (1, 16, 16, 16), (1, 32, 32, 8)]; + assert_eq!(join_runs(&runs, false), vec![(1, 0, 0, 40)]); + } + + #[test] + fn other_buffers_and_places_do_not_join() { + let runs = [(1, 0, 0, 16), (2, 16, 16, 16), (2, 40, 32, 8), (2, 48, 40, 8)]; + assert_eq!(join_runs(&runs, false), vec![(1, 0, 0, 16), (2, 16, 16, 16), (2, 40, 32, 16)]); + } + + #[test] + fn writes_do_not_cross_a_gap_and_keep_their_order() { + let runs = [(1, 512, 512, 480), (1, 0, 0, 480)]; + assert_eq!(join_runs(&runs, false), runs.to_vec()); + let runs = [(1, 0, 0, 480), (1, 512, 512, 480)]; + assert_eq!(join_runs(&runs, false), runs.to_vec()); + } + + #[test] + fn reads_cross_equal_padding_in_any_order() { + let runs = [(1, 1024, 1024, 480), (1, 0, 0, 480), (1, 512, 512, 480)]; + assert_eq!(join_runs(&runs, true), vec![(1, 0, 0, 1504)]); + } + + #[test] + fn reads_with_different_gaps_stay_apart() { + let runs = [(1, 0, 0, 480), (1, 520, 512, 480)]; + assert_eq!(join_runs(&runs, true), runs.to_vec()); + let runs = [(1, 0, 0, 16), (1, 4096, 16, 16)]; + assert_eq!(join_runs(&runs, true), runs.to_vec()); + } +} + /// Records a level of what [`stage`] describes into `list` (open): `reads` /// are copied into `between` (source, offset in it, offset in `between`, /// bytes), then `writes` out of it (destination, offset in it, offset in @@ -584,11 +672,11 @@ fn record( } else { list.ResourceBarrier(&[transition(between, constants, dest)]); } - for &(buffer, offset, at, len) in reads { + for (buffer, offset, at, len) in joined(reads, true) { list.CopyBufferRegion(between, at, buffer, offset, len); } list.ResourceBarrier(&barriers); - for &(buffer, offset, at, len) in writes { + for (buffer, offset, at, len) in joined(writes, false) { list.CopyBufferRegion(buffer, offset, between, at, len); } if !done.is_empty() { @@ -869,7 +957,7 @@ impl Host { own.list.reset(); return Some(own); } - let between = self.uav_buffer(BETWEEN)?; + let between = self.uav_buffer_for(BETWEEN, Kind::UavCopyIntermediate)?; name(&between, || "copies of title memory on the card".into()); let list = self.new_list().ok()?; Some(Own { list, between }) diff --git a/crates/victory-gpu/src/host/gpu_time.rs b/crates/victory-gpu/src/host/gpu_time.rs new file mode 100644 index 000000000..13af9f015 --- /dev/null +++ b/crates/victory-gpu/src/host/gpu_time.rs @@ -0,0 +1,913 @@ +//! Always-on GPU timing of what runs on the host queue, in every build: when +//! each list of ours ran on the card, and how long each pass in it took. The +//! "card's clock" line counts the time something of ours sat in the queue, +//! which is the card working *or* the card standing at a wait; these +//! timestamps are the card's own clock, so the two can be told apart. +//! +//! - **Lists** (`VICTORY_GPU_SUBMITS=0` turns this off): a timestamp at the +//! start and at the end of every host list and of our own lists on the host +//! queue (the sends and hashes before submissions, the compares after them, +//! the fetches, the state preludes). Per frame: the card's real busy time +//! (the union of the lists' spans), the time between them (the card idle: +//! waiting for us to send, or for the title to submit), and our own lists' +//! share. +//! - **Passes** (`VICTORY_GPU_PASSES=0` turns this off): inside a list, a +//! timestamp where a pass begins: draws until the render targets change, +//! each compute pipeline's run of dispatches, our own steps in the list +//! (indirect argument clamps, depth twins). A pass is named by the first +//! pipeline it runs (the names the runtime logs, with the shaders' hashes). +//! At most [`PER_LIST`] passes a list and [`PER_FRAME`] a frame. +//! +//! - **Steps** (with the passes): what a list records before its first draw +//! or dispatch (the title's barriers, waits for shader writes, copies, +//! resolves, clears), each run of one kind a pass of its own, named by the +//! kind; and per frame, for every recorded step of the kind, how many and +//! how many bytes ([`Step`]). These were one pass, "copies, barriers and +//! steps before their first draw", the card's largest. +//! +//! Also here, the one change to what the card runs: a wait for every shader +//! write (a UAV barrier on no resource) that follows another with no work +//! recorded between them is left out (`VICTORY_MERGE_BARRIERS=0` keeps them). +//! +//! How: every list takes a block of [`BLOCK`] slots of one timestamp heap, +//! writes `EndQuery` at its marks and resolves its block once when it closes +//! into a read-back buffer that stays mapped. Nothing waits: the marks are +//! read when the list's last one has landed (a non-zero value: each block is +//! zeroed when taken), on the frame-rate line or every so many lists, and a +//! list that has not run after a few seconds is let go. + +use std::collections::HashMap; +use std::fmt::Write as _; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +use super::*; + +/// Slots in a block. A normal list uses one block, a traced list takes more +/// only when it fills its current block. +const BLOCK: u32 = 64; +/// Passes a list is timed at, at most. +const PER_LIST: u32 = BLOCK - 2; +/// Blocks in the heap: some 16,000 lists, a few seconds of frames, longer +/// than [`GIVE_UP_MS`], so that a block is not taken again while it is read. +const BLOCKS: u32 = 16_384; +const RING: u32 = BLOCK * BLOCKS; +/// Passes timed a frame, at most (lists' starts and ends are not counted). +const PER_FRAME: u32 = 2048; +/// Steps timed a frame, at most (a budget of their own). +const STEPS_PER_FRAME: u32 = 3072; +/// A list whose marks have not landed after this long is let go (left open, +/// dropped, or on a queue that never ran it). +const GIVE_UP_MS: u64 = 1_500; + +/// What a pass is. +pub(crate) const DRAW: u8 = 0; +pub(crate) const COMPUTE: u8 = 1; +pub(crate) const STEPS: u8 = 2; +pub(crate) const OURS: u8 = 3; +const KINDS: [&str; 4] = ["draw", "compute", "copies/steps", "ours"]; + +fn submits_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_SUBMITS").is_none_or(|v| v != "0")) +} + +/// Waits for every shader write left out where nothing was recorded since the +/// one before (`VICTORY_MERGE_BARRIERS`, on unless 0). +fn merge_barriers_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MERGE_BARRIERS").is_none_or(|v| v != "0")) +} + +/// What a list records that is not a draw or a dispatch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Step { + /// The title's barriers with state changes (transitions, aliasing). + Transitions, + /// Waits for every shader write: the title's UAV barriers, syncs, barrier + /// groups, and its buffer barriers (buffers are host copies). + ShaderWrites, + BufferCopies, + TextureCopies, + Resolves, + Clears, + MemoryCopies, + /// Moves of title textures to the states the host's copies need (inside + /// the title's copies and clears: counted, not timed apart). + OurStates, + /// Texture uploads recorded into a list (counted, not timed apart). + Uploads, +} + +const STEP_NAMES: [&str; 9] = [ + "steps: the title's barriers with state changes", + "steps: waits for every shader write (UAV barriers, syncs, buffer barriers)", + "steps: the title's buffer copies", + "steps: the title's texture copies", + "steps: the title's resolves", + "steps: the title's clears", + "steps: the title's memory copies", + "steps: our moves of title textures' states", + "steps: texture uploads into lists", +]; + +/// Per step kind since the last frame-rate line: recorded, bytes. +static STEP_COUNTS: [[AtomicU64; 2]; 9] = [const { [const { AtomicU64::new(0) }; 2] }; 9]; +/// Barriers recorded by the title's barrier calls: transitions, aliasing, +/// UAV barriers on a resource, waits for every shader write recorded, those +/// left out as repeated. +static BARRIERS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// Our sends of title bytes: copy runs as made, as recorded (joined). +static SENT_RUNS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// A step of `kind` recorded, `bytes` long (0: not known). +pub(crate) fn count_step(kind: Step, bytes: u64) { + let k = &STEP_COUNTS[kind as usize]; + k[0].fetch_add(1, Ordering::Relaxed); + k[1].fetch_add(bytes, Ordering::Relaxed); +} + +/// The title's barrier call came to these host barriers. +pub(crate) fn count_barriers(transitions: u64, aliasing: u64, uav: u64) { + BARRIERS[0].fetch_add(transitions, Ordering::Relaxed); + BARRIERS[1].fetch_add(aliasing, Ordering::Relaxed); + BARRIERS[2].fetch_add(uav, Ordering::Relaxed); +} + +/// Our sends' copy runs: as made, as recorded (joined). +pub(crate) fn count_sent_runs(made: u64, recorded: u64) { + SENT_RUNS[0].fetch_add(made, Ordering::Relaxed); + SENT_RUNS[1].fetch_add(recorded, Ordering::Relaxed); +} + +/// Each step kind's pass name, interned once. +fn step_names() -> &'static [u32; 9] { + static NAMES: OnceLock<[u32; 9]> = OnceLock::new(); + NAMES.get_or_init(|| std::array::from_fn(|i| INTERNED.intern(STEP_NAMES[i]))) +} + +fn passes_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| submits_on() && std::env::var_os("VICTORY_GPU_PASSES").is_none_or(|v| v != "0")) +} + +struct Ring { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + data: usize, + frequency: u64, +} + +// SAFETY: free-threaded D3D12 objects and a mapping each list writes its own +// block of. +unsafe impl Send for Ring {} +// SAFETY: as above. +unsafe impl Sync for Ring {} + +fn ring() -> Option<&'static Ring> { + static RING_: OnceLock<Option<Ring>> = OnceLock::new(); + RING_ + .get_or_init(|| { + if !submits_on() { + return None; + } + let host = host()?; + let mut heap: Option<ID3D12QueryHeap> = None; + // SAFETY: a timestamp heap of the host device; the host queue's + // timestamp frequency. + let frequency = unsafe { + host.device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: RING, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + host.queue.GetTimestampFrequency().ok()? + }; + if frequency == 0 { + return None; + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(RING) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut back: Option<ID3D12Resource> = None; + // SAFETY: a read-back buffer in the state ResolveQueryData needs. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .ok()?; + } + let back = back?; + let mut data = std::ptr::null_mut(); + // SAFETY: kept mapped for the process, with the buffer. + unsafe { back.Map(0, None, Some(&mut data)).ok()? }; + if data.is_null() { + return None; + } + tracing::info!( + lists = BLOCKS, + per_list = PER_LIST, + per_frame = PER_FRAME, + passes = passes_on(), + "GPU timing of lists and passes on (VICTORY_GPU_SUBMITS=0 / VICTORY_GPU_PASSES=0 turn it off)" + ); + Some(Ring { heap: heap?, back, data: data as usize, frequency }) + }) + .as_ref() +} + +/// The names of passes, by number. +struct Interned(Mutex<Option<(Vec<String>, HashMap<String, u32>)>>); + +impl Interned { + fn with_names<T>(&self, f: impl FnOnce(&[String]) -> T) -> T { + let names = self.0.lock().unwrap_or_else(|e| e.into_inner()); + f(names.as_ref().map_or(&[][..], |(all, _)| all.as_slice())) + } + + fn intern(&self, name: &str) -> u32 { + let mut names = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let (all, by) = names.get_or_insert_with(Default::default); + if let Some(&n) = by.get(name) { + return n; + } + let n = all.len() as u32; + all.push(name.to_owned()); + by.insert(name.to_owned(), n); + n + } +} + +static INTERNED: Interned = Interned(Mutex::new(None)); + +/// What a mark begins: the list (with its first pass), a pass, or the end. +#[derive(Clone, Copy)] +enum What { + Start { name: u32, kind: u8, ours: bool }, + Pass { name: u32, kind: u8 }, + End, +} + +/// Per block, the number of the list that took it last (its `taken` count plus one): a list +/// left open past a turn of the ring (lists made ahead and left open) finds its block taken +/// by another and is neither resolved nor read, so two lists' values are never mixed. +static OWNER: [AtomicU64; BLOCKS as usize] = [const { AtomicU64::new(0) }; BLOCKS as usize]; + +/// A list being recorded: its block and its marks so far. +struct Rec { + base: u32, + /// Its number in [`OWNER`]. + taken: u64, + marks: Vec<(u32, What)>, + extra: Vec<(u32, u64)>, + trace: Option<Box<Trace>>, +} + +struct Trace { + list: usize, + commands: Vec<TraceCommand>, +} + +struct TraceCommand { + index: usize, + cpu_us: u64, + thread: u32, + frame: u64, + command: render_trace::Command, +} + +fn block(ring: &Ring) -> (u32, u64) { + static NEXT: AtomicU64 = AtomicU64::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let block = (n % u64::from(BLOCKS)) as u32; + OWNER[block as usize].store(n + 1, Ordering::Release); + let base = block * BLOCK; + // SAFETY: the block lies within the ring mapping. + unsafe { std::ptr::write_bytes((ring.data as *mut u64).add(base as usize), 0, BLOCK as usize) }; + (base, n + 1) +} + +fn owns(base: u32, taken: u64, extra: &[(u32, u64)]) -> bool { + let owned = |base, taken| OWNER[(base / BLOCK) as usize].load(Ordering::Acquire) == taken; + owned(base, taken) && extra.iter().all(|&(base, taken)| owned(base, taken)) +} + +impl Rec { + /// A new block, zeroed, and the list's start. + fn begin(list: &ID3D12GraphicsCommandList, name: u32, kind: u8, ours: bool) -> Option<Rec> { + let ring = ring()?; + let (base, taken) = block(ring); + let mut rec = Rec { base, taken, marks: Vec::with_capacity(8), extra: Vec::new(), trace: None }; + let what = What::Start { name, kind, ours }; + if render_trace::active() { + rec.trace_mark(list, what, render_trace::Command("list_start", [0; 5])); + } else { + rec.mark(list, what); + } + Some(rec) + } + + fn trace_mark(&mut self, list: &ID3D12GraphicsCommandList, what: What, command: render_trace::Command) { + let index = self.marks.len(); + let trace = self.trace.get_or_insert_with(|| { + let identity = list.cast::<ID3D12CommandList>().map_or_else(|_| list.as_raw() as usize, |base| base.as_raw() as usize); + Box::new(Trace { list: identity, commands: Vec::new() }) + }); + trace.commands.push(TraceCommand { index, cpu_us: now_us(), thread: thread_id(), frame: crate::frame::current(), command }); + self.mark(list, what); + } + + fn mark(&mut self, list: &ID3D12GraphicsCommandList, what: What) -> bool { + let Some(ring) = ring() else { return false }; + let used = self.marks.len() as u32; + // (the last slot is the end's) + let room = if matches!(what, What::End) { BLOCK } else { BLOCK - 1 }; + if used >= room && self.trace.is_none() { + return false; + } + let chunk = (used / BLOCK) as usize; + let base = if chunk == 0 { + self.base + } else { + if self.extra.len() < chunk { + self.extra.push(block(ring)); + } + self.extra[chunk - 1].0 + }; + let slot = base + used % BLOCK; + // SAFETY: an open list; the slot is this list's. + unsafe { list.EndQuery(&ring.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot) }; + self.marks.push((slot, what)); + true + } + + /// The end, the block resolved, and the marks handed over to be read. + fn end(mut self, list: &ID3D12GraphicsCommandList) { + let Some(ring) = ring() else { return }; + // (its block taken by another list meanwhile: not resolved, not read) + if !owns(self.base, self.taken, &self.extra) { + if let Some(trace) = &self.trace { + render_trace::event("list_trace_lost", format_args!("record={}\tlist={:#x}\treason=reused_before_close", self.taken, trace.list)); + } + if let Some(acc) = ACC.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + acc.lost += 1; + } + return; + } + if let Some(trace) = &self.trace { + let identity = trace.list; + self.trace_mark(list, What::End, render_trace::Command("list_close", [0; 5])); + render_trace::event("list_recorded", format_args!("record={}\tlist={identity:#x}\tmarks={}", self.taken, self.marks.len())); + } else if !self.mark(list, What::End) { + return; + } + let count = self.marks.len() as u32; + // SAFETY: an open list; these queries were ended in it; the buffer + // holds the whole ring. + for (chunk, base) in std::iter::once(self.base).chain(self.extra.iter().map(|&(base, _)| base)).enumerate() { + let count = (count - chunk as u32 * BLOCK).min(BLOCK); + unsafe { list.ResolveQueryData(&ring.heap, D3D12_QUERY_TYPE_TIMESTAMP, base, count, &ring.back, u64::from(base) * 8) }; + } + let n = { + let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(Pending { at: now_ms(), base: self.base, taken: self.taken, marks: self.marks, extra: self.extra, trace: self.trace }); + pending.len() + }; + static ENDED: AtomicU64 = AtomicU64::new(0); + if ENDED.fetch_add(1, Ordering::Relaxed) % 256 == 255 || n > 4096 { + collect(false); + } + } +} + +struct Pending { + at: u64, + /// Its block and its number in [`OWNER`]. + base: u32, + taken: u64, + marks: Vec<(u32, What)>, + extra: Vec<(u32, u64)>, + trace: Option<Box<Trace>>, +} + +static PENDING: Mutex<Vec<Pending>> = Mutex::new(Vec::new()); + +/// What the lists that ran since the last frame-rate line came to. +#[derive(Default)] +struct Acc { + /// Lists' spans on the card (ticks). + spans: Vec<(u64, u64)>, + /// Our own lists' ticks. + ours: u64, + lists: u64, + ours_lists: u64, + /// Per pass name: kind, ticks, times. + passes: HashMap<u32, (u8, u64, u64)>, + /// Lists let go unread. + lost: u64, +} + +static ACC: Mutex<Option<Acc>> = Mutex::new(None); + +/// Reads the lists whose marks have landed. +fn collect(wait: bool) { + let Some(ring) = ring() else { return }; + let mut pending = if wait { + PENDING.lock().unwrap_or_else(|e| e.into_inner()) + } else { + match PENDING.try_lock() { + Ok(p) => p, + Err(_) => return, + } + }; + let now = now_ms(); + let data = ring.data as *const u64; + // SAFETY: inside the mapping; the card writes whole 8-byte values. + let read = |slot: u32| unsafe { data.add(slot as usize).read_volatile() }; + let mut landed = Vec::new(); + let mut lost = 0u64; + pending.retain_mut(|p| { + // (its block taken again before it was read: another list's values now) + let reason = if !owns(p.base, p.taken, &p.extra) { + "reused_before_read" + } else if p.marks.last().is_some_and(|m| read(m.0) != 0) { + let marks = p.marks.iter().map(|&(slot, what)| (read(slot), what)).collect::<Vec<_>>(); + if owns(p.base, p.taken, &p.extra) { + landed.push((p.taken, marks, p.trace.take())); + return false; + } + "reused_during_read" + } else if now.saturating_sub(p.at) > GIVE_UP_MS { + "unresolved" + } else { + return true; + }; + lost += 1; + if let Some(trace) = &p.trace { + render_trace::event("list_trace_lost", format_args!("record={}\tlist={:#x}\treason={reason}", p.taken, trace.list)); + } + false + }); + drop(pending); + if landed.is_empty() && lost == 0 { + return; + } + for (record, marks, trace) in &landed { + if let Some(trace) = trace { + trace_landed(*record, marks, trace, ring.frequency); + } + } + let mut acc = ACC.lock().unwrap_or_else(|e| e.into_inner()); + let acc = acc.get_or_insert_with(Acc::default); + acc.lost += lost; + for (_, marks, _) in landed { + let (Some(first), Some(last)) = (marks.first(), marks.last()) else { continue }; + if first.0 == 0 || last.0 < first.0 { + continue; + } + acc.spans.push((first.0, last.0)); + acc.lists += 1; + if let What::Start { ours: true, .. } = first.1 { + acc.ours += last.0 - first.0; + acc.ours_lists += 1; + } + for pair in marks.windows(2) { + let (at, what) = pair[0]; + let ticks = pair[1].0.saturating_sub(at); + let (name, kind) = match what { + What::Start { name, kind, .. } | What::Pass { name, kind } => (name, kind), + What::End => continue, + }; + let e = acc.passes.entry(name).or_insert((kind, 0, 0)); + e.1 += ticks; + e.2 += 1; + } + } +} + +fn trace_landed(record: u64, marks: &[(u64, What)], trace: &Trace, frequency: u64) { + let mut batch = String::new(); + let list = trace.list; + INTERNED.with_names(|names| { + for &TraceCommand { index, cpu_us, thread, frame, command: render_trace::Command(op, args) } in &trace.commands { + let (start, what) = marks[index]; + let end = marks.get(index + 1).map_or(start, |mark| mark.0); + let name = match what { + What::Start { name, .. } | What::Pass { name, .. } => &names[name as usize], + What::End => "", + }; + let valid = start != 0 && end >= start; + let _ = writeln!(batch, "gpu_command\trecord={record}\tlist={list:#x}\tseq={index}\tcpu_us={cpu_us}\tthread={thread}\tframe={frame}\top={op}\targs={args:?}\tname={name}\tgpu_start={start}\tgpu_end={end}\tgpu_hz={frequency}\ttiming_valid={valid}"); + } + }); + render_trace::write(batch); +} + +/// The per-frame lines, on the frame-rate line. +pub(super) fn log(frames: f64) { + let Some(ring) = ring() else { return }; + collect(true); + let Some(acc) = ACC.lock().unwrap_or_else(|e| e.into_inner()).take() else { return }; + let frames = frames.max(1.0); + let ms = |ticks: u64| ticks as f64 * 1e3 / ring.frequency as f64; + let mut spans = acc.spans; + spans.sort_unstable(); + // The union of the lists' spans: the card running ours. + let (mut busy, mut idle, mut idle_gaps) = (0u64, 0u64, 0u64); + let mut current: Option<(u64, u64)> = None; + for (a, b) in spans.iter().copied() { + match current { + Some((s, e)) if a <= e => current = Some((s, e.max(b))), + Some((s, e)) => { + busy += e - s; + idle += a - e; + idle_gaps += 1; + current = Some((a, b)); + } + None => current = Some((a, b)), + } + } + if let Some((s, e)) = current { + busy += e - s; + } + let first_to_last = match (spans.first(), spans.iter().map(|s| s.1).max()) { + (Some(f), Some(l)) => l.saturating_sub(f.0), + _ => 0, + }; + tracing::info!( + "GPU time per frame by the card's own clock (VICTORY_GPU_SUBMITS): {:.1} lists, the card running them {:.2} ms (the union of their spans), idle between them {:.2} ms in {:.1} gaps (waiting for us to send or for the title to submit), first to last {:.1} ms (the card running {:.0} % of that: per frame the sums run high when lists of the line before land late); of the running our own lists (sends and hashes, compares, fetches, preludes) {:.2} ms in {:.1}; {} lists not read (not run in {} ms)", + acc.lists as f64 / frames, + ms(busy) / frames, + ms(idle) / frames, + idle_gaps as f64 / frames, + ms(first_to_last) / frames, + if first_to_last > 0 { busy as f64 * 100.0 / first_to_last as f64 } else { 0.0 }, + ms(acc.ours) / frames, + acc.ours_lists as f64 / frames, + acc.lost, + GIVE_UP_MS, + ); + if acc.passes.is_empty() { + return; + } + // By kind, then the costliest passes. + let mut kinds = [(0u64, 0u64); 4]; + for &(kind, ticks, times) in acc.passes.values() { + let k = &mut kinds[usize::from(kind.min(3))]; + k.0 += ticks; + k.1 += times; + } + let names = INTERNED.with_names(|all| all.to_vec()); + log_steps(frames, &acc.passes, &ms); + let mut passes: Vec<(u32, u8, u64, u64)> = acc.passes.iter().map(|(&n, &(k, t, c))| (n, k, t, c)).collect(); + passes.sort_unstable_by(|a, b| b.2.cmp(&a.2)); + let mut top = String::new(); + for (i, &(name, kind, ticks, times)) in passes.iter().take(25).enumerate() { + use std::fmt::Write as _; + let _ = write!( + top, + "{}{}. {} [{}] {:.2} ms ({:.1}x)", + if i == 0 { "" } else { "; " }, + i + 1, + names.get(name as usize).map_or("?", String::as_str), + KINDS[usize::from(kind.min(3))], + ms(ticks) / frames, + times as f64 / frames, + ); + } + tracing::info!( + "GPU passes per frame (VICTORY_GPU_PASSES; at most {PER_LIST} a list and {PER_FRAME} a frame, the rest counted in the pass before): draws {:.2} ms, compute {:.2} ms, copies and steps {:.2} ms, ours {:.2} ms; the costliest: {}", + ms(kinds[DRAW as usize].0) / frames, + ms(kinds[COMPUTE as usize].0) / frames, + ms(kinds[STEPS as usize].0) / frames, + ms(kinds[OURS as usize].0) / frames, + top, + ); +} + +/// The steps line: per kind, recorded and bytes a frame and the card's time +/// of their runs before the lists' first draws; the title's barriers; our +/// sends' copy runs. +fn log_steps(frames: f64, passes: &HashMap<u32, (u8, u64, u64)>, ms: &dyn Fn(u64) -> f64) { + use std::fmt::Write as _; + let ids = step_names(); + let mut kinds = String::new(); + for (i, name) in STEP_NAMES.iter().enumerate() { + let n = STEP_COUNTS[i][0].swap(0, Ordering::Relaxed); + let bytes = STEP_COUNTS[i][1].swap(0, Ordering::Relaxed); + let (ticks, runs) = passes.get(&ids[i]).map_or((0, 0), |&(_, t, c)| (t, c)); + if n == 0 && runs == 0 { + continue; + } + let _ = write!( + kinds, + "{}{}: {:.1} recorded, {:.2} MB, {:.2} ms on the card in {:.1} runs before first draws", + if kinds.is_empty() { "" } else { "; " }, + name.trim_start_matches("steps: "), + n as f64 / frames, + bytes as f64 / 1e6 / frames, + ms(ticks) / frames, + runs as f64 / frames, + ); + } + let b: Vec<u64> = BARRIERS.iter().map(|b| b.swap(0, Ordering::Relaxed)).collect(); + let sent: Vec<u64> = SENT_RUNS.iter().map(|s| s.swap(0, Ordering::Relaxed)).collect(); + tracing::info!( + "GPU steps per frame (VICTORY_GPU_PASSES): {kinds}; the title's barriers came to {:.1} transitions, {:.1} aliasing, {:.1} UAV barriers on a resource, {:.1} waits for every shader write recorded and {:.1} left out as repeated with nothing recorded since the one before (VICTORY_MERGE_BARRIERS={}); our sends of title bytes {:.1} copy runs made, {:.1} recorded after joining adjacent ones (VICTORY_BATCH_COPIES={})", + b[0] as f64 / frames, + b[1] as f64 / frames, + b[2] as f64 / frames, + b[3] as f64 / frames, + b[4] as f64 / frames, + u8::from(merge_barriers_on()), + sent[0] as f64 / frames, + sent[1] as f64 / frames, + u8::from(super::send::batch_copies_on()), + ); +} + +/// Whether one more step may be timed this frame. +fn step_room() -> bool { + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static COUNT: AtomicU32 = AtomicU32::new(0); + let now = crate::frame::current(); + if FRAME.swap(now, Ordering::Relaxed) != now { + COUNT.store(0, Ordering::Relaxed); + } + COUNT.fetch_add(1, Ordering::Relaxed) < STEPS_PER_FRAME +} + +/// Whether one more pass may be timed this frame. +fn frame_room() -> bool { + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static COUNT: AtomicU32 = AtomicU32::new(0); + let now = crate::frame::current(); + if FRAME.swap(now, Ordering::Relaxed) != now { + COUNT.store(0, Ordering::Relaxed); + } + COUNT.fetch_add(1, Ordering::Relaxed) < PER_FRAME +} + +/// A host list's timing: its record while it is recorded, and the pass it is in. +#[derive(Default)] +pub(super) struct List { + state: Mutex<ListState>, + /// Work recorded so far (draws, dispatches, copies, clears, held indirect + /// executions, ...): only compared, for [`List::wait_for_writes`]. + work: AtomicU64, + /// `work` + 1 when the last wait for every shader write was recorded + /// (0: none in this list yet). + waited_at: AtomicU64, + /// Whether shader/copy UAV-producing work was recorded since the last + /// list start or UAV wait. + uav_dirty: AtomicBool, +} + +#[derive(Default)] +struct ListState { + rec: Option<Rec>, + /// The pass it is in (0: none yet, or the render targets changed). + key: u64, + /// A draw or dispatch was recorded: steps are timed only before it. + drawn: bool, + /// The step kind of the run it is in, + 1 (0: none). + step: usize, +} + +impl List { + /// The list begins to be recorded (made, or reset). + pub(super) fn start(&self, list: &ID3D12GraphicsCommandList) { + self.work.store(0, Ordering::Relaxed); + self.waited_at.store(0, Ordering::Relaxed); + // Start dirty because a prior list on the host queue may have left + // unsynchronized UAV writes before this list's first barrier. + self.uav_dirty.store(true, Ordering::Relaxed); + if !submits_on() { + return; + } + static FIRST: OnceLock<u32> = OnceLock::new(); + let name = *FIRST.get_or_init(|| { + INTERNED.intern("lists: from their start to the first step, draw or dispatch (states, our own steps)") + }); + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + s.rec = Rec::begin(list, name, STEPS, false); + s.key = 0; + s.drawn = false; + s.step = 0; + } + + /// Work was recorded into the list. + pub(super) fn work(&self) { + self.work.fetch_add(1, Ordering::Relaxed); + } + + /// Shader/copy UAV-producing work was recorded into the list. + #[allow(dead_code)] + pub(super) fn uav_work(&self) { + self.uav_dirty.store(true, Ordering::Relaxed); + } + + /// Clears the shader/copy UAV dirty flag without emitting a wait. + #[allow(dead_code)] + pub(super) fn clear_uav_dirty(&self) { + self.uav_dirty.store(false, Ordering::Relaxed); + } + + /// Whether shader/copy UAV-producing work was recorded since the last + /// start or UAV wait. + #[allow(dead_code)] + pub(super) fn is_uav_dirty(&self) -> bool { + self.uav_dirty.load(Ordering::Relaxed) + } + + /// Alias for [`Self::is_uav_dirty`] for `host.rs` wiring. + #[allow(dead_code)] + pub(super) fn has_uav_work(&self) -> bool { + self.is_uav_dirty() + } + + /// Whether a wait for every shader write (a UAV barrier on no resource) + /// is to be recorded now: not if the last one in this list had nothing + /// recorded after it (`VICTORY_MERGE_BARRIERS=0`: always). Counted. + pub(super) fn wait_for_writes(&self) -> bool { + let now = self.work.load(Ordering::Relaxed) + 1; + let was = self.waited_at.swap(now, Ordering::Relaxed); + if was == now && merge_barriers_on() { + BARRIERS[4].fetch_add(1, Ordering::Relaxed); + return false; + } + self.uav_dirty.store(false, Ordering::Relaxed); + BARRIERS[3].fetch_add(1, Ordering::Relaxed); + true + } + + /// Like [`Self::wait_for_writes`], but gated on [`Self::uav_dirty`] + /// instead of generic `work` (so non-UAV draws and `OMSetRenderTargets` + /// do not force a global UAV barrier). + #[allow(dead_code)] + pub(super) fn wait_for_uav_writes(&self) -> bool { + let was = self.uav_dirty.swap(false, Ordering::Relaxed); + if !was && merge_barriers_on() { + BARRIERS[4].fetch_add(1, Ordering::Relaxed); + return false; + } + self.waited_at.store(self.work.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + BARRIERS[3].fetch_add(1, Ordering::Relaxed); + true + } + + /// A step of `kind` is recorded next: a pass of its own on the card if + /// the list has no draw or dispatch yet and the run it is in is of + /// another kind. + pub(super) fn step(&self, list: &ID3D12GraphicsCommandList, kind: Step, bytes: u64) { + if !passes_on() { + return; + } + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if render_trace::active() && let Some(rec) = s.rec.as_mut() { + rec.trace_mark(list, What::Pass { name: step_names()[kind as usize], kind: STEPS }, render_trace::Command("step", [bytes as i64, 0, 0, 0, 0])); + s.step = kind as usize + 1; + s.key = 0; + return; + } + if s.drawn || s.step == kind as usize + 1 || s.rec.as_ref().is_none_or(|r| r.marks.len() as u32 >= PER_LIST) { + return; + } + s.step = kind as usize + 1; + // (the draw or dispatch after it begins a pass of its own) + s.key = 0; + if !step_room() { + return; + } + let name = step_names()[kind as usize]; + if let Some(rec) = s.rec.as_mut() { + rec.mark(list, What::Pass { name, kind: STEPS }); + } + } + + /// Work of `kind` keyed `key` is recorded next: a new pass if the key is + /// another than the pass's. + pub(super) fn pass(&self, list: &ID3D12GraphicsCommandList, key: u64, kind: u8, command: render_trace::Command, name: impl FnOnce() -> String) { + if !passes_on() { + return; + } + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if kind == DRAW || kind == COMPUTE { + s.drawn = true; + } + if render_trace::active() && let Some(rec) = s.rec.as_mut() { + rec.trace_mark(list, What::Pass { name: INTERNED.intern(&name()), kind }, command); + s.key = key; + return; + } + if s.key == key || s.rec.as_ref().is_none_or(|r| r.marks.len() as u32 >= PER_LIST) { + return; + } + s.key = key; + if !frame_room() { + return; + } + let name = INTERNED.intern(&name()); + if let Some(rec) = s.rec.as_mut() { + rec.mark(list, What::Pass { name, kind }); + } + } + + /// The render targets changed: the next draw begins a pass. + pub(super) fn break_pass(&self) { + if passes_on() { + self.state.lock().unwrap_or_else(|e| e.into_inner()).key = 0; + } + } + + /// The list is closed. + pub(super) fn end(&self, list: &ID3D12GraphicsCommandList) { + let rec = self.state.lock().unwrap_or_else(|e| e.into_inner()).rec.take(); + if let Some(rec) = rec { + rec.end(list); + } + } +} + +/// One of our own lists on the host queue: timed as a whole, named `name`. +pub(super) struct Ours(Option<Rec>); + +impl Ours { + pub(super) fn begin(list: &ID3D12GraphicsCommandList, name: &'static str) -> Ours { + if !submits_on() { + return Ours(None); + } + Ours(Rec::begin(list, INTERNED.intern(name), OURS, true)) + } + + /// A new pass of ours in the list. + pub(super) fn pass(&mut self, list: &ID3D12GraphicsCommandList, name: &'static str) { + if !passes_on() { + return; + } + if let Some(rec) = self.0.as_mut() { + if render_trace::active() { + rec.trace_mark(list, What::Pass { name: INTERNED.intern(name), kind: OURS }, render_trace::Command("host_pass", [0; 5])); + } else if frame_room() { + rec.mark(list, What::Pass { name: INTERNED.intern(name), kind: OURS }); + } + } + } + + pub(super) fn end(self, list: &ID3D12GraphicsCommandList) { + if let Some(rec) = self.0 { + rec.end(list); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detailed_gpu_timing_resolves_more_than_one_query_block() { + let Some(host) = host() else { return }; + let Some(ring) = ring() else { return }; + let list = host.make_list().unwrap(); + let name = INTERNED.intern("query block regression test"); + let slots: Vec<_> = { + let mut state = list.gpu_time.state.lock().unwrap(); + let rec = state.rec.as_mut().unwrap(); + for _ in 0..BLOCK + 8 { + rec.trace_mark(&list.list, What::Pass { name, kind: OURS }, render_trace::Command("test_marker", [0; 5])); + } + assert_eq!(rec.extra.len(), 1); + rec.marks.iter().map(|mark| mark.0).collect() + }; + list.close(); + let native = [Some(list.list.cast().unwrap())]; + // SAFETY: the list is closed and stays alive through its completion. + unsafe { + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + host.queue_send(&native, &[], Some((&fence, 1))).unwrap(); + fence.SetEventOnCompletion(1, HANDLE::default()).unwrap(); + } + let timestamps: Vec<_> = slots.iter().map(|&slot| { + // SAFETY: the queue finished resolving these slots into the mapping. + unsafe { (ring.data as *const u64).add(slot as usize).read_volatile() } + }).collect(); + assert!(timestamps.iter().all(|&tick| tick != 0)); + assert!(timestamps.windows(2).all(|pair| pair[0] <= pair[1])); + collect(true); + render_trace::flush(); + } +} diff --git a/crates/victory-gpu/src/host/memory_samples.rs b/crates/victory-gpu/src/host/memory_samples.rs new file mode 100644 index 000000000..1736d1602 --- /dev/null +++ b/crates/victory-gpu/src/host/memory_samples.rs @@ -0,0 +1,156 @@ +//! Optional accounting for explicit residency operations and DXGI usage. + +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::{ID3D12Device, ID3D12Resource}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Kind { + TextureHeap, + SampledTexture, + WritableTexture, + DepthTwin, + SharedBuffer, + MappedLocalBuffer, + LocalUavBuffer, + UavPlacedConstants, + UavCopyAlias, + UavCopyIntermediate, + UavIndirectBudget, + UavIndirectScratch, + UavShadow, + UavSend, + UavTextureSupport, +} + +impl Kind { + const ALL: [(Self, &'static str); 15] = [ + (Self::TextureHeap, "texture_heap"), + (Self::SampledTexture, "sampled_texture"), + (Self::WritableTexture, "writable_texture"), + (Self::DepthTwin, "depth_twin"), + (Self::SharedBuffer, "shared_buffer"), + (Self::MappedLocalBuffer, "mapped_local_buffer"), + (Self::LocalUavBuffer, "local_uav_buffer"), + (Self::UavPlacedConstants, "local_uav_placed_constants"), + (Self::UavCopyAlias, "local_uav_copy_alias"), + (Self::UavCopyIntermediate, "local_uav_copy_intermediate"), + (Self::UavIndirectBudget, "local_uav_indirect_budget"), + (Self::UavIndirectScratch, "local_uav_indirect_scratch"), + (Self::UavShadow, "local_uav_shadow"), + (Self::UavSend, "local_uav_send"), + (Self::UavTextureSupport, "local_uav_texture_support"), + ]; +} + +#[derive(Clone, Copy)] +// Size of the allocation handled by each attempt. Mapping and residency +// can both report the same allocation. DXGI reports the process totals. +pub(crate) struct Allocation(pub Kind, pub u64); + +impl Allocation { + pub(crate) fn texture(kind: Kind, device: &ID3D12Device, texture: &ID3D12Resource) -> Self { + let mut bytes = 0; + if enabled() { + // SAFETY: plain queries on the allocated resource and its device. + let size = unsafe { device.GetResourceAllocationInfo(0, &[texture.GetDesc()]) }.SizeInBytes; + if size != u64::MAX { + bytes = size; + } + } + Self(kind, bytes) + } +} + +#[derive(Clone, Copy)] +pub(super) enum Step { + MakeResident, + WaitForMapping, + Enqueue, + WaitForFence, +} + +#[derive(Clone, Copy)] +struct Counts { + calls: u64, + errors: u64, + bytes: u64, + elapsed_us: u64, + max_us: u64, +} + +impl Counts { + const EMPTY: Self = Self { calls: 0, errors: 0, bytes: 0, elapsed_us: 0, max_us: 0 }; +} + +const EMPTY: [[Counts; 4]; Kind::ALL.len()] = [[Counts::EMPTY; 4]; Kind::ALL.len()]; +static COUNTS: Mutex<[[Counts; 4]; Kind::ALL.len()]> = Mutex::new(EMPTY); + +fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_MEMORY_SAMPLES")) +} + +pub(super) fn record(Allocation(kind, bytes): Allocation, step: Step, elapsed_us: u64, error: bool) { + if !enabled() { + return; + } + let mut all = COUNTS.lock().unwrap_or_else(|e| e.into_inner()); + let count = &mut all[kind as usize][step as usize]; + count.calls += 1; + count.errors += u64::from(error); + count.bytes = count.bytes.saturating_add(bytes); + count.elapsed_us += elapsed_us; + count.max_us = count.max_us.max(elapsed_us); +} + +pub(super) fn report(memory: Option<[u64; 4]>) { + if !enabled() { + return; + } + let counts = std::mem::replace(&mut *COUNTS.lock().unwrap_or_else(|e| e.into_inner()), EMPTY); + let frame = crate::frame::current(); + if let Some([local_budget, local_used, nonlocal_budget, nonlocal_used]) = memory { + tracing::info!( + target: "victory_gpu::memory", + frame, + local_budget_mib = local_budget >> 20, + local_used_mib = local_used >> 20, + nonlocal_budget_mib = nonlocal_budget >> 20, + nonlocal_used_mib = nonlocal_used >> 20, + "DXGI memory sample" + ); + } + for (kind, domain) in Kind::ALL { + let [resident, mapped, enqueued, waited] = counts[kind as usize]; + if resident.calls + mapped.calls + enqueued.calls + waited.calls == 0 { + continue; + } + tracing::info!( + target: "victory_gpu::memory", + frame, + domain, + resident_calls = resident.calls, + resident_errors = resident.errors, + resident_bytes = resident.bytes, + resident_us = resident.elapsed_us, + resident_max_us = resident.max_us, + mapped_calls = mapped.calls, + mapped_errors = mapped.errors, + mapped_bytes = mapped.bytes, + mapped_us = mapped.elapsed_us, + mapped_max_us = mapped.max_us, + enqueue_calls = enqueued.calls, + enqueue_errors = enqueued.errors, + enqueue_bytes = enqueued.bytes, + enqueue_us = enqueued.elapsed_us, + enqueue_max_us = enqueued.max_us, + paging_wait_calls = waited.calls, + paging_wait_errors = waited.errors, + paging_wait_bytes = waited.bytes, + paging_wait_us = waited.elapsed_us, + paging_wait_max_us = waited.max_us, + "GPU residency sample" + ); + } +} diff --git a/crates/victory-gpu/src/host/menu.rs b/crates/victory-gpu/src/host/menu.rs index 8cceb6af3..96f3548be 100644 --- a/crates/victory-gpu/src/host/menu.rs +++ b/crates/victory-gpu/src/host/menu.rs @@ -91,17 +91,15 @@ const ITEMS: &[Item] = &[ Item { var: "VICTORY_AMBIENT_SPECULAR", label: "REFLECTION ESTIMATE", values: ON_UNSET, live: false }, Item { var: "VICTORY_AMBIENT_AIR", label: "FOG CAP", values: &[("1.5", "1.5"), ("1", "1"), ("2", "2"), ("", "NONE")], live: false }, Item { var: "VICTORY_BVH_BUILDER", label: "RAY TRACING (SLOW, BROKEN)", values: UNSET_ON, live: false }, - Item { var: "VICTORY_WATER_LIGHT", label: "WATER LIGHT", values: &[("", "OFF (NO DARK BLOCKS)"), ("1", "ON (GREEN, DARK BLOCKS)")], live: false }, + Item { var: "VICTORY_WATER_LIGHT", label: "WATER LIGHT", values: &[("", "OFF"), ("1", "ON")], live: false }, Item { var: "VICTORY_LEAVE_OUT", label: "HEAT HAZE AND DECAL DEFRAG", values: &[("02384a60fda6f2d0,731a39171b568298", "LEFT OUT"), ("", "RUN (SLOWER, SMEARS)")], live: false }, Item { var: "VICTORY_EARLY_DEPTH", label: "EARLY DEPTH TEST", values: ON_UNSET, live: false }, - Item { var: "VICTORY_WC_NO_BACK", label: "SKIP BIG COPY-BACKS", values: ON_UNSET, live: false }, Item { var: "VICTORY_SOFT_VIEWS", label: "SOFT VIEWS (NO CUT FREEZES)", values: &[("copies", "ON"), ("", "OFF")], live: false }, Item { var: "VICTORY_TEXTURE_NO_WAIT", label: "TEXTURE NO WAIT", values: ON_UNSET, live: false }, Item { var: "VICTORY_RELAY", label: "RELAY (SPEED, TRIANGLES)", values: STAGES, live: false }, Item { var: "VICTORY_CARD_STEPS", label: "CARD STEPS", values: STAGES, live: false }, Item { var: "VICTORY_INDIRECT_BATCH", label: "INDIRECT BATCH", values: STAGES, live: false }, Item { var: "VICTORY_CARD_BUFFERS_MIN_KB", label: "CARD COMPARES FROM (KB)", values: &[("64", "64"), ("1024", "1024")], live: false }, - Item { var: "VICTORY_PORT_CONSTANTS", label: "CONSTANTS HEAP IN PLACE", values: UNSET_ON, live: false }, ]; /// The lines after the settings. const ACTIONS: [&str; 5] = diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index b5a7bb763..d963cc088 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -47,8 +47,68 @@ pub(super) fn on() -> bool { const MOST: usize = 8 << 20; /// Since the last frame-rate line: copies at their place, their bytes, those -/// out of a host copy, and texture copies out of one. -pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +/// out of a host copy, texture copies out of one, and constants read on the +/// card behind such copies ([`HostList::placed_constants`]). +pub(super) static STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// The destinations of copies at their place of this frame and the one +/// before (from, to, frame): constants read out of them are read on the card +/// ([`HostList::placed_constants`]). +static LATELY: Mutex<Vec<(usize, usize, u64)>> = Mutex::new(Vec::new()); +/// Whether [`LATELY`] may hold one (most constants are not looked up). +static ANY_LATELY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn note_placed(dst: usize, len: usize) { + // Bytes the card writes there and lands later: not constants read in + // place (`crate::port`) until they have landed. + crate::port::copy_bound(dst, len); + let frame = crate::frame::current(); + let mut lately = LATELY.lock().unwrap_or_else(|e| e.into_inner()); + lately.retain(|e| e.2 + 1 >= frame); + lately.push((dst, dst + len, frame)); + ANY_LATELY.store(true, Ordering::Relaxed); +} + +/// Whether a copy at its place lately wrote a byte of `[from, to)`. +fn placed_lately(from: usize, to: usize) -> bool { + if !ANY_LATELY.load(Ordering::Relaxed) { + return false; + } + let frame = crate::frame::current(); + let mut lately = LATELY.lock().unwrap_or_else(|e| e.into_inner()); + lately.retain(|e| e.2 + 1 >= frame); + if lately.is_empty() { + ANY_LATELY.store(false, Ordering::Relaxed); + } + lately.iter().any(|e| e.0 < to && from < e.1) +} + +/// The bytes of a buffer of ours that [`HostList::placed_constants`] copies +/// constants into, one after the other (each 256-aligned; a root view reads +/// 64 KiB, so a buffer holds sixteen of those). +const CONSTANTS_ROOM: u64 = 1 << 20; + +/// A descriptor slot pointed at constants on the card when the list is +/// submitted (the draw pointed it at upload memory when it was recorded). +struct PointSlot { + heap: usize, + index: u32, + buffer: ID3D12Resource, + gpu: u64, + len: u32, +} + +// SAFETY: D3D12 objects are free-threaded; the slot is written by the +// submitting thread. +unsafe impl Send for PointSlot {} +unsafe impl Sync for PointSlot {} + +impl PointSlot { + fn point(&self) { + // (A heap that is gone: nothing reads the slot.) + crate::descriptor::constant_slot(self.heap, self.index, &self.buffer, self.gpu, self.len); + } +} /// What the CPU does at submission for a copy at its place in a list. pub(super) struct Placed { @@ -109,22 +169,23 @@ pub(super) enum Waits { Yes, } -/// Whether a step of `runs` reads one of `ranges` on the CPU. -pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bool { - join_ranges(&mut ranges, []); - runs.iter().any(|list| { - list.deferred().copies.iter().any(|step| match step { - &Step::Copy(_, src, len) | &Step::Fill(_, src, len, _) => touches(&ranges, src, src + len), - Step::Texture(staging) => { - let (at, len) = staging.memory(); - touches(&ranges, at, at + len) - } - &Step::Plane((at, len), _) => touches(&ranges, at, at.saturating_add(len)), - Step::Host(_, (from, to)) => touches(&ranges, *from, *to), - Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len), - _ => false, - }) - }) +/// Whether `step` reads, on the CPU at submission, one of `ranges` (the +/// destinations of copies at their place that stand ahead of it in the +/// submission: a step that stands before such a copy never sees its bytes, +/// with the flights waited for or not, so it is not in their way). +pub(super) fn reads(step: &Step, ranges: &[(usize, usize)]) -> bool { + let meets = |from: usize, to: usize| from < to && ranges.iter().any(|r| r.0 < to && from < r.1); + match step { + &Step::Copy(_, src, len) | &Step::Fill(_, src, len, _) => meets(src, src.saturating_add(len)), + Step::Texture(staging) => { + let (at, len) = staging.memory(); + meets(at, at.saturating_add(len)) + } + &Step::Plane((at, len), _) => meets(at, at.saturating_add(len)), + &Step::Host(_, (from, to)) => meets(from, to), + Step::Placed(p) => p.from.is_some() && meets(p.src, p.src.saturating_add(p.len)), + _ => false, + } } /// Everything recorded so far is done, and seen, before what follows. @@ -225,7 +286,7 @@ impl HostList { from.refresh(self, src as u64, len as u64); let offset = from.offset(src as u64); if from.buffer.as_raw() == to.buffer.as_raw() { - let Some(between) = self.between(host, len as u64) else { + let Some(between) = self.between(host, len as u64, Kind::UavCopyAlias) else { return false; }; unsafe { @@ -248,6 +309,7 @@ impl HostList { STATS[0].fetch_add(1, Ordering::Relaxed); STATS[1].fetch_add(len as u64, Ordering::Relaxed); to.gpu_writes(self, dst as u64, len as u64); + note_placed(dst, len); let mut deferred = self.deferred(); deferred.copies.push(Step::Placed(Placed { dst, @@ -270,7 +332,7 @@ impl HostList { } let host = host()?; let from = shaders_own(src, len)?; - let between = self.between(host, len as u64)?; + let between = self.between(host, len as u64, Kind::UavTextureSupport)?; from.refresh(self, src as u64, len as u64); STATS[3].fetch_add(1, Ordering::Relaxed); // SAFETY: an open list; live buffers, ranges inside them. @@ -283,9 +345,82 @@ impl HostList { Some(between) } + /// Constants of `len` bytes at `src` that a copy at its place lately wrote + /// a byte of, read at this place of the list: a buffer of ours and the + /// card address they are at (256-aligned), copied there on the card out of + /// the host copy that holds them. `None`: read them as before, on the CPU + /// at submission (a fill). + /// + /// Why: with flights in the air that may write the copy's source or + /// destination, the copy is not put into title memory at submission + /// ([`Placed::prepare`]: it lands later), so a fill behind it that read it + /// on the CPU waited for those flights to land: 0.8 waits and 18.6 ms a + /// frame in a chase (run play-20261127-104020, "a step that reads where a + /// copy at its place writes"). Read here, on the card, the constants are + /// what the copy and every write ahead of them on the queue left there, + /// as for any view of a buffer's host copy; the title's own bytes around + /// them are brought up to date by the refresh, as for those + /// (`stale_under_flights` looks at it like at any other). + pub(crate) fn placed_constants(&self, src: usize, len: usize) -> Option<(ID3D12Resource, u64)> { + if !on() || len == 0 || !placed_lately(src, src + len) { + return None; + } + let size = (len as u64).next_multiple_of(256); + if size > CONSTANTS_ROOM { + return None; + } + let host = host()?; + let from = shaders_own(src, len)?; + let (start, span) = from.span(); + if (src as u64) < start || src as u64 + len as u64 > start + span { + return None; + } + let read = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let held = self.deferred().constants.clone(); + let (buffer, at, fresh) = match held { + Some((buffer, used)) if used + size <= CONSTANTS_ROOM => (buffer, used, false), + _ => (self.between(host, CONSTANTS_ROOM, Kind::UavPlacedConstants)?, 0, true), + }; + from.refresh(self, src as u64, len as u64); + // SAFETY: an open list; live buffers (the list keeps both), ranges + // inside them. A new buffer is in the common state and promoted by + // the copy; one used before was left readable below. + unsafe { + wait_for_all(host, &self.list); + if !fresh { + self.list.ResourceBarrier(&[transition(&buffer, read, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + self.list.CopyBufferRegion(&buffer, at, &from.buffer, from.offset(src as u64), len as u64); + self.list.ResourceBarrier(&[transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, read)]); + } + self.deferred().constants = Some((buffer.clone(), at + size)); + STATS[4].fetch_add(1, Ordering::Relaxed); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at; + Some((buffer, gpu)) + } + + /// [`HostList::placed_constants`] for a descriptor slot of a title heap + /// (heap address, slot) that the draw points at upload memory: the slot + /// is pointed at them when the list is submitted. Whether it was done. + pub(crate) fn place_constants_slot(&self, src: usize, len: usize, slot: (usize, u32)) -> bool { + let Some((buffer, gpu)) = self.placed_constants(src, len) else { + return false; + }; + let point = PointSlot { + heap: slot.0, + index: slot.1, + buffer, + gpu, + len: len as u32, + }; + self.defer_host(move || point.point()); + true + } + /// A buffer on the card for this recording alone. - fn between(&self, host: &Host, len: u64) -> Option<ID3D12Resource> { - let buffer = host.uav_buffer(len.next_multiple_of(1 << 16))?; + fn between(&self, host: &Host, len: u64, kind: Kind) -> Option<ID3D12Resource> { + let buffer = host.uav_buffer_for(len.next_multiple_of(1 << 16), kind)?; name(&buffer, || "bytes between copies".into()); self.keep(&buffer); Some(buffer) diff --git a/crates/victory-gpu/src/host/prefetch.rs b/crates/victory-gpu/src/host/prefetch.rs new file mode 100644 index 000000000..7da1b5e4f --- /dev/null +++ b/crates/victory-gpu/src/host/prefetch.rs @@ -0,0 +1,338 @@ +//! Pieces of copies in the card's memory that a flight's compare flags come +//! down at the flight's own end, in the same submission (`VICTORY_PREFETCH`, +//! on by default with the relay; `=0`: fetched by the landing, as before). +//! +//! Before, the thread that lands flights ([`relay`]) learned which pieces +//! differ only once the flight had run, then recorded a list of copies for +//! them, sent it and waited for the card again: 9-10 ms a frame in 8-9 such +//! waits, 32 MB a frame fetched (run 133409, 13:38), each landing (and so +//! every fence the title waits for behind it) a round trip later. +//! +//! Here the compare's list goes on: after the compare passes, a pass of +//! [`CARD_SPILL`] over the same pieces copies every piece the compare +//! flagged, whole (as the compare hashed it), into memory of ours in the +//! PC's memory, at a slot it takes with an atomic count, and notes the slot +//! beside the piece's result. When the flight has run, what it wrote is +//! there already: the landing merges it without asking the card for +//! anything. A piece without a slot (more were flagged than the memory +//! holds, a range that was not compared, a piece fetched because an +//! earlier fetch was torn) is fetched as before. +//! +//! Why the bytes are right. The pass runs on the drawing queue behind the +//! flight's lists and the compare, before anything sent later: it holds +//! what the flight ended with, and title bytes sent up with sends up to the +//! flight's own (`CardPlan::sent_as`), which is what the merge is told +//! (`fetched_after`): bytes sent up later are left out, as with a fetch. +//! Where several flights of a landing flagged a piece the last one's slot +//! is taken; where a later flight declared it and did not flag it, the +//! compare found it as an earlier one left it (it stores the hash it makes), +//! so the earlier slot holds the piece as it is, but for title bytes sent up +//! since, which are left out. No later flight can be at a piece while it +//! comes down: what came down is never torn (`torn`). + +use std::sync::atomic::{AtomicU32, AtomicU64}; + +use super::*; + +/// See the file. +pub(super) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_PREFETCH").is_none_or(|v| v != "0")) +} + +/// The pass: one group per piece of a compare pass, as [`CARD_COMPARE`] +/// cuts them. Its first thread reads the piece's result; a flagged piece +/// takes a slot (the dword at 0 counts them, also past `capacity`), and +/// the slot (1 on) or 0 goes into the header at the piece's place; then +/// the group copies the piece, 16 bytes a thread at a time. +pub(crate) const CARD_SPILL: &str = r#" +#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint local; // the first piece's place in the header, in dwords + uint capacity; // slots + uint header; // bytes before slot 0 +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer differs : register(u0); +RWByteAddressBuffer spill : register(u1); +groupshared uint slot; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { + if (thread == 0u) { + uint s = 0u; + if ((differs.Load(out_at + id.x * 4u) & 1u) != 0u) { + uint n; + spill.InterlockedAdd(0u, 1u, n); + s = n < capacity ? n + 1u : 0u; + } + spill.Store(4u + (local + id.x) * 4u, s); + slot = s; + } + GroupMemoryBarrierWithGroupSync(); + if (slot == 0u) return; + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint base = header + (slot - 1u) * 65792u; + [loop] + for (uint at = lo + thread * 16u; at < hi; at += 1024u) { + spill.Store4(base + (at - lo), now.Load4(at)); + } +} +"#; + +/// Bytes a slot takes: a piece widened to 16 bytes at both ends, with room. +pub(crate) const STRIDE: u64 = 65536 + 256; + +/// Slots a plan's memory is made with at first, the fewest and the most. +const FIRST: u32 = 64; +const FEWEST: u32 = 16; +const MOST: u32 = 2048; + +/// Since the last frame-rate line: pieces landed from a slot and their +/// bytes; flagged pieces fetched for want of one; plans whose flagged +/// pieces did not all find a slot; pieces the passes copied down. +static STATS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// Slots the next plan's memory is to have. +static WANT: AtomicU32 = AtomicU32::new(FIRST); + +struct Pipeline { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +// SAFETY: D3D12 objects, free-threaded. +unsafe impl Send for Pipeline {} +unsafe impl Sync for Pipeline {} + +/// Memory of ours: buffer, mapping, bytes. +struct Memory(ID3D12Resource, usize, u64); + +// SAFETY: a buffer and its persistent mapping; used by one plan at a time. +unsafe impl Send for Memory {} + +/// Memory given back by plans done with, for the next ones. +static POOL: Mutex<Vec<Memory>> = Mutex::new(Vec::new()); + +/// At most this many kept in [`POOL`]. +const KEPT: usize = 48; + +/// A plan's slots: where its flagged pieces came down. +pub(super) struct Spill { + memory: Memory, + /// The bytes before slot 0. + header: u64, + capacity: u32, + /// The plan's results in `differs`: the first dword and how many. + base: u32, + dwords: u32, +} + +impl Spill { + /// Where the piece whose compare result is `dword` came down (the first + /// byte [`crate::shadow::Shadow::card_hashed`] gives), if it did. + pub(super) fn slot(&self, dword: u32) -> Option<usize> { + let local = dword.checked_sub(self.base).filter(|&l| l < self.dwords)?; + // SAFETY: inside the header, which the pass (it has run) wrote. + let s = unsafe { ((self.memory.1 + 4 + 4 * local as usize) as *const u32).read_volatile() }; + (s != 0 && s <= self.capacity).then(|| self.memory.1 + self.header as usize + (s as usize - 1) * STRIDE as usize) + } + + /// The pieces flagged, also those past the slots. + fn flagged(&self) -> u32 { + // SAFETY: the count, at the mapping's start. + unsafe { (self.memory.1 as *const u32).read_volatile() } + } +} + +fn pipeline(host: &Host) -> Option<&'static Pipeline> { + static MADE: OnceLock<Option<Pipeline>> = OnceLock::new(); + MADE.get_or_init(|| { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the calls; the blob's + // own bytes; the root signature is inside the shader. + let made = unsafe { + (|| -> windows::core::Result<Pipeline> { + D3DCompile( + CARD_SPILL.as_ptr().cast(), + CARD_SPILL.len(), + windows::core::s!("card spill"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 1 << 15, + 0, + &mut code, + None, + )?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = host.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Pipeline { root, pso }) + })() + }; + match made { + Ok(p) => Some(p), + Err(e) => { + tracing::warn!(error = %e, "no pass to bring flagged pieces down with their flight: the landings fetch them (VICTORY_PREFETCH)"); + None + } + } + }) + .as_ref() +} + +/// Memory of at least `bytes`, from the pool or new. +fn memory(host: &Host, bytes: u64) -> Option<Memory> { + { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + // The smallest that holds it. + let best = pool.iter().enumerate().filter(|(_, m)| m.2 >= bytes).min_by_key(|(_, m)| m.2).map(|(i, _)| i); + if let Some(i) = best { + return Some(pool.swap_remove(i)); + } + } + let size = bytes.next_multiple_of(1 << 20); + let (buffer, data) = host.shared_buffer_cpu(size)?; + name(&buffer, || "flagged pieces of copies in the card's memory, come down with their flight".into()); + Some(Memory(buffer, data as usize, size)) +} + +/// After the compare passes of a plan, on its open list (the compare's): +/// the pass over the pieces of `compares` (of the plan's `ranges`) that are +/// landed. `differs` is the +/// compare's results buffer; the plan's results are its dwords `base` to +/// `end`. `None` if there is nothing to do or no memory. +/// +/// # Safety +/// The list is open and records the compare of `ranges` just before; +/// live buffers. +pub(super) unsafe fn record( + host: &Host, + list: &ID3D12GraphicsCommandList, + ranges: &[CardRange], + compares: &[CardCompare], + differs: &ID3D12Resource, + base: u32, + end: u32, +) -> Option<Spill> { + let passes: Vec<&CardCompare> = compares.iter().filter(|c| !ranges[c.range].picked).collect(); + if passes.is_empty() || end <= base { + return None; + } + let pipeline = pipeline(host)?; + let dwords = end - base; + let header = (4 + 4 * u64::from(dwords)).next_multiple_of(256); + let capacity = WANT.load(Ordering::Relaxed); + let memory = memory(host, header + u64::from(capacity) * STRIDE)?; + // As many slots as the memory holds. + let capacity = (((memory.2 - header) / STRIDE) as u32).min(MOST); + // SAFETY: the memory is ours alone (the plan that had it is done). + unsafe { (memory.1 as *mut u32).write_volatile(0) }; + // SAFETY: the caller's. + unsafe { + // What the compare wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&pipeline.root); + list.SetPipelineState(&pipeline.pso); + list.SetComputeRootUnorderedAccessView(2, differs.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, memory.0.GetGPUVirtualAddress()); + for pass in passes { + let r = &ranges[pass.range]; + if !r.shadow.card_has_before() { + continue; + } + let size = r.shadow.card_hash_size(); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + const MOST_GROUPS: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + let mut done = 0; + while done < pass.span.pieces { + let n = (pass.span.pieces - done).min(MOST_GROUPS); + let at = pass.at + done; + let constants = + [pass.span.first + done, pass.span.skew, size as u32, n, at * 4, at - base, capacity, header as u32]; + list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + list.Dispatch(n, 1, 1); + done += n; + } + } + } + Some(Spill { memory, header, capacity, base, dwords }) +} + +/// The plan is done with (`Host::card_done`): its memory goes back, and the +/// next plans get as many slots as this one wanted, with room. +pub(super) fn give_back(spill: Spill) { + let flagged = spill.flagged(); + STATS[4].fetch_add(u64::from(flagged.min(spill.capacity)), Ordering::Relaxed); + if flagged > spill.capacity { + STATS[3].fetch_add(1, Ordering::Relaxed); + } + let wanted = (flagged + flagged / 4).next_power_of_two().clamp(FEWEST, MOST); + // Up at once, down slowly. + let _ = WANT.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |was| { + Some(if wanted >= was { wanted } else { (was - (was - wanted) / 8).max(FEWEST) }) + }); + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + if pool.len() < KEPT { + pool.push(spill.memory); + } +} + +/// A piece landed from a slot (`bytes` of it), or fetched for want of one. +pub(super) fn landed(from_slot: bool, bytes: u64) { + if from_slot { + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(bytes, Ordering::Relaxed); + } else { + STATS[2].fetch_add(1, Ordering::Relaxed); + } +} + +/// For the frame-rate line. +pub(super) fn log(frames: f64) { + let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if !on() || s.iter().all(|&v| v == 0.0) { + return; + } + tracing::info!( + "flagged pieces come down with their flight per frame (VICTORY_PREFETCH=1): {:.0} copied down by the card, {:.0} landed \ + from there ({:.1} MB) with no wait for the card, {:.0} fetched by the landing for want of a slot; {:.2} plans with more \ + flagged than slots ({} slots now)", + s[4], + s[0], + s[1] / (1 << 20) as f64, + s[2], + s[3], + WANT.load(Ordering::Relaxed), + ); +} diff --git a/crates/victory-gpu/src/host/render_trace.rs b/crates/victory-gpu/src/host/render_trace.rs new file mode 100644 index 000000000..f6aca1b21 --- /dev/null +++ b/crates/victory-gpu/src/host/render_trace.rs @@ -0,0 +1,232 @@ +//! A bounded capture in every build. The title's frame token, host list pointer, +//! recording ID and CPU clock let the command, queue and Present rows be joined. +//! GPU timestamps are in ticks. `execute` reports the queue's frequency and a +//! pair of GPU and CPU performance-counter timestamps for calibration. +//! Set `VICTORY_RENDER_TRACE` to a new file path, `VICTORY_RENDER_TRACE_AT` to +//! the start time in seconds (default 60), and `VICTORY_RENDER_TRACE_SECONDS` +//! to the duration (default 3). The extra GPU queries affect timings during +//! capture. Use `list_trace_lost` and `capture_loss` when checking coverage. + +use std::fmt::Write as _; +use std::io::{BufWriter, Write}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::mpsc::{RecvTimeoutError, SyncSender, TrySendError, sync_channel}; +use std::time::Duration; + +use super::{now_us, thread_id}; +use windows::Win32::Graphics::Direct3D12::{ID3D12CommandList, ID3D12CommandQueue}; +use windows::core::Interface; + +struct Capture { + start_us: u64, + end_us: u64, + sender: SyncSender<Output>, +} + +enum Output { + Lines(String), + #[cfg(test)] + Flush(std::sync::mpsc::Sender<()>), +} + +static DROPPED: AtomicU64 = AtomicU64::new(0); + +fn capture() -> Option<&'static Capture> { + static CAPTURE: OnceLock<Option<Capture>> = OnceLock::new(); + CAPTURE + .get_or_init(|| { + let path = + std::env::var_os("VICTORY_RENDER_TRACE").filter(|p| !p.is_empty() && p != "0")?; + let seconds = |key, default| { + std::env::var(key) + .ok() + .and_then(|s| s.parse::<u64>().ok()) + .unwrap_or(default) + }; + let start_us = seconds("VICTORY_RENDER_TRACE_AT", 60).saturating_mul(1_000_000); + let end_us = start_us.saturating_add( + seconds("VICTORY_RENDER_TRACE_SECONDS", 3).clamp(1, 30) * 1_000_000, + ); + let file = match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + { + Ok(file) => file, + Err(error) => { + tracing::warn!(?path, %error, "could not open VICTORY_RENDER_TRACE"); + return None; + } + }; + let (sender, receiver) = sync_channel::<Output>(1024); + let worker = std::thread::Builder::new() + .name("victory-render-trace".into()) + .spawn(move || -> std::io::Result<()> { + let mut out = BufWriter::with_capacity(256 * 1024, file); + writeln!( + out, + "# VIctory render trace v1, tab-separated event and key=value fields" + )?; + loop { + match receiver.recv_timeout(Duration::from_millis(100)) { + Ok(Output::Lines(batch)) => out.write_all(batch.as_bytes())?, + #[cfg(test)] + Ok(Output::Flush(done)) => { + out.flush()?; + let _ = done.send(()); + } + Err(RecvTimeoutError::Timeout) => { + let dropped = DROPPED.swap(0, Relaxed); + if dropped != 0 { + writeln!(out, "capture_loss\tbatches={dropped}")?; + } + out.flush()?; + } + Err(RecvTimeoutError::Disconnected) => return out.flush(), + } + } + }); + match worker { + Ok(_) => { + tracing::info!(?path, start_us, end_us, "VIctory render trace enabled"); + Some(Capture { + start_us, + end_us, + sender, + }) + } + Err(error) => { + tracing::warn!(%error, "could not start the render trace writer"); + None + } + } + }) + .as_ref() +} + +pub(crate) fn active() -> bool { + capture().is_some_and(|c| (c.start_us..c.end_us).contains(&now_us())) +} + +/// Used also for GPU results that arrive after the capture window. +pub(super) fn write(batch: String) { + if let Some(c) = capture() { + match c.sender.try_send(Output::Lines(batch)) { + Ok(()) => {} + Err(TrySendError::Full(_)) => { + DROPPED.fetch_add(1, Relaxed); + } + Err(TrySendError::Disconnected(_)) => { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| tracing::warn!("the render trace writer stopped")); + } + } + } +} + +#[cfg(test)] +pub(super) fn flush() { + if let Some(c) = capture() { + let (done, wait) = std::sync::mpsc::channel(); + c.sender.send(Output::Flush(done)).unwrap(); + wait.recv_timeout(Duration::from_secs(1)).unwrap(); + } +} + +pub(crate) fn event(kind: &str, fields: impl std::fmt::Display) { + write(format!( + "{kind}\tcpu_us={}\tthread={}\tframe={}\t{fields}\n", + now_us(), + thread_id(), + crate::frame::current() + )); +} + +pub(crate) fn execute( + queue: &ID3D12CommandQueue, + lists: &[Option<ID3D12CommandList>], + signal: Option<(usize, u64)>, +) { + static NEXT: AtomicU64 = AtomicU64::new(1); + let batch = NEXT.fetch_add(1, Relaxed); + let mut gpu = 0; + let mut qpc = 0; + // SAFETY: plain clock queries on a live queue. + let (hz, kind) = unsafe { + let _ = queue.GetClockCalibration(&mut gpu, &mut qpc); + ( + queue.GetTimestampFrequency().unwrap_or(0), + queue.GetDesc().Type.0, + ) + }; + let at = now_us(); + let mut rows = format!( + "execute\tbatch={batch}\tcpu_us={at}\tthread={}\tframe={}\tqueue={:#x}\tqueue_type={kind}\tgpu_tick={gpu}\tqpc={qpc}\tgpu_hz={hz}\tfence={signal:?}\n", + thread_id(), + crate::frame::current(), + queue.as_raw() as usize + ); + for (index, list) in lists.iter().enumerate() { + if let Some(list) = list { + let _ = writeln!( + rows, + "execute_list\tbatch={batch}\tcpu_us={at}\tindex={index}\tlist={:#x}", + list.as_raw() as usize + ); + } + } + write(rows); +} + +/// A command's actual host arguments. The pipeline's readable name is held +/// separately in the GPU timing module. +#[derive(Clone, Copy)] +pub(crate) struct Command(pub &'static str, pub [i64; 5]); + +/// The translated draw/dispatch can return before there is a GPU command. +pub(crate) struct DrawCall { + start: Option<u64>, + list: usize, + pipeline: usize, + command: Command, +} + +impl DrawCall { + pub(crate) fn begin(list: &super::HostList, pipeline: usize, command: Command) -> Self { + Self { + start: active().then(now_us), + list: list.list.as_raw() as usize, + pipeline, + command, + } + } + + pub(crate) fn recorded(mut self) { + if let Some(start) = self.start.take() { + let duration_us = now_us().saturating_sub(start); + if duration_us >= 500 { + self.report("slow_draw_translation", start, duration_us); + } + } + } + + fn report(&self, event_name: &str, start: u64, duration_us: u64) { + let Command(op, args) = self.command; + event( + event_name, + format_args!( + "list={:#x}\tpipeline={:#x}\top={op}\targs={args:?}\tstart_us={start}\tduration_us={duration_us}", + self.list, self.pipeline + ), + ); + } +} + +impl Drop for DrawCall { + fn drop(&mut self) { + if let Some(start) = self.start { + self.report("draw_not_recorded", start, now_us().saturating_sub(start)); + } + } +} diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index a397db809..a48a9ee22 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -27,9 +27,27 @@ pub(super) fn own() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_OWN").is_none_or(|v| v != "0")) } +/// Whether fragmented 4-byte-aligned sends go through one bulk upload copy into a +/// device-local staging buffer and the `BULK_SCATTER` compute shader, with +/// `SCATTER` reading from device-local memory instead of over PCIe +/// (`VICTORY_BULK_SCATTER`, on by default; `=0`: `CopyBufferRegion` + PCIe +/// `SCATTER`). +fn bulk_scatter_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| own() && std::env::var_os("VICTORY_BULK_SCATTER").is_none_or(|v| v != "0")) +} + /// Runs up to this many bytes go as pairs. const SHORT: usize = 256; +/// A contiguous send of at least one write-watch block goes directly to +/// its destination. Staging it would use a copy operation anyway +/// and add a scatter over the whole block. +const DIRECT_BYTES: usize = 64 << 10; + +/// Maximum dwords copied per `BULK_SCATTER` threadgroup (64 threads × 4 dwords). +const TILE_DWORDS: u32 = 256; + /// Whether a run of `len` bytes at offset `at` of a copy goes as pairs. fn short(at: usize, len: usize) -> bool { len <= SHORT && at % 4 == 0 && len % 4 == 0 @@ -60,6 +78,48 @@ pub(crate) fn words_under() -> bool { *ON.get_or_init(|| own() && std::env::var_os("VICTORY_UNDER_WORDS").is_none_or(|v| v != "0")) } +/// Compiles `source` with `D3DCOMPILE_OPTIMIZATION_LEVEL3` (`1 << 15`). +fn compile_opt( + source: &str, + entry: windows::core::PCSTR, + target: windows::core::PCSTR, +) -> windows::core::Result<Vec<u8>> { + use windows::Win32::Graphics::Direct3D::Fxc::{D3DCOMPILE_OPTIMIZATION_LEVEL3, D3DCompile}; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("victory-send"), + None, + None, + entry, + target, + D3DCOMPILE_OPTIMIZATION_LEVEL3, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts(errors.GetBufferPointer().cast::<u8>(), errors.GetBufferSize()) + }; + tracing::warn!("a send shader of ours: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes. + let bytes = unsafe { std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()) }; + Ok(bytes.to_vec()) +} + const SCATTER: &str = r#" #define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" cbuffer Part : register(b0) { uint at; uint count; }; @@ -74,42 +134,92 @@ void main(uint3 id : SV_DispatchThreadID) { } "#; +const BULK_SCATTER: &str = r#" +#define RS "RootConstants(num32BitConstants=1, b0), SRV(t0), UAV(u0)" +cbuffer Part : register(b0) { uint tiles_at; }; +ByteAddressBuffer vram : register(t0); +RWByteAddressBuffer card : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) { + uint3 t = vram.Load3(tiles_at + gid.x * 12u); + uint dst = t.x; + uint src = t.y; + uint dwords = t.z; + if (((dst | src) & 15u) == 0u) { + uint vecs = dwords >> 2; + if (tid.x < vecs) { + card.Store4(dst + tid.x * 16u, vram.Load4(src + tid.x * 16u)); + } + uint tail = vecs << 2; + if (tail + tid.x < dwords) { + uint off = (tail + tid.x) * 4u; + card.Store(dst + off, vram.Load(src + off)); + } + } else { + for (uint i = tid.x; i < dwords; i += 64u) { + uint off = i * 4u; + card.Store(dst + off, vram.Load(src + off)); + } + } +} +"#; + struct Pass { root: ID3D12RootSignature, pso: ID3D12PipelineState, } +fn make_pass(device: &ID3D12Device, source: &str, label: &'static str) -> Option<Pass> { + let code = compile_opt(source, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; + // SAFETY: the code lives through the calls; the root signature is + // inside it. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &code).ok()?; + let pso: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .ok()?; + name(&pso, || label.into()); + Some(Pass { root, pso }) + } +} + fn pass(host: &Host) -> Option<&'static Pass> { static PASS: OnceLock<Option<Pass>> = OnceLock::new(); - PASS.get_or_init(|| { - let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; - // SAFETY: the code lives through the calls; the root signature is - // inside it. - unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?; - let pso: ID3D12PipelineState = host - .device - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: code.as_ptr().cast(), - BytecodeLength: code.len(), - }, - ..Default::default() - }) - .ok()?; - name(&pso, || "victory: changed words sent to the card".into()); - Some(Pass { root, pso }) - } - }) - .as_ref() + PASS.get_or_init(|| make_pass(&host.device, SCATTER, "victory: changed words sent to the card")) + .as_ref() } -/// Memory a submission's sends come from, mapped. +fn bulk_pass(host: &Host) -> Option<&'static Pass> { + static PASS: OnceLock<Option<Pass>> = OnceLock::new(); + PASS.get_or_init(|| make_pass(&host.device, BULK_SCATTER, "victory: bulk scatter to the card")) + .as_ref() +} + +/// Device-local staging buffer used as the single DMA target before +/// `BULK_SCATTER` and `SCATTER` read from VRAM. +struct VramBuffer { + buffer: ID3D12Resource, + size: u64, +} + +// SAFETY: a D3D12 resource is free-threaded with one owner while in use/pooled. +unsafe impl Send for VramBuffer {} + +/// Memory a submission's sends come from, mapped, plus optional device-local +/// staging for bulk scatter. pub(super) struct Memory { buffer: ID3D12Resource, data: usize, size: u64, + vram: Option<VramBuffer>, } // SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner. @@ -117,12 +227,16 @@ unsafe impl Send for Memory {} /// What submissions that have run gave back. static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new()); +/// Device-local staging buffers returned after submissions have run. +static SPARE_VRAM: Mutex<Vec<VramBuffer>> = Mutex::new(Vec::new()); /// At most this much is kept (of the card's memory, with [`on_card`]). fn kept() -> u64 { if on_card() { 256 << 20 } else { 768 << 20 } } +const KEPT_VRAM: u64 = 512 << 20; + /// Whether the memory lies in the card's memory, written by the CPU through /// the bus (`VICTORY_SEND_BAR=1`): the copies on the card's drawing queue, which /// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of @@ -156,11 +270,34 @@ fn memory(host: &Host, size: u64) -> Option<Memory> { buffer, data: data as usize, size, + vram: None, }) } +fn vram_buffer(host: &Host, size: u64) -> Option<VramBuffer> { + { + let mut spare = SPARE_VRAM.lock().unwrap_or_else(|e| e.into_inner()); + let fit = spare.iter().enumerate().filter(|(_, v)| v.size >= size).min_by_key(|(_, v)| v.size).map(|(i, _)| i); + if let Some(i) = fit { + return Some(spare.swap_remove(i)); + } + } + let size = size.max(8 << 20).next_power_of_two(); + let buffer = host.uav_buffer_for(size, Kind::UavSend)?; + name(&buffer, || "bytes a submission scatters on the card".into()); + Some(VramBuffer { buffer, size }) +} + /// The submission has run. -pub(super) fn give_back(memory: Memory) { +pub(super) fn give_back(mut memory: Memory) { + if let Some(vram) = memory.vram.take() { + let mut spare_vram = SPARE_VRAM.lock().unwrap_or_else(|e| e.into_inner()); + spare_vram.push(vram); + spare_vram.sort_by_key(|v| std::cmp::Reverse(v.size)); + while spare_vram.iter().map(|v| v.size).sum::<u64>() > KEPT_VRAM { + spare_vram.remove(0); + } + } let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); spare.push(memory); spare.sort_by_key(|m| std::cmp::Reverse(m.size)); @@ -170,20 +307,96 @@ pub(super) fn give_back(memory: Memory) { } /// Since the last frame-rate line: bytes copied, runs copied, words stored, -/// microseconds of taking them out of the CPU sides. -pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +/// microseconds of taking them out of the CPU sides, direct copy bytes and +/// staged bytes (including tile and pair records). +pub(super) static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; -/// One copy's sends: ranges copied (offset in the copy, in the memory, -/// bytes), and its pairs (where in the memory, how many). +/// One tile descriptor read by `BULK_SCATTER`. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Tile { + dst: u32, + src: u32, + dwords: u32, +} + +const TILE_STRIDE: usize = std::mem::size_of::<Tile>(); + +/// Splits a 4-byte-aligned run `[dst, dst + len)` from `src` into fixed-max-size +/// tiles (`TILE_DWORDS`), emitting a tiny head tile when `dst` is not 16-byte +/// aligned so all body tiles hit the `uint4` vectorized path. +fn push_tiles(tiles: &mut Vec<Tile>, mut dst: u32, mut src: u32, mut len: u32) { + debug_assert_eq!(dst % 4, 0); + debug_assert_eq!(src % 4, 0); + debug_assert_eq!(len % 4, 0); + if len == 0 { + return; + } + let misalign = dst & 15; + if misalign != 0 && (src & 15) == misalign { + let head = (16 - misalign).min(len); + tiles.push(Tile { + dst, + src, + dwords: head / 4, + }); + dst += head; + src += head; + len -= head; + } + let mut dwords = len / 4; + while dwords > 0 { + let n = dwords.min(TILE_DWORDS); + tiles.push(Tile { dst, src, dwords: n }); + let bytes = n * 4; + dst += bytes; + src += bytes; + dwords -= n; + } +} + +/// One copy's sends: fallback `CopyBufferRegion` ranges (offset in the copy, +/// in the upload memory, bytes), `BULK_SCATTER` tiles (offset in VRAM buffer, +/// count), `SCATTER` pairs (offset in buffer, count), and bulk run count. struct Copy { runs: Vec<(usize, u64, usize)>, + tiles: (u64, u32), pairs: (u64, u32), + bulk_runs: u64, +} + +/// Runs of a copy's sends joined into one copy each where one ends exactly +/// where the next begins, on the card side and in the memory alike (never +/// across a gap: bytes between two runs may be what shaders wrote on the +/// card). `VICTORY_BATCH_COPIES=0`: as made. +pub(crate) fn batch_copies_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BATCH_COPIES").is_none_or(|v| v != "0")) +} + +/// `runs` (card offset, memory offset, bytes) with adjacent ones joined +/// ([`batch_copies_on`]). +fn joined_runs(runs: &[(usize, u64, usize)]) -> Vec<(usize, u64, usize)> { + let mut out: Vec<(usize, u64, usize)> = Vec::with_capacity(runs.len()); + for &(a, from, n) in runs { + if batch_copies_on() + && let Some(last) = out.last_mut() + && last.0 + last.2 == a + && last.1 + last.2 as u64 == from + { + last.2 += n; + continue; + } + out.push((a, from, n)); + } + out } /// Where a submission's bytes are taken to. pub(super) struct Own { memory: Memory, copies: Vec<Copy>, + vram_bytes: u64, } /// Runs whose pairs are one piece of work. @@ -193,44 +406,161 @@ const RUNS_AT_A_TIME: usize = 4096; pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> { let began = std::time::Instant::now(); pass(host)?; - // Runs of whole words of the copy: only those are pairs. (A byte beside - // them in a word may be the card's.) - let short = |&(a, b): &(usize, usize)| short(a, b - a); - let mut at = 0u64; + let bulk_scatter = bulk_scatter_on() && bulk_pass(host).is_some(); + take_with(host, dirty, bulk_scatter, began) +} + +fn take_with( + host: &Host, + dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)], + bulk_scatter: bool, + began: std::time::Instant, +) -> Option<Own> { + let mut vram_at = 0u64; + let mut unaligned_at = 0u64; let mut copies = Vec::with_capacity(dirty.len()); - for (_, ranges) in dirty { + let mut all_tiles: Vec<Tile> = Vec::new(); + let mut tile_slices: Vec<(usize, usize, u64)> = Vec::new(); + // (src_ptr, dst_rel_offset, len) + let mut bulk_moves: Vec<(usize, u64, usize)> = Vec::new(); + let mut short_ranges: Vec<(usize, usize)> = Vec::new(); + // (from_ptr, short_slice_start..short_slice_end, dst_rel_offset) + let mut pending_work: Vec<(usize, std::ops::Range<usize>, u64)> = Vec::new(); + let mut total_words = 0u64; + + for (shadow, ranges) in dirty { + let from = shadow.card_data() as usize; let mut runs = Vec::new(); - for &(a, b) in ranges.iter().filter(|r| !short(r)) { - runs.push((a, at, b - a)); - at += ((b - a) as u64).next_multiple_of(16); + let mut words = 0usize; + let mut bulk_runs = 0u64; + let tiles_start = all_tiles.len(); + let work_start = pending_work.len(); + let mut chunk_start = short_ranges.len(); + let mut chunk_words = 0usize; + let mut pair_rel = 0u64; + + for &(a, b) in ranges { + let len = b - a; + if len == 0 { + continue; + } + if short(a, len) { + short_ranges.push((a, b)); + let w = len / 4; + words += w; + chunk_words += w; + if short_ranges.len() - chunk_start == RUNS_AT_A_TIME { + pending_work.push((from, chunk_start..short_ranges.len(), pair_rel)); + pair_rel += chunk_words as u64 * 8; + chunk_start = short_ranges.len(); + chunk_words = 0; + } + } else if bulk_scatter && len < DIRECT_BYTES && a % 4 == 0 && len % 4 == 0 { + // Keep src mod 16 equal to dst mod 16 so body tiles are 16-byte aligned. + let src_off = vram_at + (a & 15) as u64; + vram_at = (src_off + len as u64).next_multiple_of(16); + bulk_runs += 1; + bulk_moves.push((from + a, src_off, len)); + push_tiles(&mut all_tiles, a as u32, src_off as u32, len as u32); + } else { + runs.push((a, unaligned_at, len)); + unaligned_at += (len as u64).next_multiple_of(16); + } } - let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum(); - copies.push(Copy { runs, pairs: (at, words as u32) }); - at += (words as u64 * 8).next_multiple_of(16); + if chunk_words > 0 { + pending_work.push((from, chunk_start..short_ranges.len(), pair_rel)); + } + + let tile_count = (all_tiles.len() - tiles_start) as u32; + let tiles = if tile_count > 0 { + let off = vram_at; + vram_at += (u64::from(tile_count) * TILE_STRIDE as u64).next_multiple_of(16); + tile_slices.push((tiles_start, all_tiles.len(), off)); + (off, tile_count) + } else { + (0, 0) + }; + + let pairs = if words > 0 { + let off = vram_at; + vram_at += (words as u64 * 8).next_multiple_of(16); + for w in &mut pending_work[work_start..] { + w.2 += off; + } + total_words += words as u64; + (off, words as u32) + } else { + (0, 0) + }; + + copies.push(Copy { + runs, + tiles, + pairs, + bulk_runs, + }); } - if at == 0 { + + let vram_bytes = if bulk_scatter { vram_at } else { 0 }; + let total_upload = vram_at + unaligned_at; + if total_upload == 0 { return None; } - let memory = memory(host, at)?; - let mut moves: Vec<(usize, usize, usize)> = Vec::new(); - let mut work: Vec<(usize, &[(usize, usize)], usize)> = Vec::new(); - for ((shadow, ranges), copy) in dirty.iter().zip(&copies) { - let from = shadow.card_data() as usize; - moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n))); - // (80,000 runs of some words a frame: in pieces of work.) - let mut to = memory.data + copy.pairs.0 as usize; - for ranges in ranges.chunks(RUNS_AT_A_TIME) { - let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum(); - if words > 0 { - work.push((from, ranges, to)); - to += words * 8; + + let vram = if bulk_scatter && vram_bytes > 0 { + if vram_bytes > u32::MAX as u64 { + return take_with(host, dirty, false, began); + } + match vram_buffer(host, vram_bytes) { + Some(v) => Some(v), + None => return take_with(host, dirty, false, began), + } + } else { + None + }; + + let mut memory = memory(host, total_upload)?; + memory.vram = vram; + + if vram_at > 0 && unaligned_at > 0 { + for copy in &mut copies { + for run in &mut copy.runs { + run.1 += vram_at; } } } + + for (start, end, off) in tile_slices { + let slice = &all_tiles[start..end]; + // SAFETY: `memory.data` has at least `total_upload` bytes and `off` + // reserves `slice.len() * TILE_STRIDE` disjoint bytes inside `[0..vram_at)`. + unsafe { + std::ptr::copy_nonoverlapping( + slice.as_ptr().cast::<u8>(), + (memory.data + off as usize) as *mut u8, + std::mem::size_of_val(slice), + ); + } + } + + let fallback_runs: usize = copies.iter().map(|c| c.runs.len()).sum(); + let mut moves: Vec<(usize, usize, usize)> = Vec::with_capacity(bulk_moves.len() + fallback_runs); + moves.extend( + bulk_moves + .into_iter() + .map(|(src, off, len)| (src, memory.data + off as usize, len)), + ); + for ((shadow, _), copy) in dirty.iter().zip(&copies) { + if !copy.runs.is_empty() { + let from = shadow.card_data() as usize; + moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n))); + } + } + let one = |i: usize| { - let (from, ranges, to) = work[i]; - let mut to = to as *mut [u32; 2]; - for &(a, b) in ranges.iter().filter(|r| short(r)) { + let (from, ref range_idx, to_off) = pending_work[i]; + let mut to = (memory.data + to_off as usize) as *mut [u32; 2]; + for &(a, b) in &short_ranges[range_idx.clone()] { for offset in (a..b).step_by(4) { // SAFETY: inside the copy's mapping (its CPU side, which // the thread that asked, and waits, alone writes in these @@ -244,13 +574,21 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us } } }; - crate::land::each_under(work.len(), &one); + crate::land::each_under(pending_work.len(), &one); + STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed); STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed); - STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed); + STATS[2].fetch_add(total_words, Ordering::Relaxed); + STATS[4].fetch_add(copies.iter().flat_map(|copy| ©.runs).map(|run| run.2 as u64).sum(), Ordering::Relaxed); + STATS[5].fetch_add(vram_bytes, Ordering::Relaxed); crate::shadow::copy_all(moves); STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); - Some(Own { memory, copies }) + + Some(Own { + memory, + copies, + vram_bytes, + }) } impl Own { @@ -267,41 +605,82 @@ impl Own { dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)], looked: impl Fn(&Shadow) -> bool, ) { + let common = D3D12_RESOURCE_STATE_COMMON; let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; let write = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; let dest = D3D12_RESOURCE_STATE_COPY_DEST; let (mut first, mut last) = (Vec::new(), Vec::new()); + let (mut made, mut recorded) = (0u64, 0u64); + + if let Some(vram) = &self.memory.vram + && self.vram_bytes > 0 + { + recorded += 1; + // SAFETY: the caller's; live buffers, range inside both. + unsafe { list.CopyBufferRegion(&vram.buffer, 0, &self.memory.buffer, 0, self.vram_bytes) }; + first.push(transition(&vram.buffer, dest, read)); + last.push(transition(&vram.buffer, read, common)); + } + for ((shadow, _), copy) in dirty.iter().zip(&self.copies) { - for &(a, from, n) in ©.runs { + made += copy.runs.len() as u64 + copy.bulk_runs; + for (a, from, n) in joined_runs(©.runs) { + recorded += 1; // SAFETY: the caller's; live buffers, ranges inside them. unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) }; } let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest); - if copy.pairs.1 > 0 { + let uav_writes = copy.tiles.1 > 0 || copy.pairs.1 > 0; + if uav_writes { if let Some(was) = state { first.push(transition(&shadow.buffer, was, write)); } state = Some(write); } - let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let hashed = shadow.card_has_before(); if let Some(was) = state && hashed - && (!copy.runs.is_empty() || copy.pairs.1 > 0) + && (!copy.runs.is_empty() || uav_writes) { last.push(transition(&shadow.buffer, was, read)); } } + // SAFETY: the caller's; live objects. unsafe { if !first.is_empty() { list.ResourceBarrier(&first); } + let srv_gpu = self + .memory + .vram + .as_ref() + .map_or_else(|| self.memory.buffer.GetGPUVirtualAddress(), |v| v.buffer.GetGPUVirtualAddress()); + if let Some(bulk) = bulk_pass(host) + && self.copies.iter().any(|c| c.tiles.1 > 0) + { + list.SetComputeRootSignature(&bulk.root); + list.SetPipelineState(&bulk.pso); + list.SetComputeRootShaderResourceView(1, srv_gpu); + for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.tiles.1 > 0) { + list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress()); + let (at, count) = copy.tiles; + let mut done = 0u32; + while done < count { + let n = (count - done).min(D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION); + let constants = [at as u32 + done * TILE_STRIDE as u32]; + list.SetComputeRoot32BitConstants(0, 1, constants.as_ptr().cast(), 0); + list.Dispatch(n, 1, 1); + done += n; + } + } + } if let Some(pass) = pass(host) && self.copies.iter().any(|c| c.pairs.1 > 0) { list.SetComputeRootSignature(&pass.root); list.SetPipelineState(&pass.pso); - list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView(1, srv_gpu); for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) { list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress()); const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; @@ -320,6 +699,7 @@ impl Own { list.ResourceBarrier(&last); } } + super::gpu_time::count_sent_runs(made, recorded); } /// The memory, to be kept until the submission has run. @@ -327,3 +707,277 @@ impl Own { self.memory } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tiles_split_and_align_body_chunks() { + let mut tiles = Vec::new(); + // 16-byte aligned exact multiple of TILE_DWORDS (1024 B) + push_tiles(&mut tiles, 0x2000, 0x1000, 2048); + assert_eq!( + tiles, + vec![ + Tile { dst: 0x2000, src: 0x1000, dwords: 256 }, + Tile { dst: 0x2400, src: 0x1400, dwords: 256 }, + ] + ); + + // 4-byte aligned, non-16-byte aligned start: emits 3-dword head tile, + // then 16-byte-aligned body tile(s). + tiles.clear(); + push_tiles(&mut tiles, 0x104, 0x4004, 260); + assert_eq!( + tiles, + vec![ + Tile { dst: 0x104, src: 0x4004, dwords: 3 }, + Tile { dst: 0x110, src: 0x4010, dwords: 62 }, + ] + ); + let total_bytes: u32 = tiles.iter().map(|t| t.dwords * 4).sum(); + assert_eq!(total_bytes, 260); + for t in &tiles[1..] { + assert_eq!(t.dst & 15, 0); + assert_eq!(t.src & 15, 0); + } + + // Crosses multiple tiles with non-zero tail dwords. + tiles.clear(); + push_tiles(&mut tiles, 0x8, 0x8, 2500); + assert_eq!(tiles[0], Tile { dst: 0x8, src: 0x8, dwords: 2 }); + assert_eq!(tiles[1], Tile { dst: 0x10, src: 0x10, dwords: 256 }); + assert_eq!(tiles[2], Tile { dst: 0x410, src: 0x410, dwords: 256 }); + assert_eq!(tiles[3], Tile { dst: 0x810, src: 0x810, dwords: 111 }); + assert_eq!(tiles.iter().map(|t| t.dwords * 4).sum::<u32>(), 2500); + } + + #[test] + fn shaders_compile_with_optimization_level3() { + let scatter = compile_opt(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")); + assert!(scatter.is_ok(), "SCATTER failed to compile: {scatter:?}"); + assert!(!scatter.unwrap().is_empty()); + + let bulk = compile_opt(BULK_SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")); + assert!(bulk.is_ok(), "BULK_SCATTER failed to compile: {bulk:?}"); + assert!(!bulk.unwrap().is_empty()); + } + + fn test_device() -> Option<ID3D12Device> { + // SAFETY: plain DXGI/D3D12 device probing for unit test execution. + unsafe { + let mut device: Option<ID3D12Device> = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() + && let Some(d) = device + { + return Some(d); + } + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + device + } + } + + fn create_buffer( + device: &ID3D12Device, + heap_type: D3D12_HEAP_TYPE, + size: u64, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: heap_type, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut res: Option<ID3D12Resource> = None; + // SAFETY: plain committed buffer creation in tests. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut res) + .unwrap(); + } + res.unwrap() + } + + #[test] + fn bulk_scatter_and_scatter_roundtrip_on_gpu() { + let Some(device) = test_device() else { + return; + }; + let scatter_pass = make_pass(&device, SCATTER, "test scatter").unwrap(); + let bulk_pass = make_pass(&device, BULK_SCATTER, "test bulk scatter").unwrap(); + + const DST_SIZE: usize = 2 * DIRECT_BYTES; + let mut expected = vec![0xAAu8; DST_SIZE]; + // Unaligned-mod-16 long run (> SHORT) + let run1 = (0x104usize, 0x104usize + 260usize); + // 16-byte-aligned multi-tile run (> TILE_DWORDS * 4) with non-multiple-of-16 tail + let run2 = (0x1000usize, 0x1000usize + 2500usize); + // Short run via SCATTER pairs + let short_run = (0x20usize, 0x20usize + 16usize); + let direct_run = (DIRECT_BYTES, DST_SIZE); + + let mut fill_pattern = |range: (usize, usize), seed: u8| { + for (i, byte) in expected[range.0..range.1].iter_mut().enumerate() { + *byte = seed.wrapping_add((i * 13 + 7) as u8); + } + }; + fill_pattern(run1, 0x11); + fill_pattern(run2, 0x55); + fill_pattern(short_run, 0x99); + fill_pattern(direct_run, 0x37); + + // Pack upload buffer: [init_sentinel(8192) | bulk_payloads | tiles | pairs] + let mut upload_bytes = vec![0xAAu8; DST_SIZE]; + let mut at = 0usize; + let mut tiles = Vec::new(); + for &(a, b) in &[run1, run2] { + let len = b - a; + let src_off = at + (a & 15); + let need = src_off + len; + if upload_bytes.len() < DST_SIZE + need { + upload_bytes.resize(DST_SIZE + need, 0); + } + upload_bytes[DST_SIZE + src_off..DST_SIZE + need].copy_from_slice(&expected[a..b]); + push_tiles(&mut tiles, a as u32, src_off as u32, len as u32); + at = need.next_multiple_of(16); + } + let tiles_off = at; + let tiles_bytes = tiles.len() * TILE_STRIDE; + upload_bytes.resize(DST_SIZE + tiles_off + tiles_bytes.next_multiple_of(16), 0); + // SAFETY: copying Pod-like Tile structs into staging byte vec. + unsafe { + std::ptr::copy_nonoverlapping( + tiles.as_ptr().cast::<u8>(), + upload_bytes.as_mut_ptr().add(DST_SIZE + tiles_off), + tiles_bytes, + ); + } + at = (tiles_off + tiles_bytes).next_multiple_of(16); + + let pairs_off = at; + let pair_words = (short_run.1 - short_run.0) / 4; + upload_bytes.resize(DST_SIZE + pairs_off + (pair_words * 8).next_multiple_of(16), 0); + for (idx, off) in (short_run.0..short_run.1).step_by(4).enumerate() { + let val = u32::from_le_bytes(expected[off..off + 4].try_into().unwrap()); + let dst = DST_SIZE + pairs_off + idx * 8; + upload_bytes[dst..dst + 4].copy_from_slice(&(off as u32).to_le_bytes()); + upload_bytes[dst + 4..dst + 8].copy_from_slice(&val.to_le_bytes()); + } + let vram_payload_size = (pairs_off + pair_words * 8).next_multiple_of(16) as u64; + let direct_off = upload_bytes.len(); + upload_bytes.extend_from_slice(&expected[direct_run.0..direct_run.1]); + + let upload = create_buffer( + &device, + D3D12_HEAP_TYPE_UPLOAD, + upload_bytes.len() as u64, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let vram = create_buffer( + &device, + D3D12_HEAP_TYPE_DEFAULT, + vram_payload_size, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, + ); + let card = create_buffer( + &device, + D3D12_HEAP_TYPE_DEFAULT, + DST_SIZE as u64, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, + ); + let readback = create_buffer( + &device, + D3D12_HEAP_TYPE_READBACK, + DST_SIZE as u64, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + + // SAFETY: plain D3D12 command recording and synchronous fence wait. + unsafe { + let mut ptr = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut ptr)).unwrap(); + std::ptr::copy_nonoverlapping(upload_bytes.as_ptr(), ptr.cast(), upload_bytes.len()); + upload.Unmap(0, None); + + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let alloc: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .unwrap(); + + // Seed card with 0xAA and populate VRAM staging via a single CopyBufferRegion. + list.CopyBufferRegion(&card, 0, &upload, 0, DST_SIZE as u64); + list.CopyBufferRegion(&card, direct_run.0 as u64, &upload, direct_off as u64, DIRECT_BYTES as u64); + list.CopyBufferRegion(&vram, 0, &upload, DST_SIZE as u64, vram_payload_size); + list.ResourceBarrier(&[ + transition(&vram, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(&card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + + list.SetComputeRootSignature(&bulk_pass.root); + list.SetPipelineState(&bulk_pass.pso); + list.SetComputeRootShaderResourceView(1, vram.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, card.GetGPUVirtualAddress()); + let c_bulk = [tiles_off as u32]; + list.SetComputeRoot32BitConstants(0, 1, c_bulk.as_ptr().cast(), 0); + list.Dispatch(tiles.len() as u32, 1, 1); + + list.SetComputeRootSignature(&scatter_pass.root); + list.SetPipelineState(&scatter_pass.pso); + list.SetComputeRootShaderResourceView(1, vram.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, card.GetGPUVirtualAddress()); + let c_scatter = [pairs_off as u32, pair_words as u32]; + list.SetComputeRoot32BitConstants(0, 2, c_scatter.as_ptr().cast(), 0); + list.Dispatch((pair_words as u32).div_ceil(64), 1, 1); + + list.ResourceBarrier(&[ + transition(&vram, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON), + transition(&card, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), + ]); + list.CopyBufferRegion(&readback, 0, &card, 0, DST_SIZE as u64); + list.Close().unwrap(); + + let cmd: ID3D12CommandList = list.cast().unwrap(); + queue.ExecuteCommandLists(&[Some(cmd)]); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + queue.Signal(&fence, 1).unwrap(); + if fence.GetCompletedValue() < 1 { + fence.SetEventOnCompletion(1, event).unwrap(); + WaitForSingleObject(event, INFINITE); + } + windows::Win32::Foundation::CloseHandle(event).unwrap(); + + let mut rb_ptr = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut rb_ptr)).unwrap(); + let got = std::slice::from_raw_parts(rb_ptr.cast::<u8>(), DST_SIZE); + assert_eq!(got, expected.as_slice()); + readback.Unmap(0, None); + } + } +} diff --git a/crates/victory-gpu/src/host/shown.rs b/crates/victory-gpu/src/host/shown.rs new file mode 100644 index 000000000..bc77e41ff --- /dev/null +++ b/crates/victory-gpu/src/host/shown.rs @@ -0,0 +1,320 @@ +//! The swap chain's Present on a thread of its own (`VICTORY_PRESENT_THREAD`, on unless `=0`). +//! +//! With DLSS Frame Generation the Present call blocks while frame generation paces the frames +//! it shows: 12.4 ms a frame on average (16.7 the longest) in the release run of 2026-11-27 +//! 15:29, on the thread that prepares and sends submissions (`crate::queue::behind`), which was +//! the frame's wall (42 ms of a 44 ms frame). Here the submitting thread records and sends the +//! present's copy, sets the frame's markers and tags, and hands the Present call to this +//! thread; it goes on preparing the next frame's submissions meanwhile. +//! +//! The host queue's order is kept: from the hand-over until the Present call has returned, +//! whatever any thread gives the host queue through [`Host::queue_send`] (the title's +//! submissions, our copies and fetches, their fence signals) is held, and sent in the order +//! given as soon as it returns. So the frame generation work the Present puts on the queue, +//! which reads the frame's tagged depth and motion vectors, still comes before the next +//! frame's lists. The next present waits until this one is over (the back buffer's index and +//! the frame's markers go in order). +//! +//! Bounded hold (`VICTORY_PRESENT_HOLD_MS`, 250 by default, 0: no bound): a Present that has +//! not returned that long after the hand-over may be waiting for the very work held behind it +//! (frame pacing or the latency markers waiting for the card to reach a signal that is held: +//! the queue, the Present and every thread waiting on those signals would stand for good, the +//! title's watchdog or the driver's reset ending the run). Past the bound, what was held is +//! sent at once, in order, and nothing more is held for that Present. The order against frame +//! generation's own work for that one frame may then differ; a warning says so. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::{ID3D12CommandList, ID3D12CommandQueue, ID3D12Fence}; +use windows::Win32::Graphics::Dxgi::{DXGI_PRESENT, IDXGISwapChain3}; + +use super::Host; +use super::render_trace; +use windows::core::Interface; + +/// What was given to the host queue while a Present was pending: lists in calls cut at +/// `cuts`, then a fence signal. +struct Held { + lists: Vec<Option<ID3D12CommandList>>, + cuts: Vec<usize>, + signal: Option<(ID3D12Fence, u64)>, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Held {} + +struct Gate { + /// A Present was handed over and has not returned (or what it held is being sent). + pending: bool, + held: Vec<Held>, + /// When the pending Present was handed over (`super::now_us`). + since_us: u64, + /// The Present has returned: what it held is being sent by the presenting thread. + returned: bool, +} + +static GATE: Mutex<Gate> = Mutex::new(Gate { pending: false, held: Vec::new(), since_us: 0, returned: false }); + +/// [`Gate`]'s bound on holding, in microseconds (0: none). +fn hold_limit_us() -> u64 { + static LIMIT: OnceLock<u64> = OnceLock::new(); + *LIMIT.get_or_init(|| { + std::env::var("VICTORY_PRESENT_HOLD_MS").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(250) * 1000 + }) +} + +/// Presents past [`hold_limit_us`] since the last frame-rate line. +static OVERRAN: AtomicU64 = AtomicU64::new(0); + +/// Whether the presenting thread is doing a present (set by the submitting thread when it +/// hands one over, cleared when everything of it is done). +static BUSY: Mutex<bool> = Mutex::new(false); +static IDLE: Condvar = Condvar::new(); + +/// Since the last frame-rate line: presents handed over, microseconds in the Present call, +/// sends held behind it, microseconds sending them, microseconds the submitting thread waited +/// for the one before at a present, presents done where they were (no thread). +static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; +const HANDED: usize = 0; +const IN_PRESENT: usize = 1; +const HELD: usize = 2; +const RELEASING: usize = 3; +const WAITED: usize = 4; +const INLINE: usize = 5; + +/// Whether the Present goes to a thread of its own. +pub(super) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PRESENT_THREAD").is_none_or(|v| v != "0")) +} + +/// Calls `lists` on `queue` in calls cut at `cuts`, then the signal. +/// +/// # Safety +/// Closed lists; a fence the caller may signal. +unsafe fn run_on( + queue: &ID3D12CommandQueue, + lists: &[Option<ID3D12CommandList>], + cuts: &[usize], + signal: Option<(&ID3D12Fence, u64)>, +) -> windows::core::Result<()> { + let mut from = 0; + for to in cuts.iter().copied().chain([lists.len()]) { + let to = to.clamp(from, lists.len()); + if to > from { + if render_trace::active() { + render_trace::execute(queue, &lists[from..to], signal.map(|(fence, value)| (fence.as_raw() as usize, value))); + } + // SAFETY: the caller's. + unsafe { queue.ExecuteCommandLists(&lists[from..to]) }; + } + from = to; + } + match signal { + // SAFETY: the caller's. + Some((fence, value)) => unsafe { queue.Signal(fence, value) }, + None => Ok(()), + } +} + +impl Host { + /// Gives the host queue `lists` (in calls of their own from each of `cuts` on) and then + /// the signal: now, or, while a Present handed to the presenting thread is pending, as + /// soon as it has returned, in the order given. Every user of the host queue whose work + /// has to stay in order with the title's submissions goes through here. + pub(super) fn queue_send( + &self, + lists: &[Option<ID3D12CommandList>], + cuts: &[usize], + signal: Option<(&ID3D12Fence, u64)>, + ) -> windows::core::Result<()> { + let mut gate = GATE.lock().unwrap_or_else(|e| e.into_inner()); + let limit = hold_limit_us(); + if gate.pending && !gate.returned && limit != 0 && super::now_us().saturating_sub(gate.since_us) > limit { + // The Present stands past the bound: what it held goes now, in order, and this + // with it; nothing more is held for it. + let held = std::mem::take(&mut gate.held); + gate.pending = false; + OVERRAN.fetch_add(1, Relaxed); + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !SAID.swap(true, Relaxed) { + tracing::warn!( + held = held.len(), + ms = super::now_us().saturating_sub(gate.since_us) / 1000, + "a Present on the presenting thread stood past VICTORY_PRESENT_HOLD_MS: the host queue's work held behind it was sent without waiting for it (it may have waited for that work)" + ); + } + for h in held { + // SAFETY: lists closed and a fence given by earlier callers. + unsafe { run_on(&self.queue, &h.lists, &h.cuts, h.signal.as_ref().map(|(f, v)| (f, *v)))? }; + } + // SAFETY: the caller's lists and fence. + return unsafe { run_on(&self.queue, lists, cuts, signal) }; + } + if gate.pending { + if render_trace::active() { + render_trace::event("queue_held_for_present", format_args!("lists={}\tfence={:?}", lists.len(), signal.map(|(_, value)| value))); + } + gate.held.push(Held { lists: lists.to_vec(), cuts: cuts.to_vec(), signal: signal.map(|(f, v)| (f.clone(), v)) }); + STATS[HELD].fetch_add(1, Relaxed); + return Ok(()); + } + // (Under the gate's lock: a hand-over cannot come between the look and the call.) + // SAFETY: the caller's lists and fence. + unsafe { run_on(&self.queue, lists, cuts, signal) } + } + + /// Before a present touches the swap chain: the one before is over. + pub(super) fn present_wait(&self) { + let began = std::time::Instant::now(); + let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner()); + if !*busy { + return; + } + let _waiting = crate::timeline::span("a present waits for the one before on the presenting thread"); + while *busy { + busy = IDLE.wait(busy).unwrap_or_else(|e| e.into_inner()); + } + STATS[WAITED].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + } +} + +/// A Present handed over: the swap chain, what frame generation began for it. +pub(super) struct Job { + pub(super) swap_chain: IDXGISwapChain3, + pub(super) presenting: Option<crate::streamline::Presenting>, + pub(super) frame: u64, +} + +// SAFETY: DXGI and Streamline's frame token are used by one thread at a time: the submitting +// thread hands them over and touches the swap chain again only after `present_wait`. +unsafe impl Send for Job {} + +/// Hands the Present of `job` to the presenting thread; with no thread, does it here. +pub(super) fn hand_over(job: Job) { + static SENDER: OnceLock<Option<Mutex<std::sync::mpsc::Sender<Job>>>> = OnceLock::new(); + let sender = SENDER.get_or_init(|| { + let (sender, receiver) = std::sync::mpsc::channel::<Job>(); + let spawned = std::thread::Builder::new().name("victory-present".into()).spawn(move || { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL}; + // SAFETY: this thread's own priority. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + crate::cores::keep_on_fast_cores("victory-present"); + for job in receiver { + let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| present(job))); + if ended.is_err() { + // What it held would never be sent, and the next present would wait for good. + super::fail(format_args!("the thread that presents panicked")); + } + } + }); + match spawned { + Ok(_) => { + tracing::info!("the swap chain's Present runs on a thread of its own (VICTORY_PRESENT_THREAD); the host queue's work waits behind it in order"); + Some(Mutex::new(sender)) + } + Err(e) => { + tracing::warn!(error = %e, "no presenting thread: frames are presented where they are sent"); + None + } + } + }); + *BUSY.lock().unwrap_or_else(|e| e.into_inner()) = true; + { + let mut gate = GATE.lock().unwrap_or_else(|e| e.into_inner()); + gate.pending = true; + gate.returned = false; + gate.since_us = super::now_us(); + } + STATS[HANDED].fetch_add(1, Relaxed); + let job = match sender { + Some(sender) => match sender.lock().unwrap_or_else(|e| e.into_inner()).send(job) { + Ok(()) => return, + Err(std::sync::mpsc::SendError(job)) => job, + }, + None => job, + }; + STATS[INLINE].fetch_add(1, Relaxed); + present(job); +} + +/// The Present, what was held behind it, frame generation's end of the frame and the meter. +fn present(job: Job) { + let Job { swap_chain, presenting, frame } = job; + let mut showing = crate::timeline::span("the host's Present (presenting thread)"); + let called = crate::streamline::present_called(&presenting); + let began = std::time::Instant::now(); + let trace_start = render_trace::active().then(super::now_us); + // SAFETY: our swap chain; nothing else uses it until `present_wait` returns. + let result = unsafe { swap_chain.Present(0, DXGI_PRESENT(0)) }; + if let Some(start) = trace_start { + render_trace::event("present", format_args!("present_frame={frame}\tstart_us={start}\tduration_us={}\tstatus={:#x}\tasync=true", began.elapsed().as_micros(), result.0)); + } + STATS[IN_PRESENT].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + crate::streamline::present_returned(called); + showing.next("sending what waited behind the present"); + release(); + showing.next("the frame's end"); + crate::streamline::present_ends(presenting); + if let Some(host) = super::host() { + let mut presenter = host.presenter.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(p) = presenter.as_mut() { + p.panel.frame(p.meter.line_due()); + p.menu.frame(); + p.meter.frame(p.hwnd); + } + } + showing.end(); + *BUSY.lock().unwrap_or_else(|e| e.into_inner()) = false; + IDLE.notify_all(); +} + +/// Sends what was held behind the present, in order, until nothing more comes; then the +/// queue is free again. +fn release() { + let began = std::time::Instant::now(); + GATE.lock().unwrap_or_else(|e| e.into_inner()).returned = true; + let Some(host) = super::host() else { + let mut gate = GATE.lock().unwrap_or_else(|e| e.into_inner()); + gate.held.clear(); + gate.pending = false; + return; + }; + loop { + let held = { + let mut gate = GATE.lock().unwrap_or_else(|e| e.into_inner()); + if gate.held.is_empty() { + gate.pending = false; + break; + } + std::mem::take(&mut gate.held) + }; + for h in held { + // SAFETY: lists closed and a fence given by `queue_send`'s callers. + let sent = unsafe { run_on(&host.queue, &h.lists, &h.cuts, h.signal.as_ref().map(|(f, v)| (f, *v))) }; + if let Err(e) = sent { + super::fail(format_args!("work held behind a present could not be sent to the host queue ({e})")); + } + } + } + STATS[RELEASING].fetch_add(began.elapsed().as_micros() as u64, Relaxed); +} + +/// For the frame-rate line. +pub(super) fn line(frames: f64) { + let s: [f64; 6] = std::array::from_fn(|i| STATS[i].swap(0, Relaxed) as f64); + if s[HANDED] + s[INLINE] == 0.0 { + return; + } + tracing::info!( + "presents on a thread of their own, per frame (VICTORY_PRESENT_THREAD): {:.2} handed over ({:.2} done where they were), {:.1} ms in the Present call, {:.1} sends held behind it and {:.2} ms sending them; the submitting thread waited {:.2} ms at a present for the one before; {} presents stood past the hold bound (VICTORY_PRESENT_HOLD_MS)", + s[HANDED] / frames, + s[INLINE] / frames, + s[IN_PRESENT] / 1000.0 / frames, + s[HELD] / frames, + s[RELEASING] / 1000.0 / frames, + s[WAITED] / 1000.0 / frames, + OVERRAN.swap(0, Relaxed) + ); +} diff --git a/crates/victory-gpu/src/host/stamps.rs b/crates/victory-gpu/src/host/stamps.rs index 6abbcfb39..35164700c 100644 --- a/crates/victory-gpu/src/host/stamps.rs +++ b/crates/victory-gpu/src/host/stamps.rs @@ -170,8 +170,8 @@ mod tests { // SAFETY: closed lists; the fence and event are the host's, under // its lock. unsafe { - host.queue.ExecuteCommandLists(&[Some(ahead), Some(behind)]); - host.queue.Signal(&host.fence, *submitted).unwrap(); + // (In order with what waits behind a present: `super::shown`.) + host.queue_send(&[Some(ahead), Some(behind)], &[], Some((&host.fence, *submitted))).unwrap(); host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); WaitForSingleObject(host.event, INFINITE); } diff --git a/crates/victory-gpu/src/host/torn.rs b/crates/victory-gpu/src/host/torn.rs index 5faef193d..29a63d252 100644 --- a/crates/victory-gpu/src/host/torn.rs +++ b/crates/victory-gpu/src/host/torn.rs @@ -183,12 +183,19 @@ fn step(h: &mut [u32; 4], with: [u32; 4]) { *h = std::array::from_fn(|i| x[(i + 1) % 4] ^ (x[i] >> 15)); } -/// The 64 threads' hashes as one, folded to 31 bits. +/// The 64 threads' hashes as one, folded to 31 bits (6-step binary tree reduction, +/// matching [`CARD_COMPARE`]). fn finish(parts: &[[u32; 4]; 64]) -> u32 { - let mut h = parts[0]; - for part in &parts[1..] { - step(&mut h, *part); + let mut tree = *parts; + let mut stride = 32usize; + while stride > 0 { + for i in 0..stride { + let other = tree[i + stride]; + step(&mut tree[i], other); + } + stride >>= 1; } + let h = tree[0]; let f = h[0] ^ h[1].wrapping_mul(3) ^ h[2].wrapping_mul(5) ^ h[3].wrapping_mul(7); f & 0x7FFF_FFFF } diff --git a/crates/victory-gpu/src/host/uav_residency.rs b/crates/victory-gpu/src/host/uav_residency.rs new file mode 100644 index 000000000..afbec59fc --- /dev/null +++ b/crates/victory-gpu/src/host/uav_residency.rs @@ -0,0 +1,178 @@ +//! A paging fence for newly created device-local buffers. + +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows::Win32::Foundation::{E_FAIL, E_NOINTERFACE, E_NOTIMPL, HANDLE}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_UNSUPPORTED}; +use windows::core::{Error, Interface, Result}; + +use super::memory_samples::{self, Allocation, Step}; + +pub(super) fn enabled() -> bool { + static ENABLED: OnceLock<bool> = OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var_os("VICTORY_UAV_ENQUEUE_RESIDENT").is_some_and(|value| value == "1")) +} + +pub(super) struct Queue { + device: ID3D12Device3, + fence: ID3D12Fence, + last: Mutex<u64>, +} + +impl Queue { + fn new(device: &ID3D12Device) -> Result<Self> { + let device = device.cast::<ID3D12Device3>()?; + // SAFETY: a fresh fence belonging to this D3D12 device. + let fence = unsafe { device.CreateFence(0, D3D12_FENCE_FLAG_NONE)? }; + Ok(Self { device, fence, last: Mutex::new(0) }) + } + + /// Cache the paging queue, or the device's lack of support. Other setup + /// errors can be retried on a later allocation. + pub(super) fn get<'a>(cached: &'a OnceLock<Option<Self>>, device: &ID3D12Device) -> Result<Option<&'a Self>> { + if let Some(queue) = cached.get() { + return Ok(queue.as_ref()); + } + let queue = match Self::new(device) { + Ok(queue) => Some(queue), + Err(e) if matches!(e.code(), E_NOINTERFACE | E_NOTIMPL | DXGI_ERROR_UNSUPPORTED) => None, + Err(e) => return Err(e), + }; + let supported = queue.is_some(); + if cached.set(queue).is_ok() { + tracing::info!(supported, "device-local UAV residency fence (VICTORY_UAV_ENQUEUE_RESIDENT=1)"); + } + Ok(cached.get().and_then(Option::as_ref)) + } + + pub(super) fn make_resident(&self, buffer: &ID3D12Resource, allocation: Allocation) -> Result<()> { + let started = Instant::now(); + let queued = self.enqueue(buffer); + memory_samples::record(allocation, Step::Enqueue, started.elapsed().as_micros() as u64, queued.is_err()); + let value = queued?; + let started = Instant::now(); + let finished = self.wait(value); + memory_samples::record(allocation, Step::WaitForFence, started.elapsed().as_micros() as u64, finished.is_err()); + finished + } + + fn enqueue(&self, buffer: &ID3D12Resource) -> Result<u64> { + let object = buffer.cast::<ID3D12Pageable>()?; + let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let value = last.checked_add(1).filter(|&value| value != u64::MAX).ok_or_else(|| Error::from_hresult(E_FAIL))?; + // SAFETY: the buffer and paging fence belong to this device. The + // lock keeps paging fence values in the order the driver receives + // them. The caller retains the buffer while waiting for its value. + unsafe { self.device.EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, &[Some(object)], &self.fence, value)? }; + *last = value; + Ok(value) + } + + fn reached(&self, value: u64) -> Result<bool> { + // SAFETY: a plain query on the live paging fence. + let completed = unsafe { self.fence.GetCompletedValue() }; + if completed == u64::MAX { + // SAFETY: a plain query on this fence's device. + let error = unsafe { self.device.GetDeviceRemovedReason() }.err(); + return Err(error.unwrap_or_else(|| Error::from_hresult(DXGI_ERROR_DEVICE_REMOVED))); + } + Ok(completed >= value) + } + + fn wait(&self, value: u64) -> Result<()> { + if self.reached(value)? { + return Ok(()); + } + // SAFETY: a null event makes this call wait on the live fence. No + // paging lock is held, so other threads can enqueue while it waits. + if let Err(error) = unsafe { self.fence.SetEventOnCompletion(value, HANDLE::default()) } { + tracing::warn!(%error, value, "could not register a UAV residency wait; polling the paging fence"); + } + // If event registration failed, the successful enqueue still owns + // this paging operation. Keep the buffer alive until it completes. + while !self.reached(value)? { + std::thread::sleep(Duration::from_millis(1)); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn new_local_uav_can_be_used_immediately() { + let Some(host) = crate::host::host() else { return }; + const SIZE: u64 = 4096; + let (upload, source) = host.upload_buffer(SIZE).unwrap(); + let (back, read) = host.shared_buffer_cpu(SIZE).unwrap(); + let before = host.uav_residency.get().and_then(Option::as_ref).map_or(0, |paging| { + *paging.last.lock().unwrap_or_else(|e| e.into_inner()) + }); + let buffer = host.uav_buffer(SIZE).unwrap(); + if !enabled() { + assert!(host.uav_residency.get().is_none()); + } else if super::super::wait_resident() + && let Some(paging) = host.uav_residency.get().expect("the paging mode was tried") + { + assert!(paging.reached(before + 1).unwrap()); + } + // SAFETY: the three allocations have SIZE bytes; this test retains + // the resources and command objects until the copy fence completes. + unsafe { + std::ptr::write_bytes(source, 0x61, SIZE as usize); + let queue: ID3D12CommandQueue = host.device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = host.device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = host.device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.CopyBufferRegion(&buffer, 0, &upload, 0, SIZE); + list.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.CopyBufferRegion(&back, 0, &buffer, 0, SIZE); + list.Close().unwrap(); + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, HANDLE::default()).unwrap(); + assert_eq!(fence.GetCompletedValue(), 1); + assert!(std::slice::from_raw_parts(read, SIZE as usize).iter().all(|&value| value == 0x61)); + } + } + + #[test] + fn residency_wait_requires_its_fence_value() { + let Some(host) = crate::host::host() else { return }; + let Ok(queue) = Queue::new(&host.device) else { return }; + let (finished, done) = std::sync::mpsc::channel(); + let (started, running) = std::sync::mpsc::channel(); + std::thread::scope(|scope| { + let queue = &queue; + scope.spawn(move || { + started.send(()).unwrap(); + finished.send(queue.wait(2)).unwrap(); + }); + running.recv().unwrap(); + // SAFETY: the test owns this fence and gives it monotonically + // increasing values. The first cannot satisfy the wait. + unsafe { queue.fence.Signal(1).unwrap() }; + let early = done.recv_timeout(Duration::from_millis(25)); + unsafe { queue.fence.Signal(2).unwrap() }; + assert!(matches!(early, Err(std::sync::mpsc::RecvTimeoutError::Timeout))); + done.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(); + }); + } +} diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index d82a0c91f..e7c652264 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -499,8 +499,10 @@ fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> { list.Close().ok()?; let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; let event = CreateEventW(None, false, false, None).ok()?; - host.queue.ExecuteCommandLists(&[Some(list.cast().ok()?)]); - let done = host.queue.Signal(&fence, 1).and_then(|()| fence.SetEventOnCompletion(1, event)); + // (In order with what waits behind a present: `super::shown`.) + let done = host + .queue_send(&[Some(list.cast().ok()?)], &[], Some((&fence, 1))) + .and_then(|()| fence.SetEventOnCompletion(1, event)); if done.is_ok() { WaitForSingleObject(event, INFINITE); } diff --git a/crates/victory-gpu/src/host/water_timing.rs b/crates/victory-gpu/src/host/water_timing.rs new file mode 100644 index 000000000..328371f2d --- /dev/null +++ b/crates/victory-gpu/src/host/water_timing.rs @@ -0,0 +1,186 @@ +//! GPU timestamps for the water-light dispatches, resolved in the same list +//! and read when it lands. No fence or queue submission is added for timing. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +const HASHES: [&str; 5] = [ + "5dc3b25986622949", // tiled + "6f225b641c5b0708", // tiled local lights + "6871d6e4b3ac9a10", // full volume + "a10179ab7eda0dc3", // volume portals + "926c46bab3b86bd6", // submerged +]; +const LIMIT: u32 = 16; +static RUNS: [AtomicU64; HASHES.len()] = [const { AtomicU64::new(0) }; HASHES.len()]; +static NS: [AtomicU64; HASHES.len()] = [const { AtomicU64::new(0) }; HASHES.len()]; + +pub(crate) fn kind(pipeline: &crate::pipeline::host::HostPipeline) -> Option<usize> { + static ON: OnceLock<bool> = OnceLock::new(); + if !*ON.get_or_init(|| crate::switch::on("VICTORY_WATER_LIGHT")) { + return None; + } + let hash = &pipeline.stages.first()?.shader.hash; + HASHES.iter().position(|&known| known == hash) +} + +struct Stamps { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + data: usize, + frequency: u64, +} + +#[derive(Default)] +pub(super) struct List { + stamps: OnceLock<Option<Stamps>>, + passes: Mutex<Vec<usize>>, +} + +impl List { + fn stamps(&self) -> Option<&Stamps> { + self.stamps.get_or_init(|| { + let host = host()?; + let mut heap = None; + // SAFETY: an ordinary timestamp heap and a query of the host queue. + let frequency = unsafe { + host.device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: LIMIT * 2, NodeMask: 0 }, + &mut heap, + ).ok()?; + host.queue.GetTimestampFrequency().ok()? + }; + if frequency == 0 { + return None; + } + let mut back: Option<ID3D12Resource> = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(LIMIT) * 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: a readback buffer in the state required by ResolveQueryData. + unsafe { + host.device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ).ok()?; + } + let back = back?; + let mut data = std::ptr::null_mut(); + // SAFETY: the readback resource is kept alive with its mapping. + unsafe { back.Map(0, None, Some(&mut data)).ok()? }; + if data.is_null() { + return None; + } + Some(Stamps { heap: heap?, back, data: data as usize, frequency }) + }).as_ref() + } + + pub(super) fn begin(&self, list: &ID3D12GraphicsCommandList, kind: usize) -> Option<u32> { + let mut passes = self.passes.lock().unwrap_or_else(|e| e.into_inner()); + let index = passes.len() as u32; + if index >= LIMIT { + return None; + } + let stamps = self.stamps()?; + passes.push(kind); + // SAFETY: the open list records into its own heap, with index below LIMIT * 2. + unsafe { list.EndQuery(&stamps.heap, D3D12_QUERY_TYPE_TIMESTAMP, index * 2) }; + Some(index) + } + + pub(super) fn end(&self, list: &ID3D12GraphicsCommandList, index: u32) { + if let Some(Some(stamps)) = self.stamps.get() { + // SAFETY: begin recorded the first timestamp for this bounded pair. + unsafe { list.EndQuery(&stamps.heap, D3D12_QUERY_TYPE_TIMESTAMP, index * 2 + 1) }; + } + } + + pub(super) fn resolve(&self, list: &ID3D12GraphicsCommandList) { + let Some(Some(stamps)) = self.stamps.get() else { return }; + let count = self.passes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; + if count != 0 { + // SAFETY: all these queries were recorded on this list and fit the result buffer. + unsafe { list.ResolveQueryData(&stamps.heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count * 2, &stamps.back, 0) }; + } + } + + pub(super) fn collect(&self) { + let Some(Some(stamps)) = self.stamps.get() else { return }; + let passes = self.passes.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: the completed list resolved two timestamp values per pass. + let data = unsafe { std::slice::from_raw_parts(stamps.data as *const u64, passes.len() * 2) }; + for (&kind, pair) in passes.iter().zip(data.chunks_exact(2)) { + let ticks = pair[1].saturating_sub(pair[0]); + if ticks != 0 { + RUNS[kind].fetch_add(1, Ordering::Relaxed); + NS[kind].fetch_add((u128::from(ticks) * 1_000_000_000 / u128::from(stamps.frequency)) as u64, Ordering::Relaxed); + } + } + } + + pub(super) fn reset(&self) { + if self.stamps.get().is_some() { + self.passes.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } + } +} + +pub(super) fn log(frames: f64) { + for (kind, hash) in HASHES.into_iter().enumerate() { + let ns = NS[kind].swap(0, Ordering::Relaxed); + let runs = RUNS[kind].swap(0, Ordering::Relaxed); + if runs != 0 { + tracing::info!(hash, runs, ms_per_frame = ns as f64 / 1e6 / frames.max(1.0), "water light GPU time"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_completed_list_resolves_water_timestamps() { + let Some(host) = host() else { return }; + let (allocator, list) = host.make_prelude().expect("timestamp test list"); + // SAFETY: the list has just been created and closed. + unsafe { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + } + let timing = List::default(); + let first = timing.begin(&list, 0).expect("timestamp pair"); + timing.end(&list, first); + timing.resolve(&list); + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: this queue, fence and event belong to the host and the + // submission lock excludes other users of the event. + unsafe { + list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + *submitted += 1; + host.queue.Signal(&host.fence, *submitted).unwrap(); + host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); + WaitForSingleObject(host.event, INFINITE); + } + let stamps = timing.stamps().unwrap(); + // SAFETY: the completed list resolved the first pair of timestamps. + let pair = unsafe { std::slice::from_raw_parts(stamps.data as *const u64, 2) }; + assert!(pair[0] > 0 && pair[1] >= pair[0], "{pair:?}"); + timing.collect(); + timing.reset(); + assert!(timing.passes.lock().unwrap().is_empty()); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 467074089..5a36debd1 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -440,6 +440,7 @@ fn clamp_into( ahead: bool, ) -> bool { let before = list.indirect_state(dst); + list.trace_gpu_pass("indirect argument clamp", [spec.0.into(), spec.1.into(), spec.2.into(), i64::from(ahead), 0]); let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead); if recorded { list.indirect_readable(dst); @@ -513,8 +514,8 @@ fn record_clamp_as( // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every // earlier execution's reads of the scratch buffer; nothing else writes it. - // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two - // waits for every earlier shader write out (the state changes stay). + // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the wait + // for every earlier shader write out (the state changes stay). #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::IndirectBounded, 1); #[cfg(feature = "diagnostics")] @@ -525,14 +526,14 @@ fn record_clamp_as( uav_barrier(), transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]; - let second = [ - uav_barrier(), - transition( - dst, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), - ]; + // The state transition on `dst` already orders UAV writes to `dst` before + // `ExecuteIndirect` reads it; `budget` is only read/written by the next + // clamp/batch pass, which begins with `first[0]` (`uav_barrier()`). + let after = transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ); let skip = usize::from(!waits); unsafe { // Earlier shader writes (the title's argument and count passes) first. @@ -547,7 +548,7 @@ fn record_clamp_as( l.SetComputeRootUnorderedAccessView(4, budget); l.Dispatch(records.div_ceil(64), 1, 1); } - l.ResourceBarrier(&second[skip..]); + l.ResourceBarrier(&[after]); } true } @@ -603,6 +604,7 @@ pub(crate) fn open_batch( } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + list.trace_gpu_pass("indirect argument clamp batch", [0; 5]); batch::record(c, &list.list, (&dst, before), budget, sources, jobs); // SAFETY: the list's own upload memory of that many bytes, 256-byte // aligned, until it is reset. @@ -962,6 +964,170 @@ void main() { assert_eq!(run(&mut warp, 2), [0, 0, 0]); } + /// A table pass of the compare (`crate::host::card_table`): the pieces are + /// the numbers put in the result dwords, in any order, and each result is + /// that piece's, as a pass over the piece alone gives it; a hashing table + /// pass stores the hashes a later compare finds unchanged. + #[test] + fn warp_card_table_pass_takes_the_pieces_named() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 4; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); + let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); + let content: Vec<u8> = (0..size).map(|i| (i * 13 + i / 97) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + let order = [3u32, 0, 2]; + let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] { + // SAFETY: our open list, live buffers, the compare's own root + // signature; the mappings hold what is read and written. + unsafe { + for (slot, piece) in order.iter().enumerate() { + differs_ptr.cast::<u32>().add(slot).write_volatile(*piece); + } + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, 0, size as u32, order.len() as u32, 0, mode | 4]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(order.len() as u32, 1, 1); + } + warp.submit_and_wait(); + // SAFETY: as above. + [0, 1, 2].map(|slot| unsafe { differs_ptr.cast::<u32>().add(slot).read_volatile() }) + }; + // Hashed through the table: the dwords keep the numbers. + assert_eq!(run(&mut warp, 0), order); + // Compared through it: unchanged, and each the hash of its own piece. + let found = run(&mut warp, 1); + for (slot, &piece) in order.iter().enumerate() { + assert_eq!(found[slot] & 1, 0, "piece {piece}"); + // SAFETY: inside the mapping, which the card has read. + let bytes = unsafe { std::slice::from_raw_parts(now_ptr.add(piece as usize * PIECE).cast_const(), PIECE) }; + assert_eq!(found[slot] >> 1, crate::host::piece_hash(bytes), "piece {piece}"); + } + // A change in piece 2 (slot 2) only. + // SAFETY: inside the mapping. + unsafe { now_ptr.add(2 * PIECE + 77).write_volatile(content[2 * PIECE + 77] ^ 0x10) }; + assert_eq!(run(&mut warp, 1).map(|d| d & 1), [0, 0, 1]); + } + + /// The pass that brings flagged pieces down with their flight + /// (`crate::host::prefetch`), on the software adapter, after the + /// compare: each flagged piece takes a slot (noted at its place in the + /// header, 1 on) and comes down whole; the others are noted 0; past the + /// slots a flagged piece is noted 0 and counted. + #[test] + fn warp_card_spill_brings_down_the_flagged_pieces_whole() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + let spill = compile_cs(&warp.device, crate::host::CARD_SPILL).expect("the card spill must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 4; + // The copy begins 100 bytes into its first piece (the skew). + const SKEW: u32 = 100; + // (A multiple of 16: the card's buffers are of 64 KiB.) + let size = PIECE * PIECES as usize - 96; + let stride = crate::host::SPILL_STRIDE as usize; + const HEADER: u32 = 256; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); + let (_differs, _, differs_gpu) = warp.shared_buffer(64); + let (_slots, slots_ptr, slots_gpu) = warp.shared_buffer(u64::from(HEADER) + 4 * stride as u64); + let content: Vec<u8> = (0..size).map(|i| (i * 7 + i / 509) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + let run = |warp: &mut WarpHarness, mode: u32, capacity: u32| { + // SAFETY: our open list, live buffers, each pass's own root + // signature; the mappings hold what is read and written. + unsafe { + slots_ptr.cast::<u32>().write_volatile(0); + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, SKEW, size as u32, PIECES, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(PIECES, 1, 1); + warp.list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + if mode != 0 { + warp.list.SetComputeRootSignature(&spill.root); + warp.list.SetPipelineState(&spill.pso); + let constants = [0u32, SKEW, size as u32, PIECES, 0, 0, capacity, HEADER]; + warp.list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, differs_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, slots_gpu); + warp.list.Dispatch(PIECES, 1, 1); + } + } + warp.submit_and_wait(); + // SAFETY: as above. + let count = unsafe { slots_ptr.cast::<u32>().read_volatile() }; + let slots: Vec<u32> = (0..PIECES as usize).map(|p| unsafe { slots_ptr.cast::<u32>().add(1 + p).read_volatile() }).collect(); + (count, slots) + }; + // Hashed first; then nothing flagged. + run(&mut warp, 0, 4); + assert_eq!(run(&mut warp, 2, 4), (0, vec![0, 0, 0, 0])); + // Pieces 0 and 2 changed: both come down, whole. + let changed = [10usize, 2 * PIECE + 5000 - SKEW as usize]; + for &at in &changed { + // SAFETY: inside the mapping. + unsafe { now_ptr.add(at).write_volatile(content[at] ^ 0x5A) }; + } + let (count, slots) = run(&mut warp, 2, 4); + assert_eq!(count, 2); + assert_eq!(slots[1], 0); + assert_eq!(slots[3], 0); + let mut taken: Vec<u32> = vec![slots[0], slots[2]]; + taken.sort_unstable(); + assert_eq!(taken, [1, 2]); + for piece in [0usize, 2] { + // The piece's offsets in the copy, widened to 16 bytes, as the + // compare hashes them. + let lo = (piece * PIECE).saturating_sub(SKEW as usize) & !15; + let hi = (((piece + 1) * PIECE - SKEW as usize).min(size) + 15) & !15; + let at = HEADER as usize + (slots[piece] as usize - 1) * stride; + // SAFETY: inside both mappings. + let (down, now) = unsafe { + ( + std::slice::from_raw_parts(slots_ptr.add(at).cast_const(), hi - lo), + std::slice::from_raw_parts(now_ptr.add(lo).cast_const(), hi - lo), + ) + }; + assert!(down == now, "piece {piece} came down whole"); + } + // One slot: the second flagged piece is counted, noted 0. + for &at in &changed { + // SAFETY: inside the mapping. + unsafe { now_ptr.add(at).write_volatile(content[at]) }; + } + let (count, slots) = run(&mut warp, 2, 1); + assert_eq!(count, 2); + assert_eq!(slots.iter().filter(|&&s| s == 1).count(), 1); + assert_eq!(slots.iter().filter(|&&s| s == 0).count(), 3); + } + /// What the passes over copies in the card's memory cost on the card /// (ignored: a measurement): rounds of a few passes of some pieces and a /// wait, as a frame has them. `VICTORY_BENCH_CS=<file>` times another diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 4bb00c4b0..283820a88 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -167,14 +167,6 @@ pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> { } } -/// Something placed elsewhere (`crate::port`) in the same form: counted as -/// [`place_for`] counts, so that [`gone`] takes it off again. -pub(crate) fn counted(window: bool, bytes: u64) { - let at = if window { 0 } else { 2 }; - STATS[at].fetch_add(1, Ordering::Relaxed); - STATS[at + 1].fetch_add(bytes, Ordering::Relaxed); -} - /// What [`place_for`] gave is gone. pub(crate) fn gone(window: bool, bytes: u64) { let at = if window { 0 } else { 2 }; @@ -283,11 +275,13 @@ struct Views { pages: BTreeMap<(usize, u64), Vec<usize>>, /// Of those, how many are shown more than once. pages_twice: usize, - /// Sections by handle: bytes, and whether made committed. - sections: Vec<(usize, u64, bool)>, + /// Sections by handle: bytes, and whether made committed. (After + /// vilocity 0f44a1706: a map, as [`Views::whole`]: + /// with `VICTORY_SECTION_MB` a request is thousands of sections.) + sections: BTreeMap<usize, (u64, bool)>, /// Our own view of a whole section, by its handle (0: the host gave /// none), made when first asked for ([`beside`]) and kept. - whole: Vec<(usize, usize)>, + whole: BTreeMap<usize, usize>, } /// Read by many threads at once (write faults, landings), changed when the @@ -296,8 +290,8 @@ static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), pages_twice: 0, - sections: Vec::new(), - whole: Vec::new(), + sections: BTreeMap::new(), + whole: BTreeMap::new(), }); fn views() -> std::sync::RwLockReadGuard<'static, Views> { @@ -312,20 +306,17 @@ fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> { /// if with `SEC_COMMIT` (only such a section can be opened as a heap). pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { let mut v = views_mut(); - v.sections.retain(|s| s.0 != section); // A handle's number given out again: the view was of the section that // had it before (it stays mapped: someone may be writing through it). - v.whole.retain(|w| w.0 != section); - v.sections.push((section, bytes, committed)); + v.whole.remove(§ion); + v.sections.insert(section, (bytes, committed)); } /// The runtime lets go of a section, and of its handle: no view the title /// sees is of it any more, and [`beside`]'s view goes. pub fn title_memory_section_gone(section: usize) { let whole = { - let mut v = views_mut(); - let at = v.whole.iter().position(|w| w.0 == section); - at.map(|i| v.whole.swap_remove(i).1) + views_mut().whole.remove(§ion) }; if let Some(base) = whole.filter(|&base| base != 0) { // SAFETY: a view of ours. Who writes through it found the section @@ -583,7 +574,7 @@ pub(crate) fn beside(at: usize, len: usize) -> Option<usize> { let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { return None; }; - v.whole.iter().find(|w| w.0 == section).map(|w| (w.1, offset)) + v.whole.get(§ion).map(|&base| (base, offset)) }; if let Some((base, offset)) = known { return (base != 0).then(|| base + offset as usize); @@ -592,17 +583,17 @@ pub(crate) fn beside(at: usize, len: usize) -> Option<usize> { let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { return None; }; - let base = match v.whole.iter().find(|w| w.0 == section) { - Some(w) => w.1, + let base = match v.whole.get(§ion) { + Some(&base) => base, None => { - let &(_, bytes, _) = v.sections.iter().find(|s| s.0 == section)?; + let &(bytes, _) = v.sections.get(§ion)?; // SAFETY: the whole of a section the runtime made; a view the // title sees is of it, so its handle is open. let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize; if base == 0 { tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own"); } - v.whole.push((section, base)); + v.whole.insert(section, base); base } }; @@ -623,11 +614,11 @@ pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> { return None; } let offset = offset + within as u64; - if let Some(whole) = v.whole.iter().find(|w| w.0 == section) { + if let Some(&whole) = v.whole.get(§ion) { let mut shown = [0; 8]; let all = v.pages.get(&(section, offset))?; shown.get_mut(..all.len())?.copy_from_slice(all); - return (whole.1 != 0).then(|| (whole.1 + offset as usize, shown)); + return (whole != 0).then(|| (whole + offset as usize, shown)); } } if asked || beside(page, K64).is_none() { @@ -933,11 +924,13 @@ unsafe fn private(p: &mut Probe, rig: &mut Rig) { let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); p.part_reads = first && second; p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); - mem::ResetWriteWatch(base.cast(), SIZE); + crate::watch::with_kernel_write_watch(|| mem::ResetWriteWatch(base.cast(), SIZE)); let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); - let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + let watched = crate::watch::with_kernel_write_watch(|| { + mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) + }) == 0; memory.cast::<[u32; 3]>().write([40, 2, 0]); let shaded = rig.shade(buffer.GetGPUVirtualAddress()); let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; @@ -1189,9 +1182,16 @@ fn census_of(spans: &[(u64, u64, bool)]) -> Vec<String> { bytes >> 20, big >> 20 )); - for &(_, bytes, committed) in &v.sections { + // Sections alike in one line (`VICTORY_SECTION_MB`: thousands of them); + // one of a kind reads as before. + let mut alike: BTreeMap<(u64, bool), usize> = BTreeMap::new(); + for §ion in v.sections.values() { + *alike.entry(section).or_default() += 1; + } + for ((bytes, committed), count) in alike { lines.push(format!( - "census, a section of {} MB, {}", + "census, {} of {} MB, {}", + if count == 1 { "a section".to_string() } else { format!("{count} sections") }, bytes >> 20, if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } )); diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 9b2301825..8943cba0e 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -57,7 +57,7 @@ fn threads() -> usize { } /// Whether views of the title's pages are written through one of ours. -fn beside_on() -> bool { +pub(crate) fn beside_on() -> bool { static ON: OnceLock<bool> = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_BESIDE").is_none_or(|v| v != "0")) } @@ -331,6 +331,57 @@ pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) { POOL.get_or_init(|| Pool::new("victory-land", threads())).each(count, f); } +/// [`Pool::each`] on threads kept for putting the title's bytes in under flights' writes, +/// one copy a job (`crate::host`'s `stale_of`; `VICTORY_MERGE_THREADS`, 4 with this one). +/// Others than those of [`each_under`], which a job here leaves alone (its pages are +/// compared on its own thread then). +pub(crate) fn each_merge(count: usize, f: &(dyn Fn(usize) + Sync)) { + static POOL: OnceLock<&'static Pool> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::env::var("VICTORY_MERGE_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4usize); + Pool::new("victory-merge", threads.clamp(1, 16)) + }) + .each(count, f); +} + +/// `victory bench`: lands whole 64 KiB pieces (title address, the card's bytes, the held +/// copy) as a landing does, on `threads` threads (a pool kept per count). +pub(crate) fn bench_land(work: &[(usize, usize, usize)], threads: usize) { + static POOLS: std::sync::Mutex<Vec<(usize, &'static Pool)>> = std::sync::Mutex::new(Vec::new()); + let pool = { + let mut pools = POOLS.lock().unwrap_or_else(|e| e.into_inner()); + match pools.iter().find(|p| p.0 == threads) { + Some(p) => p.1, + None => { + let p = Pool::new("victory-bench-land", threads.clamp(1, 32)); + pools.push((threads, p)); + p + } + } + }; + let cut: Vec<(usize, usize)> = work.iter().map(|p| (p.0, BLOCK)).collect(); + let jobs = jobs(&cut); + pool.each(jobs.len(), &|j| { + let mut notes = Notes::default(); + for &(at, now, held) in &work[jobs[j].clone()] { + // SAFETY: each piece its own bytes, which the caller keeps. + unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside_on(), std::ptr::null()) }; + } + notes.flush(); + }); +} + +/// [`Pool::each`] on threads kept for resetting host lists that have run +/// (`crate::list::recycle`; `VICTORY_RESET_THREADS`, 6 with this one). +pub(crate) fn each_reset(count: usize, f: &(dyn Fn(usize) + Sync)) { + static POOL: OnceLock<&'static Pool> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::env::var("VICTORY_RESET_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(6usize); + Pool::new("victory-reset", threads.clamp(1, 8)) + }) + .each(count, f); +} + /// [`Pool::each`] on threads kept for the title's bytes under flights' writes /// (`VICTORY_UNDER_THREADS`, 6 with this one). pub(crate) fn each_under(count: usize, f: &(dyn Fn(usize) + Sync)) { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index f1cc6bede..997c7a32e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -17,6 +17,8 @@ #[cfg(windows)] mod ambient; +pub mod bench; +mod bench_gpu; #[cfg(all(windows, feature = "diagnostics"))] mod capture; #[cfg(windows)] @@ -24,10 +26,25 @@ mod compose; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; +#[cfg(windows)] +mod copystat_footprint; +#[cfg(windows)] +mod tight; + +/// Release builds with the `mimalloc` feature: the Rust side allocates +/// through mimalloc (per-thread caches) instead of the process heap, which +/// it shares with the title and the drivers. Diagnostics builds count every +/// block through `copystat`'s allocator, which then uses mimalloc too. +#[cfg(all(feature = "mimalloc", not(all(windows, feature = "diagnostics"))))] +#[global_allocator] +static MIMALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; + #[cfg(all(windows, feature = "diagnostics"))] mod faultbook; #[cfg(windows)] mod cores; +#[cfg(windows)] +mod demand; pub mod descriptor; pub mod device; #[cfg(windows)] @@ -83,6 +100,9 @@ pub mod shader_cache; mod memory; #[cfg(windows)] mod shadow; +mod sharded; +#[cfg(all(windows, target_arch = "x86_64"))] +mod stages; #[cfg(windows)] mod tiles; pub mod signature; @@ -108,6 +128,14 @@ mod texback; #[cfg(windows)] pub use host::on_failure; +/// The texture book: the title's DirectStorage requests followed as they +/// finish, and what they fill made ready for the card (`texture::ledger`). +#[cfg(windows)] +pub use texture::ledger as texture_book; +/// Decoded DirectStorage outputs kept across runs (`texture::converted`). +#[cfg(windows)] +pub use texture::converted as converted_cache; + /// Whether `switch` is on now, if it is one of those `VICTORY_AB` turns on and /// off while the title runs (`ab`). #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 1d3f364e4..8c3db7c11 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -233,6 +233,17 @@ pub(crate) fn tables_done(lists: &[This]) { } } +/// A thin recording's last reference went away. A submission that took its +/// host lists also took their state via `detach_parts`. +#[cfg(windows)] +fn discard_thin_state(this: This) { + // SAFETY: the recording's private list is idle until it goes into BACKS. + let list = unsafe { &mut *this.cast_mut().cast::<List>() }; + list.earlier.clear(); + list.gate.clear(); + list.state.get_mut().unwrap_or_else(|e| e.into_inner()).tables_done(); +} + /// The host list behind a title list, if there is a host GPU, for a call /// that records into it: counted as a title call, which records an /// indirect execution held back first ([`crate::host::HostList::title_call`]). @@ -273,8 +284,12 @@ impl Detached { &self.host } - /// Releases this list's dynamic descriptor slots once its GPU submission - /// has completed, without waiting for the full `bury_lag` allocator delay. + pub(crate) fn tables_submitted(&mut self, fence: u64) { + self._state.tables_submitted(fence); + } + + /// Clears the descriptor state of a finished list. The slots of a flight + /// were handed off to the heap when the list was submitted. pub(crate) fn release_tables(&mut self) { self._state.tables_done(); } @@ -344,18 +359,53 @@ pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) { if !pools() { return; } + // The room the idle pool has: lists past it are not reset, only let go. + let room = IDLE_MOST.0.saturating_sub(IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len()); + let mut keep: Vec<crate::host::HostList> = Vec::new(); for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { // The descriptor slots and the upload memory its commands named. drop(_state); drop(_uploads); - if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { - continue; + if ran.contains(&i) && keep.len() < room { + keep.push(host); } - // As the title's reset does: what the list kept for its commands - // goes, its allocators stay. - host.reset(); - let bytes = host.scratch_kept(); - let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + } + if keep.is_empty() { + return; + } + let started = std::time::Instant::now(); + // As the title's reset does: what the list kept for its commands goes, + // its allocators stay. Each list's reset is its own allocator's and + // list's (the driver frees what they held), so a flight's lists are + // reset on several threads at once, past a few. + if keep.len() >= RESET_WIDE && reset_wide() { + struct Lists(*const crate::host::HostList); + // SAFETY: each job resets one list of its own, which nothing else + // touches until `each_reset` returns. + unsafe impl Sync for Lists {} + let lists = Lists(keep.as_ptr()); + let count = keep.len(); + crate::land::each_reset(count.div_ceil(RESET_JOB), &|j| { + let lists = &lists; + for n in j * RESET_JOB..((j + 1) * RESET_JOB).min(count) { + // SAFETY: in `keep`, alive until this returns; one job each. + unsafe { &*lists.0.add(n) }.reset(); + } + }); + } else { + keep.iter().for_each(crate::host::HostList::reset); + } + let kept: Vec<(crate::host::HostList, u64)> = keep + .into_iter() + .map(|host| { + let bytes = host.scratch_kept(); + (host, bytes) + }) + .collect(); + RECYCLED[0].fetch_add(kept.len() as u64, std::sync::atomic::Ordering::Relaxed); + RECYCLED[1].fetch_add(started.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed); + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + for (host, bytes) in kept { if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { idle.0.push(Idle(host, bytes)); idle.1 += bytes; @@ -363,6 +413,26 @@ pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) { } } +/// Since the last frame-rate line: host lists reset and kept for reuse +/// ([`recycle`]), and the nanoseconds (wall time) their resets took. +#[cfg(windows)] +pub(crate) static RECYCLED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Lists of one recycling from which they are reset on several threads +/// ([`recycle`]), and the lists a job resets. +#[cfg(windows)] +const RESET_WIDE: usize = 4; +#[cfg(windows)] +const RESET_JOB: usize = 2; + +/// Whether lists are reset on several threads (`VICTORY_RESET_WIDE=0`: one +/// after another on the calling thread, as before). +#[cfg(windows)] +fn reset_wide() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RESET_WIDE").is_none_or(|v| v != "0")) +} + /// A wait for a memory value recorded into list `this`, with waits cut /// into lists (`crate::queue::cuts`). On the console the queue runs the /// list up to the wait, stands there until the value is in memory, and @@ -759,7 +829,7 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT list.gate.clear(); } #[cfg(windows)] - with_state(this, |host, state| { + with_state_on(host_list_held(this), this, |host, state| { host.reset(); state.reset(pipeline); }); @@ -863,15 +933,63 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> .iter() .filter_map(|b| host_barrier(list, b)) .collect(); - // Buffers have host copies, not resources the barrier can name: - // a barrier on one waits for every shader write before it. - if barriers.iter().any(|b| { - b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() - }) { - host.push(UAV_BARRIER); - #[cfg(feature = "diagnostics")] + // Buffers have host copies, not resources the barrier can name directly: + // transitions not leaving `UNORDERED_ACCESS` (`0x8`) need no UAV + // barrier, and UAV-relevant buffer barriers emit a targeted UAV + // barrier on `shadow.buffer` when `shadow::find_any` resolves to one, + // falling back to a global wait (`wait_all`) only otherwise. + const BEGIN_ONLY: u32 = 1; + const UNORDERED_ACCESS: u32 = 0x8; + let mut wait_all = false; + for b in barriers { + if b.kind == 1 || b.first.is_null() { + continue; + } + let Some((addr, len)) = crate::resource::buffer_bytes(b.first) else { + continue; + }; + if b.kind == 0 + && (b.flags & BEGIN_ONLY != 0 || ((b.second >> 32) as u32 & UNORDERED_ACCESS) == 0) + { + continue; + } + if !addr.is_null() + && len > 0 + && let Some(shadow) = crate::shadow::find_any(addr as u64, len) + { + list.keep(&shadow.buffer); + let ptr: This = windows::core::Interface::as_raw(&shadow.buffer).cast_const().cast(); + if !host.iter().any(|h| h.kind == 2 && h.first == ptr) { + host.push(Barrier { kind: 2, flags: 0, first: ptr, second: 0, last: 0 }); + } + } else { + wait_all = true; + } + } + #[cfg(feature = "diagnostics")] + if wait_all { crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); } + // The title's own waits for every shader write (UAV barriers on no + // resource) are that one wait too: one of them at most, and none if + // the last one in the list had nothing recorded after it + // (`VICTORY_MERGE_BARRIERS`). + let before = host.len(); + host.retain(|b| !(b.kind == 2 && b.first.is_null())); + wait_all |= host.len() != before; + let transitions = host.iter().filter(|b| b.kind == 0).count() as u64; + let aliasing = host.iter().filter(|b| b.kind == 1).count() as u64; + let uav = host.iter().filter(|b| b.kind == 2).count() as u64; + crate::host::count_gpu_barriers(transitions, aliasing, uav); + if !host.is_empty() { + list.gpu_step(crate::host::GpuStep::Transitions, 0); + } + if wait_all && list.wait_for_writes() { + if host.is_empty() { + list.gpu_step(crate::host::GpuStep::ShaderWrites, 0); + } + host.push(UAV_BARRIER); + } if !host.is_empty() { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>()); @@ -897,6 +1015,7 @@ pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: if let Some((texture, before)) = list.transition(resource, state) { let state = crate::host::legal_state(texture, state); let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); + crate::host::count_gpu_step(crate::host::GpuStep::OurStates, 0); // SAFETY: an open list and a live texture. unsafe { list.list.ResourceBarrier(&[barrier]) }; } @@ -927,6 +1046,7 @@ fn buffer_copy(this: This, list: &crate::host::HostList, to: *mut u8, from: *con if len == 0 { return; } + list.gpu_step(crate::host::GpuStep::BufferCopies, len as u64); if list.place_copy(to as usize, from as usize, len) { with_state(this, |_, state| state.copied()); } else { @@ -987,6 +1107,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { if unlike(dst, src) { return; } + list.gpu_step(crate::host::GpuStep::TextureCopies, 0); // Two title textures over the same memory have one host // texture between them: the copy would be of that texture onto // itself, which the host does not allow, and it would change @@ -1078,6 +1199,7 @@ extern "system" fn copy_texture_region( else { return; }; + list.gpu_step(crate::host::GpuStep::TextureCopies, 0); let Some(to) = crate::resource::host_resource(dst.resource) else { // Texture to buffer: a read back. The list copies the texels // into a host buffer of ours; once it has run they go to the @@ -1294,7 +1416,7 @@ fn read_back( let bytes = pitch * (rows - 1) + row; let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?; - let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?; + let buffer = host.read_back_pooled(size).ok_or("no read-back buffer")?; // As a texture source of any copy: what shaders wrote to a depth twin // and what the title wrote itself first, then the state. list.twin_use(src.resource, false, false); @@ -1361,6 +1483,7 @@ extern "system" fn resolve( }; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; + list.gpu_step(crate::host::GpuStep::Resolves, 0); const RESOLVE_DEST: u32 = 0x1000; const RESOLVE_SOURCE: u32 = 0x2000; if unlike(dst, src) { @@ -1430,6 +1553,7 @@ extern "system" fn clear_rtv( else { return; }; + list.gpu_step(crate::host::GpuStep::Clears, 0); let (Some(texture), Some(host)) = ( crate::resource::host_resource(record.resource), crate::host::host(), @@ -1481,6 +1605,7 @@ extern "system" fn clear_dsv( else { return; }; + list.gpu_step(crate::host::GpuStep::Clears, 0); let (Some(texture), Some(host)) = ( crate::resource::host_resource(record.resource), crate::host::host(), @@ -1519,6 +1644,7 @@ extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: && src != 0 { let len = len as usize; + list.gpu_step(crate::host::GpuStep::MemoryCopies, len as u64); if list.place_copy(dst as usize, src as usize, len) { with_state(this, |_, state| state.copied()); return; @@ -1653,10 +1779,15 @@ extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size } crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); } - // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; + // (none where the last one in the list had nothing recorded after + // it: `VICTORY_MERGE_BARRIERS`) + if list.wait_for_writes() { + list.gpu_step(crate::host::GpuStep::ShaderWrites, 0); + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } } } let _ = (this, flags, control, address, size); @@ -1931,7 +2062,7 @@ mod state { } fn count_draw() { - DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + DRAWS.add(1); } /// Draws of the kinds the host does not run yet (indirect, mesh), and @@ -2010,20 +2141,21 @@ pub(crate) fn take_indirect() -> u64 { } static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); fn count_dispatch() { - DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + DISPATCHES.add(1); } #[cfg(not(windows))] extern "system" fn dispatch(_: This) { count_dispatch(); } -static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// (Added to by every draw on every recording and translating thread: one +/// place per thread, `crate::sharded`.) +static DRAWS: crate::sharded::Counter = crate::sharded::Counter::new(); +static DISPATCHES: crate::sharded::Counter = crate::sharded::Counter::new(); /// Draws (any kind, mesh and indirect included) and compute dispatches /// recorded since the last call. pub(crate) fn take_counts() -> (u64, u64) { - use std::sync::atomic::Ordering::Relaxed; - (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) + (DRAWS.take(), DISPATCHES.take()) } /// A GPU wait for a memory value: the list's commands after it run when @@ -2222,10 +2354,15 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; with_state(this, |_, state| state.synced()); - // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; + // (none where the last one in the list had nothing recorded after it: + // `VICTORY_MERGE_BARRIERS`) + if list.wait_for_writes() { + list.gpu_step(crate::host::GpuStep::ShaderWrites, 0); + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } } #[cfg(not(windows))] let _ = (this, count); diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index e2371c308..66e158b84 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -144,7 +144,7 @@ impl Front { !std::mem::replace(&mut inner.scheduled, true) }; if schedule { - held(&READY).push_back(recording.clone()); + held(&READY).push(recording.clone()); WORK.notify_one(); } } @@ -161,8 +161,38 @@ impl Front { /// Streams' memory to use again. static WORDS: Mutex<Vec<Vec<u64>>> = Mutex::new(Vec::new()); -/// Recordings with words to translate. -static READY: Mutex<VecDeque<Arc<Recording>>> = Mutex::new(VecDeque::new()); +/// Recordings with words to translate. Finish submitted work before taking +/// another speculative recording that will hold descriptor slots. +static READY: Mutex<Ready> = Mutex::new(Ready { submitted: VecDeque::new(), ahead: VecDeque::new() }); + +struct Ready { + submitted: VecDeque<Arc<Recording>>, + ahead: VecDeque<Arc<Recording>>, +} + +impl Ready { + fn push(&mut self, recording: Arc<Recording>) { + if recording.submitted.load(Relaxed) { + self.submitted.push_back(recording); + } else { + self.ahead.push_back(recording); + } + } + + fn prioritize(&mut self, recordings: &[Arc<Recording>]) { + for recording in recordings { + if !recording.submitted.swap(true, Relaxed) + && let Some(index) = self.ahead.iter().position(|other| Arc::ptr_eq(other, recording)) + { + self.submitted.push_back(self.ahead.remove(index).unwrap()); + } + } + } + + fn pop(&mut self) -> Option<Arc<Recording>> { + self.submitted.pop_front().or_else(|| self.ahead.pop_front()) + } +} static WORK: Condvar = Condvar::new(); /// Lists of ours nobody uses, closed. static BACKS: Mutex<Vec<usize>> = Mutex::new(Vec::new()); @@ -185,6 +215,8 @@ pub(crate) struct Recording { done: AtomicBool, moved: Condvar, abandoned: AtomicBool, + /// Accessed under READY while scheduling translation. + submitted: AtomicBool, } #[derive(Default)] @@ -208,6 +240,7 @@ impl Recording { done: AtomicBool::new(false), moved: Condvar::new(), abandoned: AtomicBool::new(false), + submitted: AtomicBool::new(false), } } @@ -243,9 +276,18 @@ impl Recording { (chunk, inner.back as This) }; let began = std::time::Instant::now(); + let trace_start = crate::host::render_trace::active().then(crate::host::now_us); let (calls, closed) = translate(back, &chunk, || self.abandoned.load(Acquire)); STATS[0].fetch_add(calls, Relaxed); STATS[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + if let Some(start) = trace_start { + let list = super::host_list_held(back).map_or(0, |host| windows::core::Interface::as_raw(&host.list) as usize); + crate::host::render_trace::event( + "translate_list", + format_args!("recording={:#x}\tlist={list:#x}\tstart_us={start}\tduration_us={}\tcalls={calls}\tclosed={closed}", + std::ptr::from_ref(self) as usize, began.elapsed().as_micros()), + ); + } let mut inner = held(&self.inner); inner.kept.push(chunk); if closed { @@ -272,6 +314,7 @@ impl Drop for Recording { STATS[3].fetch_add(1, Relaxed); super::close(inner.back as This); } + super::discard_thin_state(inner.back as This); held(&BACKS).push(inner.back); } } @@ -309,7 +352,7 @@ fn start() { let recording = { let mut ready = held(&READY); loop { - match ready.pop_front() { + match ready.pop() { Some(r) => break r, None => ready = WORK.wait(ready).unwrap_or_else(|e| e.into_inner()), } @@ -330,7 +373,7 @@ fn start() { /// The recordings of submitted lists, in order (one that was not begun is left /// out). pub(crate) fn submitted(lists: &[This]) -> Arc<[Arc<Recording>]> { - lists + let recordings: Arc<[_]> = lists .iter() .filter(|l| !l.is_null()) .filter_map(|&l| { @@ -340,7 +383,9 @@ pub(crate) fn submitted(lists: &[This]) -> Arc<[Arc<Recording>]> { front.submitted = true; front.recording.clone() }) - .collect() + .collect(); + held(&READY).prioritize(&recordings); + recordings } /// For the frame-rate line. @@ -884,6 +929,22 @@ const MINE: [(usize, *const ()); 50] = [ mod tests { use super::*; + #[test] + fn submitted_recordings_take_priority_in_submission_order() { + let first = Arc::new(Recording::new(0)); + let second = Arc::new(Recording::new(0)); + let ahead = Arc::new(Recording::new(0)); + let mut ready = Ready { submitted: VecDeque::new(), ahead: VecDeque::new() }; + ready.push(ahead.clone()); + ready.push(second.clone()); + ready.push(first.clone()); + ready.prioritize(&[first.clone(), second.clone(), first.clone()]); + assert!(Arc::ptr_eq(&ready.pop().unwrap(), &first)); + assert!(Arc::ptr_eq(&ready.pop().unwrap(), &second)); + assert!(Arc::ptr_eq(&ready.pop().unwrap(), &ahead)); + assert!(ready.pop().is_none()); + } + /// Every method of the tables that records is written down too: what is /// left in both tables alike records nothing. #[test] diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index b03009435..c8a171dca 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -87,7 +87,7 @@ const PIECE: usize = 4096; /// Pages held, at most (3 GiB). const MOST: usize = 3 << 14; /// Pages of title memory with small title buffers in them, at most. -const WINDOWS: usize = 512; +const WINDOWS: usize = 2048; /// The biggest packed structure taken for one. const PACKED: u64 = 64 << 20; /// For so many frames what a page holds may still be on its way. @@ -435,13 +435,31 @@ impl Memory { } } + /// Coalesces sorted `pages` into contiguous runs and calls [`Memory::bring`] + /// on each run. + fn bring_pages(&mut self, pages: &[u64]) { + let Some(&first) = pages.first() else { return }; + let (mut run_start, mut run_end) = (first, first + 1); + for &page in &pages[1..] { + if page == run_end { + run_end += 1; + } else { + self.bring(run_start, run_end); + run_start = page; + run_end = page + 1; + } + } + self.bring(run_start, run_end); + } + /// Looks at some of the pages and packed structures again. fn look_again(&mut self) { + let mut sweep_pages = Vec::new(); for _ in 0..self.order.len().div_ceil(SWEEP) { self.sweep = (self.sweep + 1) % self.order.len(); let page = self.order[self.sweep]; if self.pages.contains_key(&page) { - self.bring(page, page + 1); + sweep_pages.push(page); } else { self.order.swap_remove(self.sweep); if self.order.is_empty() { @@ -449,6 +467,9 @@ impl Memory { } } } + sweep_pages.sort_unstable(); + sweep_pages.dedup(); + self.bring_pages(&sweep_pages); for _ in 0..self.packed_order.len().div_ceil(SWEEP) { self.packed_sweep = (self.packed_sweep + 1) % self.packed_order.len(); let address = self.packed_order[self.packed_sweep]; @@ -675,13 +696,15 @@ impl Memory { } pages.sort_unstable(); let mut made = 0; + let mut mapped = Vec::new(); for &page in &pages { if made < FAULTS && self.faulted < FAULTS_ALL && self.copy_of(page).is_none() && self.map(page) { made += 1; self.faulted += 1; - self.bring(page, page + 1); + mapped.push(page); } } + self.bring_pages(&mapped); self.stats.faults += pages.len() as u64; // Each is an access that read 0 or was dropped. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -796,36 +819,34 @@ impl Memory { /// A list with this key ([`HostList::used`]) asks the builder for sizes. const SIZES: usize = usize::MAX - (9 << 33); +/// Whether the current frame recorded a dispatch that asks for BVH sizes. +static SIZES_FRAME: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Returns and clears whether the frame recorded a BVH size query, so `present` +/// drains submissions before the next frame reads the compacted-size slot. +pub(crate) fn take_sizes_frame() -> bool { + SIZES_FRAME.swap(false, std::sync::atomic::Ordering::AcqRel) +} + /// Whether a submission that asks for the sizes of structures is waited for, -/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=1`; off). -/// -/// Off: it does not help. In run light-15, with it, 33 of 154 copies had the -/// slot's old size still (all of them recorded one frame after the size was -/// asked for) against 53 of 230 in light-11, 48 of 275 dynamic structures -/// were good, and the title asks in every frame, so every frame waits (109 ms -/// against 90). The title reads the slot before our submission of the asking -/// list is through, or reads it for another purpose; not known. -/// -/// The title asks for a new structure's compacted size (a program of one -/// thread stores it into a small buffer), reads it a frame or two later -/// without looking whether it is there, takes memory of that size and copies -/// the structure into it. With submissions that land up to two frames late it -/// read what the slot held before, some other structure's size, and the copy -/// wrote over its neighbours: of 230 such copies of run light-11, 99 were -/// asked for two frames earlier and landed in that frame, none of those with -/// the right size. +/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT`; on with +/// `VICTORY_BVH_BUILDER=1` unless `=0`). fn sizes_wait() -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_some_and(|v| v == "1")) + *ON.get_or_init(|| match std::env::var("VICTORY_BVH_SIZES_WAIT").ok().as_deref().map(str::trim) { + Some("0") => false, + Some("1") => true, + _ => crate::pipeline::builder_runs(), + }) } /// Whether a dispatch of the builder is its program of a structure's size: /// one thread, the structure's address and what to store (1: the compacted -/// size) as constants, a small title buffer to store into. +/// size) as constants, a title buffer to store into. fn asks_size(written: &[u64], constants: &[u32], threads: Option<[u32; 3]>) -> bool { threads == Some([1, 1, 1]) && matches!(*constants, [_, hi, 1..=3, ..] if (1..0x20).contains(&hi)) - && written.first().is_some_and(|&at| crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK)) + && written.first().is_some_and(|&at| crate::shadow::in_buffer(at, 1).is_some()) } /// Whether one of `lists` asks for sizes. @@ -923,8 +944,10 @@ pub(crate) fn ready( m.trace.dispatch(frame, list, addresses, written, constants, threads); } let builds = use_ != Use::Reads; - if builds && sizes_wait() && asks_size(written, constants, threads) { + let asked_size = builds && sizes_wait() && asks_size(written, constants, threads); + if asked_size { list.first_use(SIZES); + SIZES_FRAME.store(true, std::sync::atomic::Ordering::Release); } while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {} m.stats.uses[usize::from(builds)] += 1; @@ -984,15 +1007,21 @@ pub(crate) fn ready( m.land(at); } }); - m.bring_up(list); + if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) { + m.bring_up(list); + } } if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) { - if let Some((start, len)) = crate::shadow::in_buffer(at, 1) - && len <= BACK - && use_ == (Use::Builds { back: true }) - && list.first_use(usize::MAX - (5 << 33) - (start >> 2 & 0x7FFF_FFFF) as usize) + if use_ == (Use::Builds { back: true }) + && let Some((start, len)) = crate::shadow::in_buffer(at, 1) { - m.small(list, start, len); + if len <= BACK { + if list.first_use(usize::MAX - (5 << 33) - (start >> 2 & 0x7FFF_FFFF) as usize) { + m.small(list, start, len); + } + } else if asked_size { + m.small(list, at & !0xFF, 256); + } } m.opens(at); if !packed && crate::shadow::in_buffer(at, 1).is_none() { @@ -1030,7 +1059,7 @@ pub(crate) fn ready( Some(&run) => run, None => { // Held for the heap's life: not given back with a list's slots. - let base = heap.dynamic(COPIES + 1)?; + let base = heap.reserve_dynamic(COPIES + 1)?; // Every slot of the run: a number shows no view of another kind. for n in 0..=COPIES { heap.null_raw_uav_at(base + n); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index c462b0e25..e8cd4eac8 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -439,7 +439,10 @@ pub(crate) fn bound(this: This) { return; } let p = pipeline(this); - if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) { + // Looked at first: a swap writes the pipeline's line on every bind, on + // every thread that binds it, and the lookups of its host pipeline + // (`host_pipeline`) read that line. + if p.bound.load(std::sync::atomic::Ordering::Relaxed) || p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) { return; } let frame = crate::frame::current(); @@ -574,7 +577,8 @@ fn hand_out( ) -> HRESULT { tracing::trace!(?shaders, "pipeline state"); #[cfg(windows)] - let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); + // (The pipeline of earlier runs made ahead for this one, if there is one.) + let host = make::adopt(make::Pending::new(shaders.clone(), graphics)); #[cfg(windows)] known::note(host.key(), &shaders, host.graphics.as_deref()); #[cfg(windows)] @@ -770,6 +774,16 @@ pub mod known; mod library; #[cfg(windows)] mod make; +#[cfg(windows)] +mod samplers; + +/// Makes the static sampler states of earlier runs on the host device, in +/// their order, before anything else makes one (`samplers::replay`): called +/// right after the device is made. +#[cfg(windows)] +pub(crate) fn replay_static_samplers(device: &windows::Win32::Graphics::Direct3D12::ID3D12Device) { + samplers::replay(device); +} /// Lets the pipeline library's mapped file go from memory when no pipeline /// has loaded for a while (`library::trim`); called by the host's sweep. diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 2e2d0bd55..c2c2698c8 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -361,6 +361,7 @@ pub(crate) struct Stage { /// The root parameter of its user data, and its size in dwords. pub(crate) user_data: Option<(u32, u32)>, /// Root parameters of its root views: (title root parameter, ours). + /// Constant buffers are raw root SRVs (`victory_shader::emit::HostShader::root_cbvs`). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, /// Root UAVs: one-view tables like the SRVs (or root descriptors with @@ -498,21 +499,29 @@ impl HostPipeline { ShaderVisibility: visibility, }); } - for (slots, kind, out) in [ + // Root constant buffers are raw root SRVs (`t<slot>`): the + // translation reads them as raw bytes, at the title's address, + // which needs 4 bytes where a CBV needs 256 (the title's lie on + // 16), and reads zeros past the 64 KiB a CBV shows itself. So + // they stay root descriptors, never one-view tables. + for (slots, kind, out, constants) in [ ( &t.root_cbvs, - D3D12_ROOT_PARAMETER_TYPE_CBV, + D3D12_ROOT_PARAMETER_TYPE_SRV, &mut stage.root_cbvs, + true, ), ( &t.root_srvs, D3D12_ROOT_PARAMETER_TYPE_SRV, &mut stage.root_srvs, + false, ), ( &t.root_uavs, D3D12_ROOT_PARAMETER_TYPE_UAV, &mut stage.root_uavs, + false, ), ] { for &slot in slots { @@ -527,7 +536,7 @@ impl HostPipeline { || slot == victory_shader::emit::SLOT_TABLE_STRIDES || slot == victory_shader::emit::SLOT_MEMORY }; - if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && !constants && bounded_root_srvs() { // A one-view table: the view's size bounds the // reads (and a root UAV's writes), which a root // descriptor leaves unbounded. @@ -599,9 +608,9 @@ impl HostPipeline { return None; } }; - // Not from the library if it has static samplers (their places in the - // driver's table differ between runs: `library::with_static_samplers`). - let _samplers = super::library::with_static_samplers(!samplers.is_empty()); + // From the library with static samplers only where their places in + // the driver's table are those of earlier runs (`pipeline::samplers`). + let _samplers = super::library::with_static_samplers(super::samplers::admit(&samplers)); let code = |i: usize| { stages.get(i).and_then(|(s, _)| s.translated()).map_or( D3D12_SHADER_BYTECODE::default(), diff --git a/crates/victory-gpu/src/pipeline/known.rs b/crates/victory-gpu/src/pipeline/known.rs index 621e80526..82c806243 100644 --- a/crates/victory-gpu/src/pipeline/known.rs +++ b/crates/victory-gpu/src/pipeline/known.rs @@ -260,10 +260,129 @@ pub fn make(dir: &Path, which: &[usize], mut each: impl FnMut(usize, Option<(f64 } } +/// The pipelines earlier runs requested are made from the moment this is +/// called (the title not yet started), in the order they first requested +/// them, on the pipeline workers, in this process: the title's own creation of +/// each finds it made or queued ([`super::make::adopt`]). A first run (nothing +/// recorded) only records. Called once, with the cache folders in place +/// (`use_pipeline_cache`), by the run of a title; not by `victory warm`. +/// +/// While the title loads ([`super::make`]'s `LOADING`) the workers but one run +/// at normal priority; a frame of a world's worth of draws ends that. +pub fn prewarm() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let Some(dir) = super::library::folder() else { return }; + super::make::prewarm_begin(); + let spawned = std::thread::Builder::new().name("victory-prewarm".into()).spawn(move || { + queue_earlier(&dir); + super::make::prewarm_end(); + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "pipelines of earlier runs are not made ahead"); + super::make::prewarm_end(); + } + }); +} + +/// The 16 bytes of a pipeline's key. +fn id_of(key: &str) -> Option<[u8; 16]> { + let mut id = [0u8; 16]; + for (at, b) in id.iter_mut().enumerate() { + *b = u8::from_str_radix(key.get(2 * at..2 * at + 2)?, 16).ok()?; + } + (key.len() == 32).then_some(id) +} + +/// Reads the earlier runs' pipelines from the books and queues them in the +/// order of first use ([`prewarm`]). +fn queue_earlier(dir: &Path) { + let began = std::time::Instant::now(); + let keys = super::library::plan(); + if keys.is_empty() { + tracing::info!("pipeline prewarm: no pipeline recorded by earlier runs (a first run only records)"); + return; + } + super::make::prewarm_plan(&keys); + // The host device, as the title's first pipeline would make it. + if crate::host::host().is_none() { + return; + } + let mut places = HashMap::new(); + walk_shaders(dir, |_, hash, at, len| drop(places.insert(hash, (at, len)))); + let Ok(mut file) = std::fs::File::open(dir.join(SHADERS)) else { + tracing::info!("pipeline prewarm: no book of the title's shaders (VICTORY_PIPELINE_BOOK=1 writes it)"); + return; + }; + let ids: Vec<Option<[u8; 16]>> = keys.iter().map(|k| id_of(k)).collect(); + let wanted: HashSet<[u8; 16]> = ids.iter().flatten().copied().collect(); + let mut entries: HashMap<[u8; 16], Vec<u8>> = HashMap::new(); + walk_pipelines(dir, |_, bytes| { + if let Some(id) = bytes.first_chunk::<16>() + && wanted.contains(id) + { + entries.insert(*id, bytes.to_vec()); + } + }); + let (mut queued, mut missing, mut unreadable, mut changed, mut by_the_title) = (0usize, 0usize, 0usize, 0usize, 0usize); + let mut shaders: HashMap<[u8; 32], Arc<Shader>> = HashMap::new(); + for (key, id) in keys.iter().zip(&ids) { + let Some(entry) = id.and_then(|id| entries.get(&id)) else { + missing += 1; + continue; + }; + let parsed = parse_by(entry, &mut |stage, hash| { + if let Some(s) = shaders.get(hash) { + return Some(s.clone()); + } + let &(at, len) = places.get(hash)?; + let mut bytes = vec![0; len as usize]; + file.seek(SeekFrom::Start(at)).ok()?; + file.read_exact(&mut bytes).ok()?; + let s = super::shader(STAGES.get(usize::from(stage))?, &bytes); + shaders.insert(*hash, s.clone()); + Some(s) + }); + let Some((parsed, graphics)) = parsed else { + unreadable += 1; + continue; + }; + let pending = super::make::Pending::new(parsed, graphics); + if pending.key() != key.as_str() { + changed += 1; + continue; + } + if super::make::prewarm_add(pending) { + queued += 1; + } else { + by_the_title += 1; + } + } + tracing::info!( + planned = keys.len(), + queued, + not_in_the_books = missing, + unreadable, + key_changed = changed, + created_by_the_title_first = by_the_title, + ms = began.elapsed().as_millis() as u64, + "pipeline prewarm: pipelines of earlier runs queued, first used first" + ); +} + #[allow(clippy::type_complexity)] fn parse( entry: &[u8], read: &mut impl FnMut(&[u8; 32]) -> Option<Vec<u8>>, +) -> Option<(Vec<Arc<Shader>>, Option<Box<GraphicsState>>)> { + parse_by(entry, &mut |stage, hash| Some(super::shader(STAGES.get(usize::from(stage))?, &read(hash)?))) +} + +/// As [`parse`], the shaders (by stage number and hash) from `get`. +#[allow(clippy::type_complexity)] +fn parse_by( + entry: &[u8], + get: &mut impl FnMut(u8, &[u8; 32]) -> Option<Arc<Shader>>, ) -> Option<(Vec<Arc<Shader>>, Option<Box<GraphicsState>>)> { let mut rest = entry.get(16..)?; let (&count, after) = rest.split_first()?; @@ -274,7 +393,7 @@ fn parse( rest = after; let mut hash = [0; 32]; hash.copy_from_slice(&head[1..]); - shaders.push(super::shader(STAGES.get(usize::from(head[0]))?, &read(&hash)?)); + shaders.push(get(head[0], &hash)?); } let (&graphics, rest) = rest.split_first()?; let g = match graphics { @@ -465,6 +584,15 @@ mod tests { assert!(GraphicsState::get(&bytes[..9]).is_none()); } + #[test] + fn a_key_is_sixteen_bytes() { + let id = id_of("000102030405060708090a0b0c0d0e0f").unwrap(); + assert_eq!(id[..3], [0, 1, 2]); + assert_eq!(id[15], 15); + assert!(id_of("0001").is_none()); + assert!(id_of(&"zz".repeat(16)).is_none()); + } + #[test] fn a_torn_end_is_not_read() { let dir = std::env::temp_dir().join(format!("victory-known-{}", std::process::id())); diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index f81db5772..361e153a2 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -255,14 +255,15 @@ static CALLS: Mutex<Vec<(u32, &'static str, String, u64)>> = Mutex::new(Vec::new thread_local! { /// The pipeline this thread is making (its shaders), for [`CALLS`]. static LABEL: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) }; - /// Whether the pipeline this thread makes has static samplers - /// ([`with_static_samplers`]). - static STATIC_SAMPLERS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// How the pipeline this thread makes may use the library for its + /// static samplers ([`with_static_samplers`]). + static STATIC_SAMPLERS: std::cell::Cell<super::samplers::Use> = + const { std::cell::Cell::new(super::samplers::Use::Plain) }; } /// The pipelines this thread makes while the guard lives have static -/// samplers (`samplers`): they are made, never loaded from or stored in the -/// library, unless `VICTORY_LIBRARY_STATIC_SAMPLERS=1`. +/// samplers, and `use_` says whether they may come from and go into the +/// library ([`super::samplers::admit`]). /// /// Why: the card's driver (NVIDIA, 4070 SUPER) keeps static samplers in a /// table of its own and puts their places in that table into the compiled @@ -278,18 +279,18 @@ thread_local! { /// 0.44 stops with green and magenta fringes (2026-11-26 runs; made in the /// run, the image was smooth). Every loaded pipeline with static samplers /// may read through another one's: other filters, address modes, levels -/// and comparisons. -/// shortcut: they are compiled every run (the driver's own cache on disk -/// makes that quick); a fixed order of static samplers made before any -/// pipeline would let the library keep them again. -pub(crate) fn with_static_samplers(samplers: bool) -> StaticSamplers { - StaticSamplers(STATIC_SAMPLERS.replace(samplers && !static_samplers_kept())) +/// and comparisons. [`super::samplers`] makes the states of earlier runs +/// first, in their order, so they keep their places: pipelines with only +/// those come from the library under a name that holds their places +/// ([`super::samplers::Use::Placed`]); the others are made. +pub(crate) fn with_static_samplers(use_: super::samplers::Use) -> StaticSamplers { + StaticSamplers(STATIC_SAMPLERS.replace(use_)) } -/// While it lives, the pipelines this thread makes skip the library if they -/// have static samplers ([`with_static_samplers`]); the setting before it -/// comes back when it is dropped. -pub(crate) struct StaticSamplers(bool); +/// While it lives, the pipelines this thread makes use the library as +/// [`with_static_samplers`] was told; the setting before it comes back when +/// it is dropped. +pub(crate) struct StaticSamplers(super::samplers::Use); impl Drop for StaticSamplers { fn drop(&mut self) { @@ -297,15 +298,6 @@ impl Drop for StaticSamplers { } } -/// `VICTORY_LIBRARY_STATIC_SAMPLERS=1`: pipelines with static samplers are -/// loaded from and stored in the library too, as before. -fn static_samplers_kept() -> bool { - static ON: OnceLock<bool> = OnceLock::new(); - *ON.get_or_init(|| { - std::env::var_os("VICTORY_LIBRARY_STATIC_SAMPLERS").is_some_and(|v| v == "1") - }) -} - /// Names the pipeline this thread makes next. pub(crate) fn label(text: String) { LABEL.with(|l| *l.borrow_mut() = text); @@ -568,10 +560,26 @@ pub(crate) fn pipeline( load: impl FnOnce(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result<ID3D12PipelineState>, create: impl FnOnce() -> windows::core::Result<ID3D12PipelineState>, ) -> windows::core::Result<ID3D12PipelineState> { + use super::samplers::Use; + let samplers = STATIC_SAMPLERS.get(); + // A pipeline with static samplers is named by their places in the + // driver's table as well: one stored where they had other places is + // never looked up. + let salted; + let name = match samplers { + Use::Placed(tag) => { + salted = format!("{name}-s{tag:016x}"); + salted.as_str() + } + Use::Plain | Use::Unplaced => name, + }; let wide = HSTRING::from(name); - let Some(library) = library().filter(|_| !STATIC_SAMPLERS.get()) else { + let Some(library) = library().filter(|_| samplers != Use::Unplaced) else { MADE.fetch_add(1, Ordering::Relaxed); - return create(); + let made_at = std::time::Instant::now(); + let pso = create(); + record(if samplers == Use::Unplaced { Kind::StaticSamplers } else { Kind::Made }, made_at); + return pso; }; let began = std::time::Instant::now(); let loaded = { @@ -586,6 +594,7 @@ pub(crate) fn pipeline( let refused = match loaded { Ok(pso) => { LOADED.fetch_add(1, Ordering::Relaxed); + record(Kind::Loaded, began); crate::host::trail(|| { let label = LABEL.with(|l| l.borrow().clone()); format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3) @@ -595,10 +604,12 @@ pub(crate) fn pipeline( Err(e) => e, }; // Compiled outside any lock: compiles take up to seconds. + let made_at = std::time::Instant::now(); let pso = { let _call = call("make", name); create()? }; + record(Kind::Made, made_at); MADE.fetch_add(1, Ordering::Relaxed); crate::host::trail(|| { let label = LABEL.with(|l| l.borrow().clone()); @@ -618,15 +629,56 @@ pub(crate) fn pipeline( Ok(pso) } +/// As [`save`], from a worker while more pipelines are still queued. +/// +/// Every save serialises the whole library (over a gigabyte once it is warm) +/// and, while it does, holds off every store; in the middle of a burst of new +/// pipelines (a new area, a cutscene) that is exactly when the title is +/// waiting on them, and the write competes with texture streaming for the +/// disk. Saves in a burst are kept to one every `VICTORY_LIBRARY_SAVE_BUSY_S` +/// seconds (default 180; 20 as before); the save when the queue runs dry and +/// the one at exit are as they were. +pub(crate) fn save_while_busy() { + static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); + static EVERY: OnceLock<std::time::Duration> = OnceLock::new(); + let every = *EVERY.get_or_init(|| { + let secs = std::env::var("VICTORY_LIBRARY_SAVE_BUSY_S").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(180); + std::time::Duration::from_secs(secs) + }); + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + match *last { + // The first busy save of the run waits a full interval too. + None => { + *last = Some(std::time::Instant::now()); + return; + } + Some(t) if t.elapsed() < every => return, + _ => *last = Some(std::time::Instant::now()), + } + } + save(false); +} + /// Writes the library and the early list if pipelines were added since the /// last save and `SAVE_EVERY` has passed (or `now`). +/// +/// Under host memory pressure ([`crate::residency::pressured`]) the interval +/// is `SAVE_EVERY_PRESSURED` instead: the serialised library (over a gigabyte +/// once warm) is written through the PC's memory, and on a 32 GB PC that ran +/// pressured for a whole session (log of 2026-11-27, commit headroom 3.4 GB) +/// those pages pushed the title's own out, and its threads stalled on page +/// faults. The save at exit (`now`) is unchanged, so nothing made is lost +/// unless the process ends without one. pub(crate) fn save(now: bool) { static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); + const SAVE_EVERY_PRESSURED: std::time::Duration = std::time::Duration::from_secs(600); let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; { let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); - if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + let every = if crate::residency::pressured() { SAVE_EVERY_PRESSURED } else { SAVE_EVERY }; + if !now && last.is_some_and(|t| t.elapsed() < every) { return; } *last = Some(std::time::Instant::now()); @@ -666,7 +718,8 @@ pub(crate) fn save(now: bool) { }; // Through `used`: a process that asked for none yet (`victory shaders`) // must not write the earlier runs' list over with nothing. - let used: Vec<String> = used().iter().flatten().cloned().collect(); + let used: Vec<String> = ordered(used().iter().flatten().cloned().collect()); + let order = order_text(); let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; if bytes > 0 && library_written.is_ok() { // In place unless the system refused and the new one waits beside it. @@ -685,7 +738,8 @@ pub(crate) fn save(now: bool) { let slow: Vec<String> = slow_ones().iter().flatten().map(|(key, ms)| format!("{key} {ms}")).collect(); let written = library_written .and_then(|()| write_atomically(&dir.join(SLOW_FILE), slow.join("\n").as_bytes())) - .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); + .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())) + .and_then(|()| write_atomically(&dir.join(ORDER_FILE), order.as_bytes())); match written { Ok(()) => tracing::info!( bytes, @@ -697,6 +751,7 @@ pub(crate) fn save(now: bool) { ), Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), } + log_summary(false); } /// Writes the library's `size` serialised bytes to the file `tmp`: through @@ -777,6 +832,13 @@ pub(crate) fn slow(key: &str) -> bool { /// The title pipeline with `key` took `ms` to make. pub(crate) fn note_time(key: &str, ms: u64) { + { + let mut now = NOW.lock().unwrap_or_else(|e| e.into_inner()); + let now = now.get_or_insert_default(); + if now.ms.len() < EARLY_MAX || now.ms.contains_key(key) { + now.ms.insert(key.to_owned(), ms.min(u64::from(u32::MAX)) as u32); + } + } if ms < SLOW_MS { return; } @@ -822,6 +884,15 @@ pub(crate) fn wanted_early(key: &str) -> bool { /// A draw or dispatch requested the title pipeline with `key`. pub(crate) fn note_used(key: &str) { + { + let mut now = NOW.lock().unwrap_or_else(|e| e.into_inner()); + let now = now.get_or_insert_default(); + if now.order.len() < EARLY_MAX && now.seen.insert(key.to_owned()) { + now.order.push(key.to_owned()); + // The order file is written with the next save. + USED_CHANGED.store(true, Ordering::Relaxed); + } + } let mut used = used(); let set = used.get_or_insert_with(HashSet::new); if set.len() < EARLY_MAX && set.insert(key.to_owned()) { @@ -829,10 +900,191 @@ pub(crate) fn note_used(key: &str) { } } +/// Title pipelines in the order a run first drew or dispatched with them, +/// and the milliseconds each took to make (all of them, not only the slow +/// ones), one `key ms` a line, the first used first. The early list beside +/// it holds the same keys in the same order, so a build that reads it as a +/// set does as before; a missing or odd order file only means no order is +/// known (the title's creation order, as before). +const ORDER_FILE: &str = "pipeline-order.txt"; + +/// What this run has seen: keys in first-use order, and make times. +#[derive(Default)] +struct Now { + order: Vec<String>, + seen: HashSet<String>, + ms: std::collections::HashMap<String, u32>, +} + +static NOW: Mutex<Option<Now>> = Mutex::new(None); + +type Earlier = std::collections::HashMap<String, (u64, u32)>; + +/// Parses [`ORDER_FILE`]: key to (place in the order, ms). +fn parse_order(text: &str) -> Earlier { + let mut map = Earlier::new(); + for line in text.lines() { + let mut parts = line.split_whitespace(); + let Some(key) = parts.next() else { continue }; + let ms = parts.next().and_then(|m| m.parse().ok()).unwrap_or(0); + let rank = map.len() as u64; + map.entry(key.to_owned()).or_insert((rank, ms)); + } + map +} + +/// The order the earlier runs first used pipelines in. +fn previous() -> &'static Earlier { + static PREVIOUS: OnceLock<Earlier> = OnceLock::new(); + PREVIOUS.get_or_init(|| { + let text = DIR.get().and_then(|d| std::fs::read_to_string(d.join(ORDER_FILE)).ok()).unwrap_or_default(); + let map = parse_order(&text); + tracing::info!(pipelines = map.len(), "title pipelines with a recorded first-use order"); + map + }) +} + +/// Where the title pipeline with `key` came in the earlier runs' order of +/// first use: lower is sooner; `u64::MAX` if not known. +pub(crate) fn rank(key: &str) -> u64 { + previous().get(key).map_or(u64::MAX, |&(rank, _)| rank) +} + +/// The earlier runs' keys, in their order. +fn before() -> Vec<&'static String> { + let mut before: Vec<(&String, u64)> = previous().iter().map(|(k, &(r, _))| (k, r)).collect(); + before.sort_by_key(|&(_, r)| r); + before.into_iter().map(|(k, _)| k).collect() +} + +/// The keys of `used` in first-use order: this run's first, then the earlier +/// runs' that this one has not used (in their order), then the rest. +fn ordered(used: HashSet<String>) -> Vec<String> { + let mut out: Vec<String> = Vec::with_capacity(used.len()); + let mut put = HashSet::new(); + let now = NOW.lock().unwrap_or_else(|e| e.into_inner()); + let this_run = now.as_ref().map_or(&[][..], |n| &n.order[..]); + for key in this_run.iter().chain(before()) { + if used.contains(key) && put.insert(key.clone()) { + out.push(key.clone()); + } + } + let mut rest: Vec<&String> = used.iter().filter(|k| !put.contains(*k)).collect(); + rest.sort(); + out.extend(rest.into_iter().cloned()); + out +} + +/// The title pipelines earlier runs requested, in the order they first did +/// (those with no recorded place last, by key): what the prewarm makes at the +/// start, before the title creates them (`known::prewarm`). Empty on a first +/// run, which only records. +pub(super) fn plan() -> Vec<String> { + let set: HashSet<String> = used().iter().flatten().cloned().collect(); + ordered(set) +} + +/// The text of [`ORDER_FILE`] for a save: this run's pipelines in the order +/// they were first used, then the earlier runs' others in theirs. +fn order_text() -> String { + let now = NOW.lock().unwrap_or_else(|e| e.into_inner()); + let this_run = now.as_ref().map_or(&[][..], |n| &n.order[..]); + let ms_of = |key: &str| { + now.as_ref().and_then(|n| n.ms.get(key).copied()).or_else(|| previous().get(key).map(|p| p.1)).unwrap_or(0) + }; + let mut lines: Vec<String> = Vec::new(); + let mut put = HashSet::new(); + for key in this_run.iter().chain(before()) { + if lines.len() >= EARLY_MAX { + break; + } + if put.insert(key.as_str()) { + lines.push(format!("{key} {}", ms_of(key))); + } + } + lines.join("\n") +} + +/// What a host pipeline cost, by how it came about. +#[derive(Clone, Copy)] +enum Kind { + /// Loaded from the pipeline library. + Loaded, + /// Compiled by the host driver (its own cache on disk may make that quick). + Made, + /// Compiled by the driver and kept out of the library: static samplers + /// not yet made first ([`super::samplers`]). + StaticSamplers, +} + +const KINDS: [&str; 3] = [ + "loaded from the library", + "made", + "made, static samplers new to the table (in the library from the next run)", +]; + +static TIMES: Mutex<[Vec<u32>; 3]> = Mutex::new([Vec::new(), Vec::new(), Vec::new()]); + +fn record(kind: Kind, began: std::time::Instant) { + let ms = began.elapsed().as_millis().min(u128::from(u32::MAX)) as u32; + TIMES.lock().unwrap_or_else(|e| e.into_inner())[kind as usize].push(ms); +} + +/// Count, p50, p90, p99, max and total of `ms`. +fn percentiles(ms: &[u32]) -> (usize, u32, u32, u32, u32, u64) { + let mut sorted = ms.to_vec(); + sorted.sort_unstable(); + let at = |p: usize| sorted.get(sorted.len().saturating_sub(1) * p / 100).copied().unwrap_or(0); + (sorted.len(), at(50), at(90), at(99), sorted.last().copied().unwrap_or(0), sorted.iter().map(|&m| u64::from(m)).sum()) +} + +/// One line per kind of host pipeline made in this run, release builds too: +/// how many, and how long each took (p50, p90, p99, max, total thread +/// time). The static-sampler line tells whether the driver's own cache +/// makes those compiles quick. Without `force`, at most once a minute and +/// only if more were made since. +pub(crate) fn log_summary(force: bool) { + static LAST: Mutex<Option<(std::time::Instant, usize)>> = Mutex::new(None); + let times = TIMES.lock().unwrap_or_else(|e| e.into_inner()); + let total: usize = times.iter().map(Vec::len).sum(); + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if total == 0 || last.is_some_and(|(at, seen)| total == seen || (!force && at.elapsed().as_secs() < 60)) { + return; + } + *last = Some((std::time::Instant::now(), total)); + } + for (what, ms) in KINDS.iter().zip(times.iter()) { + if ms.is_empty() { + continue; + } + let (count, p50, p90, p99, max, sum) = percentiles(ms); + tracing::info!(count, p50_ms = p50, p90_ms = p90, p99_ms = p99, max_ms = max, total_s = sum / 1000, "host pipelines {what}"); + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn order_file_gives_ranks_and_survives_odd_lines() { + let map = parse_order("aa 10\n\nbb\nbad line extra\naa 99\ncc 7"); + assert_eq!(map["aa"], (0, 10)); + assert_eq!(map["bb"], (1, 0)); + assert_eq!(map["bad"].0, 2); + assert_eq!(map["cc"], (3, 7)); + assert!(parse_order("").is_empty()); + assert_eq!(rank("never seen"), u64::MAX); + } + + #[test] + fn percentiles_of_make_times() { + assert_eq!(percentiles(&[]), (0, 0, 0, 0, 0, 0)); + let ms: Vec<u32> = (1..=100).collect(); + assert_eq!(percentiles(&ms), (100, 50, 90, 99, 100, 5050)); + } + #[test] fn names_change_with_what_goes_into_the_pipeline() { let a = name("graphics", b"root", &[b"vs", b"ps"], "state"); @@ -845,13 +1097,15 @@ mod tests { assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state")); } - /// A pipeline with static samplers is made, not looked up in the library - /// (with or without a host); the guard gives the setting back. + /// A pipeline with static samplers not made first is made, not looked up + /// in the library (with or without a host); the guard gives the setting + /// back. #[test] - fn pipelines_with_static_samplers_skip_the_library() { + fn pipelines_with_unplaced_static_samplers_skip_the_library() { + use super::super::samplers::Use; let looked = std::cell::Cell::new(false); { - let _guard = with_static_samplers(true); + let _guard = with_static_samplers(Use::Unplaced); let made = pipeline( "with static samplers", |_, _| { @@ -863,12 +1117,12 @@ mod tests { assert!(made.is_err()); assert!(!looked.get(), "the library was asked"); { - let _inner = with_static_samplers(false); - assert!(!STATIC_SAMPLERS.get()); + let _inner = with_static_samplers(Use::Placed(7)); + assert_eq!(STATIC_SAMPLERS.get(), Use::Placed(7)); } - assert!(STATIC_SAMPLERS.get()); + assert_eq!(STATIC_SAMPLERS.get(), Use::Unplaced); } - assert!(!STATIC_SAMPLERS.get()); + assert_eq!(STATIC_SAMPLERS.get(), Use::Plain); } #[test] diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 9b7b09584..a884ac171 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -21,8 +21,8 @@ //! its end (run textures-d2, the first after a new translation; Belobug //! 18e57db8 found the same). -use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; +use std::collections::{BinaryHeap, HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -48,6 +48,8 @@ pub(crate) struct Pending { scene_input: bool, /// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH). left_out: Option<&'static str>, + /// Made ahead of the title's own creation of it ([`prewarm_add`]). + prewarmed: AtomicBool, } fn named(shaders: &[Arc<Shader>], name: &[u8]) -> bool { @@ -172,6 +174,7 @@ impl Pending { made: OnceLock::new(), key: key.finalize().to_hex()[..32].to_owned(), used: AtomicBool::new(false), + prewarmed: AtomicBool::new(false), } } @@ -184,6 +187,9 @@ impl Pending { let began = Instant::now(); let made = HostPipeline::new(&self.shaders, self.graphics.as_deref()); super::library::note_time(&self.key, began.elapsed().as_millis() as u64); + if self.prewarmed.load(Ordering::Relaxed) { + PRE_MADE.fetch_add(1, Ordering::Relaxed); + } made }); let (lock, done) = &DONE; @@ -278,6 +284,7 @@ pub(crate) fn waiting() -> u64 { /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { + note_draw(); if p.left_out.is_some() { LEFT_OUT.fetch_add(1, Ordering::Relaxed); return None; @@ -288,6 +295,9 @@ pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { super::library::note_used(&p.key); } if p.made.get().is_none() { + if p.prewarmed.load(Ordering::Relaxed) { + LATE.fetch_add(1, Ordering::Relaxed); + } start(p, REQUESTED); wait(p, crate::frame::current()); } @@ -418,26 +428,66 @@ fn slow_limit() -> usize { }) } +/// An early pipeline in the queue: the one an earlier run first used soonest +/// goes first (`rank`, see `library::rank`); those with no recorded place +/// (`u64::MAX`) and equal places keep the order they were queued in (`n`). +struct Ranked { + rank: u64, + n: u64, + p: Arc<Pending>, +} + +impl PartialEq for Ranked { + fn eq(&self, other: &Self) -> bool { + (self.rank, self.n) == (other.rank, other.n) + } +} + +impl Eq for Ranked {} + +impl PartialOrd for Ranked { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for Ranked { + /// Reversed: a `BinaryHeap` gives the greatest first. + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + (other.rank, other.n).cmp(&(self.rank, self.n)) + } +} + struct Queue { /// Requested passes over the screen: before all others, and the only ones /// [`SCREEN_WORKERS`] take. screen: VecDeque<Arc<Pending>>, - early: VecDeque<Arc<Pending>>, + /// In the order earlier runs first used them (`VICTORY_PIPELINE_ORDER=0`: + /// the title's creation order, as before). + early: BinaryHeap<Ranked>, /// Those of the early ones known to take long, and how many of them are /// being made ([`slow_limit`]). - slow: VecDeque<Arc<Pending>>, + slow: BinaryHeap<Ranked>, slow_now: usize, requested: VecDeque<Arc<Pending>>, + queued: u64, +} + +/// Whether early pipelines are made in the order earlier runs first used them. +fn by_first_use() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_ORDER").is_none_or(|v| v != "0")) } impl Queue { const fn new() -> Self { Self { screen: VecDeque::new(), - early: VecDeque::new(), - slow: VecDeque::new(), + early: BinaryHeap::new(), + slow: BinaryHeap::new(), slow_now: 0, requested: VecDeque::new(), + queued: 0, } } @@ -457,28 +507,51 @@ impl Queue { self.screen.push_back(p.clone()); } else if priority == REQUESTED { self.requested.push_back(p.clone()); - } else if slow { - self.slow.push_back(p.clone()); } else { - self.early.push_back(p.clone()); + self.queued += 1; + let rank = if by_first_use() { super::library::rank(&p.key) } else { u64::MAX }; + let entry = Ranked { rank, n: self.queued, p: p.clone() }; + if slow { + self.slow.push(entry); + } else { + self.early.push(entry); + } } Some(prev == NOT_QUEUED) } + /// Whether the next known-slow pipeline is one an earlier run used before + /// the next other early one. + fn slow_is_sooner(&self) -> bool { + matches!((self.early.peek(), self.slow.peek()), (Some(early), Some(slow)) if slow > early) + } + + /// The next known-slow pipeline, if fewer than `limit` are being made. + fn take_slow(&mut self, limit: usize) -> Option<Arc<Pending>> { + if self.slow_now >= limit { + return None; + } + let p = unclaimed(&mut self.slow)?; + p.was_slow.store(true, Ordering::Relaxed); + self.slow_now += 1; + Some(p) + } + fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option<Arc<Pending>> { - // An early entry can have been promoted and claimed already. - let unclaimed = |list: &mut VecDeque<Arc<Pending>>| { - std::iter::from_fn(|| list.pop_front()).find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) - }; let mut p = self.screen.pop_front(); if p.is_none() && !screens_only { - p = self.requested.pop_front().or_else(|| unclaimed(&mut self.early)); - if p.is_none() && self.slow_now < slow_limit { - p = unclaimed(&mut self.slow); - if let Some(p) = &p { - p.was_slow.store(true, Ordering::Relaxed); - self.slow_now += 1; - } + p = self.requested.pop_front(); + // While the title loads, all go in the order earlier runs used + // them in, the slow ones among them (as many at once as the limit + // allows); otherwise the slow ones wait behind the others. + if p.is_none() && LOADING.load(Ordering::Relaxed) && by_first_use() && self.slow_is_sooner() { + p = self.take_slow(slow_limit); + } + if p.is_none() { + p = unclaimed(&mut self.early); + } + if p.is_none() { + p = self.take_slow(slow_limit); } } let p = p?; @@ -487,6 +560,11 @@ impl Queue { } } +/// The next entry of `list` that was not promoted and claimed already. +fn unclaimed(list: &mut BinaryHeap<Ranked>) -> Option<Arc<Pending>> { + std::iter::from_fn(|| list.pop().map(|r| r.p)).find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) +} + static QUEUE: Mutex<Queue> = Mutex::new(Queue::new()); static AVAILABLE: Condvar = Condvar::new(); @@ -505,7 +583,11 @@ fn start(p: &Arc<Pending>, priority: u8) { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); if let Some(new) = queue.push(p, priority) { if new { - PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + let waiting = WAITING.fetch_add(1, Ordering::Relaxed) + 1; + PEAK.fetch_max(waiting, Ordering::Relaxed); + if waiting >= BOOST_PENDING && boost_level().is_some() { + BOOST.store(true, Ordering::Relaxed); + } } // (One woken could be a worker that takes passes over the screen // alone: it would leave the pipeline to nobody.) @@ -516,10 +598,45 @@ fn start(p: &Arc<Pending>, priority: u8) { /// Workers that make passes over the screen alone, besides the others. const SCREEN_WORKERS: usize = 2; +/// Pipelines waiting at once from which the workers are in a hurry (a world +/// entry or a cold cache queues hundreds; a draw or two does not). +const BOOST_PENDING: u64 = 32; + +/// Whether the workers are in a hurry: set when [`BOOST_PENDING`] pipelines +/// wait, cleared when they are all made ([`drained`]). Then the workers run +/// above their usual priority and may all take the pipelines known to take long. +static BOOST: AtomicBool = AtomicBool::new(false); + +/// How many workers there are (0 until started). +static WORKERS: AtomicUsize = AtomicUsize::new(0); + +/// The priority of workers in a hurry: `VICTORY_PIPELINE_BOOST` unset or +/// `below`: below normal, `normal`: normal, `0`: none (as before). +fn boost_level() -> Option<i32> { + use windows::Win32::System::Threading::{THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL}; + static LEVEL: OnceLock<Option<i32>> = OnceLock::new(); + *LEVEL.get_or_init(|| match std::env::var("VICTORY_PIPELINE_BOOST").ok().as_deref().map(str::trim) { + Some("0") => None, + Some("normal") => Some(THREAD_PRIORITY_NORMAL.0), + _ => Some(THREAD_PRIORITY_BELOW_NORMAL.0), + }) +} + +/// The most workers that take known-slow pipelines now: the usual limit, or +/// while [`BOOST`] all but one (that one is left for what draws ask for). +fn slow_limit_now() -> usize { + let usual = slow_limit(); + let hurry = LOADING.load(Ordering::Relaxed) || (BOOST.load(Ordering::Relaxed) && boost_level().is_some()); + if usual == usize::MAX || !hurry { + return usual; + } + usual.max(WORKERS.load(Ordering::Relaxed).saturating_sub(1)) +} + fn next(screens_only: bool) -> Arc<Pending> { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); loop { - if let Some(p) = queue.pop(screens_only, slow_limit()) { + if let Some(p) = queue.pop(screens_only, slow_limit_now()) { return p; } queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); @@ -553,6 +670,7 @@ fn workers() -> bool { std::thread::available_parallelism().map_or(2, |n| n.get()), crate::residency::limited_host_ram(), ); + WORKERS.store(workers, Ordering::Relaxed); tracing::info!(workers, "pipeline workers"); let screens = if screens_first() { SCREEN_WORKERS } else { 0 }; for i in 0..workers + screens { @@ -564,14 +682,31 @@ fn workers() -> bool { // and the streaming one, which is below normal itself // (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before). let lowest = !screens_only && std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0"); - // SAFETY: a plain call on our own thread. - unsafe { - use windows::Win32::System::Threading::*; - let priority = if lowest { THREAD_PRIORITY_LOWEST } else { THREAD_PRIORITY_BELOW_NORMAL }; - let _ = SetThreadPriority(GetCurrentThread(), priority); - } + use windows::Win32::System::Threading::*; + let usual = if lowest { THREAD_PRIORITY_LOWEST } else { THREAD_PRIORITY_BELOW_NORMAL }; + let set = |priority: THREAD_PRIORITY| { + // SAFETY: a plain call on our own thread. + let _ = unsafe { SetThreadPriority(GetCurrentThread(), priority) }; + }; + set(usual); + let mut now = usual.0; loop { let p = next(screens_only); + // In a hurry (a world's worth of pipelines waiting, the + // title's thread waiting for them): above the usual + // lowest, until they are all made. + // While the title loads and pipelines of earlier runs are + // being made ahead ([`LOADING`]): all workers but the + // first at normal priority. + let wanted = match boost_level() { + _ if lowest && i != 0 && LOADING.load(Ordering::Relaxed) => THREAD_PRIORITY_NORMAL.0, + Some(level) if lowest && BOOST.load(Ordering::Relaxed) => level.max(usual.0), + _ => usual.0, + }; + if wanted != now { + set(THREAD_PRIORITY(wanted)); + now = wanted; + } p.make(); if p.was_slow.load(Ordering::Relaxed) { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); @@ -581,7 +716,7 @@ fn workers() -> bool { if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { - super::library::save(false); + super::library::save_while_busy(); } } }); @@ -602,6 +737,8 @@ static PEAK: AtomicU64 = AtomicU64::new(0); /// the cache saved (at most every 20 s). fn drained() { use super::library::{EARLY, LOADED, MADE}; + BOOST.store(false, Ordering::Relaxed); + loading_over("everything queued is made"); if PEAK.swap(0, Ordering::Relaxed) >= 10 { tracing::info!( made = MADE.load(Ordering::Relaxed), @@ -609,10 +746,147 @@ fn drained() { started_early = EARLY.load(Ordering::Relaxed), "host pipelines all made" ); + super::library::log_summary(true); } super::library::save(false); } +/// Whether the title is loading and pipelines of earlier runs are being made +/// ahead of its asking for them ([`prewarm_begin`]): the workers but the first +/// run at normal priority, all but one of them may be in known-slow pipelines, +/// and the queue goes in the order earlier runs first used pipelines in, slow +/// ones included. Cleared by [`loading_over`]. +static LOADING: AtomicBool = AtomicBool::new(false); +static LOADING_SINCE: Mutex<Option<Instant>> = Mutex::new(None); + +/// Pipelines planned from earlier runs, queued by the prewarm, made so far, +/// found by the title's creation of the same pipeline, and asked for by a draw +/// before they were made. +pub(super) static PLANNED: AtomicU64 = AtomicU64::new(0); +pub(super) static QUEUED: AtomicU64 = AtomicU64::new(0); +static PRE_MADE: AtomicU64 = AtomicU64::new(0); +static ADOPTED: AtomicU64 = AtomicU64::new(0); +static LATE: AtomicU64 = AtomicU64::new(0); + +/// By key: the planned pipelines, `None` until one exists (made by the prewarm +/// or created by the title, whichever came first). The title's creation of a +/// pipeline gets the one that is here ([`adopt`]), made or in the queue. +static PREWARMED: Mutex<Option<HashMap<String, Option<Arc<Pending>>>>> = Mutex::new(None); + +/// A frame in which this many draws and dispatches are asked for is a world's +/// (the menu and loading screen draw 1 to 11); two in a row end the loading. +const WORLD_DRAWS: u64 = 300; +static DRAW_FRAME: AtomicU64 = AtomicU64::new(0); +static DRAW_COUNT: AtomicU64 = AtomicU64::new(0); +static WORLD_FRAMES: AtomicU64 = AtomicU64::new(0); + +/// The prewarm starts: counts as a pipeline waiting until [`prewarm_end`], so +/// that the workers do not run out of work between the loader's entries. +pub(super) fn prewarm_begin() { + *LOADING_SINCE.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now()); + WAITING.fetch_add(1, Ordering::Relaxed); + LOADING.store(true, Ordering::Relaxed); +} + +/// The loader has queued all it will. +pub(super) fn prewarm_end() { + if QUEUED.load(Ordering::Relaxed) == 0 { + loading_over("nothing to make ahead"); + } + if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { + drained(); + } +} + +/// The keys the prewarm will queue. +pub(super) fn prewarm_plan(keys: &[String]) { + let mut map = PREWARMED.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_default(); + for key in keys { + map.entry(key.clone()).or_insert(None); + } + PLANNED.store(keys.len() as u64, Ordering::Relaxed); +} + +/// Queues a pipeline of an earlier run, before the title creates it; `false` +/// if the title created it first (its own is the one that is made). +pub(super) fn prewarm_add(p: Pending) -> bool { + p.prewarmed.store(true, Ordering::Relaxed); + let p = Arc::new(p); + { + let mut map = PREWARMED.lock().unwrap_or_else(|e| e.into_inner()); + let slot = map.get_or_insert_default().entry(p.key.clone()).or_insert(None); + if slot.is_some() { + return false; + } + *slot = Some(p.clone()); + } + if p.left_out.is_none() && !p.shaders.is_empty() { + QUEUED.fetch_add(1, Ordering::Relaxed); + start(&p, EARLY); + } + true +} + +/// The pipeline the title's creation of `p` gets: the one the prewarm made or +/// queued for the same key, else `p` itself. +pub(crate) fn adopt(p: Pending) -> Arc<Pending> { + let mut map = PREWARMED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(slot) = map.as_mut().and_then(|m| m.get_mut(&p.key)) { + if let Some(there) = slot.as_ref() { + ADOPTED.fetch_add(1, Ordering::Relaxed); + return there.clone(); + } + let p = Arc::new(p); + *slot = Some(p.clone()); + return p; + } + Arc::new(p) +} + +/// Counts a draw or dispatch of the title while it loads: a frame of a +/// world's worth of them ends the loading. +fn note_draw() { + if !LOADING.load(Ordering::Relaxed) { + return; + } + let frame = crate::frame::current(); + let last = DRAW_FRAME.load(Ordering::Relaxed); + if frame != last && DRAW_FRAME.compare_exchange(last, frame, Ordering::Relaxed, Ordering::Relaxed).is_ok() { + if DRAW_COUNT.swap(0, Ordering::Relaxed) >= WORLD_DRAWS { + if WORLD_FRAMES.fetch_add(1, Ordering::Relaxed) >= 1 { + loading_over("the title draws a world"); + } + } else { + WORLD_FRAMES.store(0, Ordering::Relaxed); + } + } + DRAW_COUNT.fetch_add(1, Ordering::Relaxed); +} + +/// The title has loaded (or everything planned is made): the workers go back +/// to their usual priority and limits. +fn loading_over(why: &str) { + if !LOADING.swap(false, Ordering::Relaxed) { + return; + } + let seconds = LOADING_SINCE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .map_or(0.0, |t| t.elapsed().as_secs_f64()); + tracing::info!( + why, + seconds = (seconds * 10.0).round() / 10.0, + planned = PLANNED.load(Ordering::Relaxed), + queued = QUEUED.load(Ordering::Relaxed), + made = PRE_MADE.load(Ordering::Relaxed), + found_by_the_title = ADOPTED.load(Ordering::Relaxed), + asked_before_made = LATE.load(Ordering::Relaxed), + waiting = waiting(), + "pipeline prewarm: loading over, workers back to their usual priority" + ); +} + #[cfg(test)] mod tests { use super::*; @@ -680,6 +954,31 @@ mod tests { assert!(super::super::library::wanted_early(&p.key)); } + /// The title's creation of a pipeline gets the one made ahead for its key, + /// or its own if it came first (and then the prewarm leaves it alone). + #[test] + fn the_title_gets_the_pipeline_made_ahead() { + let named = |key: &str| { + let mut p = Pending::new(Vec::new(), None); + p.key = key.to_owned(); + p + }; + prewarm_plan(&["ahead-test".to_owned(), "title-first-test".to_owned()]); + assert!(prewarm_add(named("ahead-test"))); + let got = adopt(named("ahead-test")); + assert!(got.prewarmed.load(Ordering::Relaxed)); + assert!(Arc::ptr_eq(&got, &adopt(named("ahead-test")))); + + let own = adopt(named("title-first-test")); + assert!(!own.prewarmed.load(Ordering::Relaxed)); + assert!(!prewarm_add(named("title-first-test"))); + assert!(Arc::ptr_eq(&own, &adopt(named("title-first-test")))); + + // Not planned: not kept. + let (a, b) = (adopt(named("unplanned-test")), adopt(named("unplanned-test"))); + assert!(!Arc::ptr_eq(&a, &b)); + } + #[test] fn draws_promote_early_pipelines_without_claiming_them_twice() { let earlier = Arc::new(Pending::new(Vec::new(), None)); @@ -723,6 +1022,22 @@ mod tests { assert!(queue.pop(false, 1).is_none()); } + /// Early pipelines come out by the place earlier runs first used them in, + /// those with none after them, and equal places in the order queued. + #[test] + fn early_pipelines_go_in_first_use_order() { + let new = || Arc::new(Pending::new(Vec::new(), None)); + let mut heap = BinaryHeap::new(); + let ps = [new(), new(), new(), new()]; + for (n, (rank, p)) in [(u64::MAX, &ps[0]), (5, &ps[1]), (1, &ps[2]), (u64::MAX, &ps[3])].into_iter().enumerate() { + heap.push(Ranked { rank, n: n as u64, p: p.clone() }); + } + let order: Vec<_> = std::iter::from_fn(|| heap.pop()).map(|r| r.p).collect(); + for (got, want) in order.iter().zip([&ps[2], &ps[1], &ps[0], &ps[3]]) { + assert!(Arc::ptr_eq(got, want)); + } + } + /// Passes over the screen go before all others, and workers of their own /// take nothing else. #[test] diff --git a/crates/victory-gpu/src/pipeline/samplers.rs b/crates/victory-gpu/src/pipeline/samplers.rs new file mode 100644 index 000000000..abbb39d96 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/samplers.rs @@ -0,0 +1,377 @@ +//! The driver's table of static samplers, made in the same order every run, +//! so pipelines with static samplers can be kept in the pipeline library. +//! +//! The card's driver (NVIDIA) keeps the static samplers of every root +//! signature in one table of its own, one entry per distinct sampler state, +//! in the order those states are first made in the process, and a compiled +//! pipeline holds its samplers' places in that table. A pipeline loaded from +//! the library in another run therefore reads through whatever sits at the +//! places of the run that stored it (see `library::with_static_samplers`). +//! Measured with `examples/lut3d_probe.rs` (4070, driver 621.01, +//! 2026-11-27): +//! - stored after the composite's three samplers were made first, one root +//! signature each, and loaded in a run that made them first in the same +//! order and then ten others (`PRELOAD=1`, then `PRELOAD=1 SHIFT=10`): +//! filtered, as made; +//! - loaded in a run that made them first in another order (`PRELOAD=lin`) +//! or not first at all: unfiltered (another sampler); +//! - made first at another register and space, visible to the pixel stage +//! only (`PRELOAD_ODD=1`): filtered. The table tells samplers apart by +//! their state alone. +//! +//! So: every sampler state the title's pipelines ever had is kept in a file +//! beside the library ([`FILE`]), in the order first seen, and made right +//! after the device, before anything else makes a static sampler +//! ([`replay`]): those take the same places in every run. A pipeline whose +//! samplers are all among them is loaded from and stored in the library +//! under a name that also holds their places and states ([`admit`]); one +//! with a state new to the file is made, kept out of the library, and its +//! new states are added to the file: the next run makes them first too. +//! +//! `VICTORY_LIBRARY_STATIC_SAMPLERS=0`: pipelines with static samplers never +//! use the library (the way before); `=1`: they always do, without the +//! table (the way before that, wrong where the places moved). + +use std::collections::{HashMap, HashSet}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; + +/// The sampler states, in the order they are made, beside the library. +pub(super) const FILE: &str = "static-samplers.bin"; +const MAGIC: &[u8; 8] = b"VICSS001"; +/// At most this many states are made first (the card's table holds 2,032; +/// the rest is left to the title's own and to ours). +const MAX: usize = 1024; + +/// One static sampler's state: everything but its register, space and +/// visibility (the table does not tell those apart). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(crate) struct State([u32; 10]); + +impl State { + pub(crate) fn of(s: &D3D12_STATIC_SAMPLER_DESC) -> Self { + State([ + s.Filter.0 as u32, + s.AddressU.0 as u32, + s.AddressV.0 as u32, + s.AddressW.0 as u32, + s.MipLODBias.to_bits(), + s.MaxAnisotropy, + s.ComparisonFunc.0 as u32, + s.BorderColor.0 as u32, + s.MinLOD.to_bits(), + s.MaxLOD.to_bits(), + ]) + } + + fn desc(self) -> D3D12_STATIC_SAMPLER_DESC { + let s = self.0; + D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(s[0] as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(s[1] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(s[2] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(s[3] as i32), + MipLODBias: f32::from_bits(s[4]), + MaxAnisotropy: s[5], + ComparisonFunc: D3D12_COMPARISON_FUNC(s[6] as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(s[7] as i32), + MinLOD: f32::from_bits(s[8]), + MaxLOD: f32::from_bits(s[9]), + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + } + } + + fn bytes(self) -> [u8; 40] { + let mut out = [0u8; 40]; + for (i, w) in self.0.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes()); + } + out + } + + fn from_bytes(b: &[u8]) -> Self { + let mut w = [0u32; 10]; + for (i, v) in w.iter_mut().enumerate() { + *v = u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap_or_default()); + } + State(w) + } +} + +/// A record in the file: the state and a check of it (a torn or damaged +/// record ends the list there). +const RECORD: usize = 48; + +fn record(state: State) -> [u8; RECORD] { + let mut out = [0u8; RECORD]; + let bytes = state.bytes(); + out[..40].copy_from_slice(&bytes); + let check = blake3::hash(&bytes); + out[40..].copy_from_slice(&check.as_bytes()[..8]); + out +} + +/// The states a file holds, in order, up to the first bad record. +pub(crate) fn parse(file: &[u8]) -> Vec<State> { + let Some(body) = file.strip_prefix(MAGIC.as_slice()) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for r in body.chunks_exact(RECORD) { + let state = State::from_bytes(&r[..40]); + if blake3::hash(&r[..40]).as_bytes()[..8] != r[40..] { + break; + } + out.push(state); + } + out +} + +/// How a pipeline with static samplers may use the library. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Use { + /// No static samplers: as any pipeline. + Plain, + /// All its samplers were made first, at these places: from and into the + /// library, its name salted with this tag. + Placed(u64), + /// A sampler not made first: made, not from or into the library. + Unplaced, +} + +struct Table { + /// Places of the states made first ([`replay`]). + placed: HashMap<State, u32>, + /// States seen this run that are not placed, already in the file. + noted: HashSet<State>, + /// The number of states in the file. + in_file: usize, + path: Option<PathBuf>, + /// The root signatures that made them, kept for the device's life. + _made: Vec<ID3D12RootSignature>, +} + +// SAFETY: D3D12 objects are free-threaded; the rest are plain data. +unsafe impl Send for Table {} + +static TABLE: OnceLock<Mutex<Table>> = OnceLock::new(); + +/// Whether the table decides (default), or `VICTORY_LIBRARY_STATIC_SAMPLERS` +/// says never (0) or always (1). +fn mode() -> Option<bool> { + static MODE: OnceLock<Option<bool>> = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_LIBRARY_STATIC_SAMPLERS").as_deref() { + Ok("0") => Some(false), + Ok("1") => Some(true), + _ => None, + }) +} + +/// Makes the states of [`FILE`] in `dir`, in their order, one root signature +/// each, on `device`: called right after the device is made, before anything +/// else makes a static sampler. Once; later calls do nothing. +pub(crate) fn replay(device: &ID3D12Device) { + TABLE.get_or_init(|| { + let path = super::library::folder().map(|d| d.join(FILE)); + let states = if mode().is_none() { + path.as_deref().map(read).unwrap_or_default() + } else { + Vec::new() + }; + let began = std::time::Instant::now(); + let mut made = Vec::with_capacity(states.len().min(MAX)); + let mut placed = HashMap::new(); + for state in states.iter().copied().take(MAX) { + if placed.contains_key(&state) { + continue; + } + match make(device, state) { + Ok(root) => { + placed.insert(state, placed.len() as u32); + made.push(root); + } + Err(e) => { + // Places after a refused one would not be the stored + // runs' places: none are used past it. + tracing::warn!(error = %e, at = placed.len(), "a static sampler state refused; the later ones are not placed"); + break; + } + } + } + if !states.is_empty() { + tracing::info!( + states = placed.len(), + ms = began.elapsed().as_millis() as u64, + "static sampler states made first, in the order of earlier runs (pipelines with them come from the library)" + ); + } + Mutex::new(Table { + placed, + noted: HashSet::new(), + in_file: states.len(), + path, + _made: made, + }) + }); +} + +/// The states in `path`; a torn end (a run that stopped while adding) is +/// cut off, so what is added next reads back. +fn read(path: &Path) -> Vec<State> { + let Ok(bytes) = std::fs::read(path) else { return Vec::new() }; + let states = parse(&bytes); + let whole = MAGIC.len() + states.len() * RECORD; + if !states.is_empty() && bytes.len() != whole { + let cut = std::fs::OpenOptions::new().write(true).open(path).and_then(|f| f.set_len(whole as u64)); + if let Err(e) = cut { + tracing::warn!(error = %e, "static sampler states: the torn end not cut off"); + } + } + states +} + +fn make(device: &ID3D12Device, state: State) -> windows::core::Result<ID3D12RootSignature> { + let sampler = state.desc(); + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumStaticSamplers: 1, + pStaticSamplers: &sampler, + ..Default::default() + }, + }, + }; + // SAFETY: the description points at a live sampler; the blob is read + // while it lives. + unsafe { + let mut blob: Option<ID3DBlob> = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +/// How a pipeline whose root signature has `samplers` may use the library; +/// states not in the file yet are added to it (made first from the next run +/// on). +pub(crate) fn admit(samplers: &[D3D12_STATIC_SAMPLER_DESC]) -> Use { + if samplers.is_empty() { + return Use::Plain; + } + match mode() { + Some(true) => return Use::Placed(0), + Some(false) => return Use::Unplaced, + None => {} + } + let Some(table) = TABLE.get() else { return Use::Unplaced }; + let mut table = table.lock().unwrap_or_else(|e| e.into_inner()); + let mut tag = blake3::Hasher::new(); + let mut new = Vec::new(); + let mut unplaced = false; + for s in samplers { + let state = State::of(s); + match table.placed.get(&state) { + Some(&at) => { + tag.update(&at.to_le_bytes()); + tag.update(&state.bytes()); + } + None => { + unplaced = true; + if table.noted.insert(state) { + new.push(state); + } + } + } + } + if !new.is_empty() { + table.add(&new); + } + if unplaced { + return Use::Unplaced; + } + let hash = tag.finalize(); + Use::Placed(u64::from_le_bytes(hash.as_bytes()[..8].try_into().unwrap_or_default())) +} + +impl Table { + /// Appends `states` to the file (a new file starts with its mark). + fn add(&mut self, states: &[State]) { + let Some(path) = &self.path else { return }; + if self.in_file >= MAX { + return; + } + let room = MAX - self.in_file; + let mut bytes = Vec::with_capacity(8 + states.len() * RECORD); + let fresh = !path.exists() || self.in_file == 0; + if fresh { + bytes.extend_from_slice(MAGIC); + } + for &s in states.iter().take(room) { + bytes.extend_from_slice(&record(s)); + } + let written = (|| -> std::io::Result<()> { + if fresh { + // A file whose records did not read (damaged) starts again. + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, &bytes)?; + std::fs::rename(&tmp, path) + } else { + let mut f = std::fs::OpenOptions::new().append(true).open(path)?; + f.write_all(&bytes) + } + })(); + match written { + Ok(()) => self.in_file += states.len().min(room), + Err(e) => tracing::warn!(error = %e, "static sampler states not kept"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn state(bias: f32) -> State { + State::of(&D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + MipLODBias: bias, + MaxLOD: 12.0, + ShaderRegister: 3, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + ..Default::default() + }) + } + + #[test] + fn a_state_leaves_out_register_and_visibility() { + let mut d = state(0.5).desc(); + d.ShaderRegister = 9; + d.RegisterSpace = 2; + assert_eq!(State::of(&d), state(0.5)); + assert_ne!(state(0.5), state(0.25)); + } + + #[test] + fn the_file_reads_back_in_order_and_stops_at_a_torn_record() { + let mut file = MAGIC.to_vec(); + for b in [0.0, 1.0, 2.0] { + file.extend_from_slice(&record(state(b))); + } + assert_eq!(parse(&file), vec![state(0.0), state(1.0), state(2.0)]); + // A torn last record, and a damaged middle one. + let torn = &file[..file.len() - 5]; + assert_eq!(parse(torn), vec![state(0.0), state(1.0)]); + let mut bad = file.clone(); + bad[8 + RECORD + 3] ^= 1; + assert_eq!(parse(&bad), vec![state(0.0)]); + assert!(parse(b"other").is_empty()); + } +} diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index aadc34dd5..9898240fe 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -25,6 +25,8 @@ use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{GUID, HRESULT, IUnknown, Interface}; +use crate::host::memory_samples::{Allocation, Kind}; + /// Bytes of a block; pieces of more than half of one are not pooled (with /// blocks made ahead, [`ahead`]: of more than one). const BLOCK: u64 = 64 << 20; @@ -299,7 +301,8 @@ impl<B: Clone> Pool<B> { } fn give(&mut self, piece: Piece, now: u64) { - self.resting.push_back((now + REST, piece)); + let rest = if self.spare <= SPARE { 250 } else { REST }; + self.resting.push_back((now + rest, piece)); } /// Makes the pieces that rested long enough free, and lets go of empty @@ -680,7 +683,7 @@ pub(crate) unsafe fn texture( tracing::warn!(error = %e, "no block of texture memory"); } if let Some(h) = &heap - && let Err(e) = crate::host::resident(device, h).and_then(|()| crate::host::mapped(device)) + && let Err(e) = crate::host::resident_and_mapped(device, h, Allocation(Kind::TextureHeap, BLOCK)) { tracing::warn!(error = %e, "a block of texture memory is not resident"); return None; diff --git a/crates/victory-gpu/src/port.rs b/crates/victory-gpu/src/port.rs index 22edcf3d9..514f53196 100644 --- a/crates/victory-gpu/src/port.rs +++ b/crates/victory-gpu/src/port.rs @@ -1,5 +1,7 @@ -//! Renderer port #1: the title's 32-bit graphics heap as the card's own -//! memory (`VICTORY_PORT_CONSTANTS`, off by default). +//! Renderer port #1, as the title-memory home of the unified memory model +//! (docs/performance/UNIFIED_MEMORY_ARCHITECTURE.md): the title's 32-bit +//! graphics heap opened in place, and constant buffers in it that no shader +//! writes read by the card where the title wrote them. Always on. //! //! What the title does (game_scarlett_master.exe, the routine at image //! +0x1e86440, reached at its start): one `XMemVirtualAlloc` of the five @@ -10,53 +12,73 @@ //! protection (`XMemVirtualAlloc`, kind 0x20406000, flags 0x27); then ONE //! `XMemAllocatePhysicalPages` for all their pages and five //! `XMemMapPhysicalPages`, in order, each from the next page of that one -//! array. `xmem` makes one section of all the pages, so the whole -//! reservation is one stretch of one section: views that follow one -//! another in memory and in the section alike. The title's 174 MB buffer at -//! 0x34e10000 (where its ring of constants lies, and what the skinning -//! passes write through one view of all of it) is in it; it is never -//! tile-mapped (`CopyPageMappings` maps the GPU heap's pages, not these). +//! array. `xmem` makes one section of all the pages (and gives them their +//! slices in address order, `xmem::arrange`), so the whole reservation is +//! one stretch of one section: views that follow one another in memory and +//! in the section alike. The title's 174 MB buffer (where its ring of +//! constants lies, and what the skinning passes write through one view of +//! all of it) is in it; it is never tile-mapped (`CopyPageMappings` maps +//! the GPU heap's pages, not these). //! -//! What the layer did with it: a host copy in the card's memory, the title's -//! writes found and sent up (17 MB a frame in ~600 pieces), what shaders -//! wrote fetched back and merged, and every constant buffer read out of it -//! (~6,000 fills a frame) either waited for flights or done on the card -//! from the copy. +//! Two homes. The 174 MB buffer is mostly geometry the card reads by the +//! hundred megabytes a list, and skinning writes it through one view of the +//! whole: it stays the card copy `crate::shadow` makes (in place, all of it +//! in the PC's memory, the card read and wrote it over the bus and was +//! slower overall on a 12 GB card). A view cannot be backed in part here +//! and in part on the card: tile mappings into a heap opened on title +//! memory remove the device (`crate::inplace`). So the split is by access: +//! a constant buffer view (root or in a table) of bytes no shader writes +//! ([`constants`]) is bound to the title's memory itself, through one +//! buffer placed over the whole stretch; every other access binds the card +//! copy, as before. For those constants nothing is refreshed, filled into +//! upload memory, sent up, merged or waited for: the card reads the title's +//! bytes when it runs, as the console's does. //! -//! What is done here instead: the stretch is mapped once more, at an -//! address of ours (a view of the same section: the same physical pages), -//! and opened as a host heap there (`OpenExistingHeapFromAddress1`); title -//! buffers and windows of title memory in it are buffers placed in that -//! heap ([`crate::shadow::Shadow`]'s in-place form): the card reads and -//! writes the title's bytes where the title wrote them. Nothing is tracked, -//! sent up, fetched back or compared for it, and no compare or hash pass -//! of ours ever runs over it (they are for copies in the card's memory: -//! one such pass over memory shared with the PC removed the device on -//! another tree). No tile mapping is ever made into this heap (that removes -//! the device). +//! Alignment (2026-11-27, branch `perf/raw-constants`): a constant buffer +//! VIEW needs its address on 256 bytes on the host; the title places its +//! constants on 16, so 6,185 of 6,556 views a frame could not be bound here +//! (run play-20261127-111731). The translation now reads every constant +//! buffer as raw bytes (`victory_shader::emit::HostShader::root_cbvs`), and +//! one in a view slot as a structured buffer of dwords (the slot holds a +//! structured view, stride 4): both need the address on 4 bytes only +//! ([`ALIGN`]), so every constant buffer of the title can be read here. (A +//! first try read tables' through the slots' raw twins: raw views begin on +//! 16, and NVIDIA's heaps have no room for twins, run +//! play-20261127-114321: 108 read in place, 2,841-4,075 not.) The caller +//! says what binds it ([`Use`]), for the counts. +//! +//! "No shader writes it", per 4 KiB page ([`PAGE_MARKS`]): no read-back +//! into title memory was ever recorded for it ([`gpu_bound`]: for good), no +//! title buffer copy into it was recorded in the last [`COPY_FRAMES`] +//! frames ([`copy_bound`]: such a copy may be done on the card, in front of +//! the lists, `crate::host`'s `card_steps`, or at its place in the list, +//! and lands in title memory after the flight), and no landing put shader +//! output there in the last [`LANDED_FRAMES`] frames +//! (`crate::watch::landed_lately`, the window `fill_is_titles` has used by +//! default: skinning outputs land every frame and stay the card's; a ring +//! page a copy wrote once comes back). //! //! Why our own view: a heap opened from an address holds the pages it was //! opened on: the title could not unmap, decommit or protect them while it //! stands. Opened on our view, the title's own views stay free to change. -//! When the title maps other pages at such an address, what is in place -//! there is let go (`crate::inplace::title_memory_freeing`) and the region -//! forgotten; the view of ours stays (shortcut: it is never unmapped, a -//! few hundred MB of address space at most). +//! When the title maps other pages at such an address, the region is +//! forgotten (`crate::inplace::title_memory_freeing`): new binds take the +//! card copy; lists and slots bound before hold the region's buffer, which +//! still shows our view (shortcut: never unmapped, a few hundred MB of +//! address space at most), so nothing reads freed memory. //! -//! What it assumes: the CPU steps of ours that read this memory at -//! submission (fills of constant buffers, the title's buffer copies done on -//! the CPU) read what the title's CPU wrote, not what a submission still in -//! the air writes there: in place nothing tells the flights' writes, so -//! nothing waits for them. The title's constants are its CPU's; how many -//! such steps there are is on the frame-rate line ([`log`]). +//! What it assumes: the title does not write constants a submission still +//! in the air reads (the console's GPU reads them at execution too), and a +//! shader's first write to a page is not read through a constant buffer +//! before it lands (the same as `crate::host`'s `fill_is_titles`). -use std::sync::Mutex; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::RwLock; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows_sys::Win32::System::Memory as mem; -use crate::inplace::{Placed, cover, stretch}; +use crate::inplace::{cover, stretch}; const K64: u64 = 64 << 10; @@ -68,112 +90,317 @@ const LOW: u64 = 1 << 32; /// while the heap stands. const MOST: u64 = 512 << 20; -/// `VICTORY_PORT_CONSTANTS`: `1` turns renderer port #1 on (title buffers -/// and windows of title memory in the title's 32-bit graphics memory, view -/// memory that is one stretch of a section, used in place); unset or -/// anything else: off, everything as before. -pub(crate) fn on() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - // Read once, here: the switch of renderer port #1. - *ON.get_or_init(|| std::env::var("VICTORY_PORT_CONSTANTS").is_ok_and(|v| v.trim() == "1")) +/// The most bytes a constant buffer view reads (4,096 vectors). +const CONSTANTS_MOST: u64 = 64 << 10; + +/// The alignment a constant buffer needs to be read in place: a root one is +/// a raw root SRV (`victory_shader::emit::HostShader::root_cbvs`), one in a +/// view slot a structured view of dwords +/// (`crate::descriptor::host::HostHeap::constant_at`): both begin on any 4 +/// bytes. +pub(crate) const ALIGN: u64 = 4; + +/// What binds a constant buffer asked about ([`constants`]), for the counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Use { + /// A root view (`crate::draw` `root_view`). + Root, + /// A table's slot made afresh for a draw (`crate::draw` `tables`). + Table, + /// A title slot made by the descriptor mirror + /// (`crate::descriptor::host` `make_twinned`). + Mirror, } -/// A stretch of title memory opened as a heap through a view of ours. +/// Frames before memory that could not be opened is asked about again +/// (pages of a stretch may not be committed yet). +const RETRY_FRAMES: u64 = 600; + +/// 4 KiB pages below [`LOW`]. +const PAGES: usize = (LOW / 4096) as usize; + +/// Frames a page a title buffer copy was recorded into is not read in place +/// ([`copy_bound`]): the copy's flight lands within them (the relay keeps +/// one or two frames in the air; `crate::host`'s `placed_lately` trusts +/// two). +const COPY_FRAMES: u64 = 8; + +/// Frames a page shader output landed in is not read in place. +const LANDED_FRAMES: u64 = 600; + +/// [`PAGE_MARKS`]' mark of a page the card writes for good. +const FOR_GOOD: u32 = u32::MAX; + +/// A stretch of title memory opened as a heap through a view of ours, and +/// one buffer placed over all of it. struct Region { start: u64, end: u64, - heap: ID3D12Heap, + whole: ID3D12Resource, + _heap: ID3D12Heap, } -// SAFETY: D3D12 heaps are free-threaded. +// SAFETY: D3D12 heaps and resources are free-threaded. unsafe impl Send for Region {} +// SAFETY: as above; nothing in it changes once made. +unsafe impl Sync for Region {} -static REGIONS: Mutex<Vec<Region>> = Mutex::new(Vec::new()); +static REGIONS: RwLock<Vec<Region>> = RwLock::new(Vec::new()); /// The lowest start and highest end of every region (both 0: none), for a /// quick look on the paths that run thousands of times a frame. static BOUNDS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; -/// Since the start: regions opened, their bytes; title buffers and windows -/// placed; refused because the memory is not one stretch of a section, -/// not committed, refused by the host; regions forgotten because the title -/// mapped other pages there. Then, since the last line: fills read out of -/// ported memory on the CPU, their bytes, buffer copies on the CPU that -/// touch it, their bytes. -static STATS: [AtomicU64; 13] = [const { AtomicU64::new(0) }; 13]; - -/// Whether `[at, at + len)` may be ported: in the title's 32-bit graphics -/// memory. -pub(crate) fn wanted(at: u64, len: u64) -> bool { - on() && at.checked_add(len).is_some_and(|end| end <= LOW && len > 0) +/// Per 64 MiB of memory below [`LOW`]: the frame (plus one) memory there +/// last could not be opened, 0 never. +static TRIED: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; + +/// The host refused to open a stretch: none is asked for again. +static REFUSED: AtomicBool = AtomicBool::new(false); + +/// Per 4 KiB page below [`LOW`]: 0 nothing; [`FOR_GOOD`] a write on the +/// card is bound for it ([`gpu_bound`]); else the frame (low 32 bits, at +/// least 1) a title buffer copy into it was last recorded ([`copy_bound`]). +/// 4 MB of address space, of which only the pages written are memory. +static PAGE_MARKS: [AtomicU32; PAGES] = [const { AtomicU32::new(0) }; PAGES]; + +// What [`STATS`] holds. Since the start: regions opened, their bytes; asks +// that could not open one because the memory is not one stretch of a +// section, not committed, no view of it could be made, the host refused, no +// buffer could be placed; regions forgotten because the title mapped other +// pages there. Then, since the last line: constant buffer views bound in +// place and their bytes; not, because off 4 bytes (as a root view), because +// a shader writes a page of it, because outside every region; fills of +// upload memory read out of ported memory on the CPU and their bytes; title +// buffer copies on the CPU that touch it and their bytes; small stream views +// in place and their bytes; not in place because off 4 bytes in a table's +// slot, in a title slot (mirror); in place in a table's slot, in a title +// slot (the rest of [`READ`] are root views). +const OPENED: usize = 0; +const OPENED_BYTES: usize = 1; +const NOT_STRETCH: usize = 2; +const NOT_COMMITTED: usize = 3; +const NO_VIEW: usize = 4; +const HOST_REFUSED: usize = 5; +const NO_BUFFER: usize = 6; +const FORGOTTEN: usize = 7; +const READ: usize = 8; +const READ_BYTES: usize = 9; +const MISALIGNED: usize = 10; +const SHADERS: usize = 11; +const OUTSIDE: usize = 12; +const FILLS: usize = 13; +const FILL_BYTES: usize = 14; +const COPIES: usize = 15; +const COPY_BYTES: usize = 16; +const STREAM_READ: usize = 17; +const STREAM_READ_BYTES: usize = 18; +const MISALIGNED_TABLE: usize = 19; +const MISALIGNED_MIRROR: usize = 20; +const READ_TABLE: usize = 21; +const READ_MIRROR: usize = 22; +static STATS: [AtomicU64; 23] = [const { AtomicU64::new(0) }; 23]; + +/// A constant buffer of `len` bytes at title address `address`, read in +/// place: the buffer to bind and hold (the caller's list and slot keep it), +/// and the host address of `address` in it (on [`ALIGN`] bytes, what every +/// view a constant buffer is read through needs). `None`: bind the card copy +/// or fill upload memory, as before. In place only if the view's bytes +/// (`len` rounded up to 256, 64 KiB at most: what a CBV of it shows) lie in +/// a region and no shader writes any of their pages. `by`: what binds it. +pub(crate) fn constants(address: u64, len: u64, by: Use) -> Option<(ID3D12Resource, u64)> { + if len == 0 || address >= LOW { + return None; + } + let misaligned = match by { + Use::Root => MISALIGNED, + Use::Table => MISALIGNED_TABLE, + Use::Mirror => MISALIGNED_MIRROR, + }; + let size = len.min(CONSTANTS_MOST).next_multiple_of(256); + let end = address.checked_add(size)?; + if end > LOW { + return None; + } + // Regions begin on 64 KiB and their buffer with them: the host address + // is aligned as the title's is. + if address % ALIGN != 0 { + if touches(address as usize, size as usize) { + STATS[misaligned].fetch_add(1, Ordering::Relaxed); + } + return None; + } + let Some((whole, start)) = region_holding(address, end) else { + STATS[OUTSIDE].fetch_add(1, Ordering::Relaxed); + return None; + }; + // SAFETY: a live buffer. + let gpu = unsafe { whole.GetGPUVirtualAddress() } + (address - start); + if gpu % ALIGN != 0 { + STATS[misaligned].fetch_add(1, Ordering::Relaxed); + return None; + } + if !written_by_no_shader(address, size) { + STATS[SHADERS].fetch_add(1, Ordering::Relaxed); + return None; + } + STATS[READ].fetch_add(1, Ordering::Relaxed); + STATS[READ_BYTES].fetch_add(len.min(CONSTANTS_MOST), Ordering::Relaxed); + match by { + Use::Root => {} + Use::Table => { + STATS[READ_TABLE].fetch_add(1, Ordering::Relaxed); + } + Use::Mirror => { + STATS[READ_MIRROR].fetch_add(1, Ordering::Relaxed); + } + } + Some((whole, gpu)) } -/// Title memory `[start, start + len)` in place, if [`wanted`] and the -/// memory is one stretch of a section: a buffer placed in the region's -/// heap. `None` leaves the caller to do what it did before. -pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> { - if !wanted(start, len) { +/// Small (`<= 64 KiB`), CPU-written vertex/index window insideported memory +/// that is neither written by shaders/copies nor inside a VRAM-resident +/// (`carded`) buffer: the host resource and GPU address in place, or `None`. +pub(crate) fn stream_bytes(address: u64, len: u64) -> Option<(ID3D12Resource, u64)> { + if len == 0 || len > CONSTANTS_MOST || address >= LOW { + return None; + } + let end = address.checked_add(len)?; + if end > LOW { + return None; + } + // Constraint 2: keep static VRAM-resident (`carded`) geometry on the card, + // while letting repeatedly CPU-written dynamic streams (`<= 64 KiB`) read in place. + if crate::shadow::in_card_static(address, len) { + return None; + } + let (whole, start) = region_holding(address, end)?; + if !written_by_no_shader(address, len) { + return None; + } + // SAFETY: a live buffer. + let gpu = unsafe { whole.GetGPUVirtualAddress() } + (address - start); + STATS[STREAM_READ].fetch_add(1, Ordering::Relaxed); + STATS[STREAM_READ_BYTES].fetch_add(len, Ordering::Relaxed); + Some((whole, gpu)) +} + +/// The pages below [`LOW`] of `[at, at + len)`, if any. +fn pages(at: usize, len: usize) -> Option<std::ops::RangeInclusive<usize>> { + let (at, end) = (at as u64, (at as u64).saturating_add(len as u64).min(LOW)); + (len > 0 && at < end).then(|| (at / 4096) as usize..=((end - 1) / 4096) as usize) +} + +/// [`PAGE_MARKS`]' mark of a copy recorded in `frame`: 1 to +/// [`FOR_GOOD`] - 1. +fn stamp(frame: u64) -> u32 { + (frame % u64::from(FOR_GOOD - 1)) as u32 + 1 +} + +/// A write on the card bound for title memory `[at, at + len)` was +/// recorded (a read-back): its pages are never read in place again +/// ([`constants`]). +pub(crate) fn gpu_bound(at: usize, len: usize) { + for page in pages(at, len).into_iter().flatten() { + if PAGE_MARKS[page].load(Ordering::Relaxed) != FOR_GOOD { + PAGE_MARKS[page].store(FOR_GOOD, Ordering::Relaxed); + } + } +} + +/// A title buffer copy into `[at, at + len)` was recorded (done on the CPU +/// at submission, on the card in front of the lists, or at its place in +/// the list): its pages are not read in place for [`COPY_FRAMES`] frames, +/// until what the card did of it has landed. +pub(crate) fn copy_bound(at: usize, len: usize) { + let now = stamp(crate::frame::current()); + for page in pages(at, len).into_iter().flatten() { + let mark = &PAGE_MARKS[page]; + let was = mark.load(Ordering::Relaxed); + if was != FOR_GOOD && was != now { + mark.store(now, Ordering::Relaxed); + } + } +} + +/// Whether no shader or copy on the card writes a page of `[at, at + len)` +/// (below [`LOW`], `len` > 0), as [`PAGE_MARKS`] and the landings tell. +fn written_by_no_shader(at: u64, len: u64) -> bool { + let now = stamp(crate::frame::current()); + let marked = |page: usize| match PAGE_MARKS[page].load(Ordering::Relaxed) { + 0 => false, + FOR_GOOD => true, + copied => u64::from(now.wrapping_sub(copied)) <= COPY_FRAMES, + }; + if pages(at as usize, len as usize).into_iter().flatten().any(marked) { + return false; + } + !crate::watch::landed_lately(at as usize, len as usize, LANDED_FRAMES) +} + +/// The region holding `[at, end)`: its whole buffer and start, opened if +/// none does and the memory may be asked about now. +fn region_holding(at: u64, end: u64) -> Option<(ID3D12Resource, u64)> { + let hi = BOUNDS[1].load(Ordering::Relaxed); + if hi != 0 && at >= BOUNDS[0].load(Ordering::Relaxed) && end <= hi { + let regions = REGIONS.read().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = regions.iter().find(|r| r.start <= at && end <= r.end) { + return Some((r.whole.clone(), r.start)); + } + } + if REFUSED.load(Ordering::Relaxed) { + return None; + } + let cell = &TRIED[(at >> 26) as usize]; + let now = crate::frame::current(); + let tried = cell.load(Ordering::Relaxed); + if tried != 0 && now < tried - 1 + RETRY_FRAMES { return None; } let host = crate::host::host()?; - match place_in(&host.device, start, len) { - Ok(placed) => { - crate::inplace::counted(window, len); - let n = STATS[2].fetch_add(1, Ordering::Relaxed) + 1; - if n <= 32 || n.is_power_of_two() { - tracing::info!( - start = format_args!("{start:#x}"), - len, - window, - "renderer port 1: title memory in place, read and written by the card where the title has it" - ); + match region_for(&host.device, at, end) { + Ok(found) => Some(found), + Err((why_at, why)) => { + cell.store(now + 1, Ordering::Relaxed); + if why_at == HOST_REFUSED { + REFUSED.store(true, Ordering::Relaxed); } - Some(placed) - } - Err((at, why)) => { - let n = STATS[at].fetch_add(1, Ordering::Relaxed) + 1; - if n <= 8 || n.is_power_of_two() { - tracing::warn!(start = format_args!("{start:#x}"), len, window, why, "renderer port 1: title memory not in place, a copy as before"); + let n = STATS[why_at].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + tracing::warn!( + at = format_args!("{at:#x}"), + why, + "renderer port 1: title memory not opened in place, constants there are read from the card copy" + ); } None } } } -/// [`place_for`]'s work: the region holding the pages of `[start, start + -/// len)`, opened if none does, and a buffer placed in it. `Err` with the -/// statistic to count and why. -pub(crate) fn place_in(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, (usize, String)> { - let at = start & !(K64 - 1); - let end = (start + len.max(1)).next_multiple_of(K64); - let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); - let i = match regions.iter().position(|r| r.start <= at && end <= r.end) { - Some(i) => i, - None => { - let region = open_region(device, at, end)?; - regions.push(region); - let n = regions.len() - 1; - let r = ®ions[n]; - STATS[0].fetch_add(1, Ordering::Relaxed); - STATS[1].fetch_add(r.end - r.start, Ordering::Relaxed); - bounds(®ions); - n - } - }; - let region = ®ions[i]; - let buffer = crate::inplace::place(device, ®ion.heap, at - region.start, end - at).map_err(|e| (6, format!("no buffer placed in the region: {e}")))?; - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); - Ok(Placed { buffer, heap: region.heap.clone(), gpu, bias: start - at }) +/// The region holding the pages of `[at, end)`, opened if none does: its +/// whole buffer and start. `Err` with the statistic to count and why. +fn region_for(device: &ID3D12Device, at: u64, end: u64) -> Result<(ID3D12Resource, u64), (usize, String)> { + let mut regions = REGIONS.write().unwrap_or_else(|e| e.into_inner()); + if let Some(r) = regions.iter().find(|r| r.start <= at && end <= r.end) { + return Ok((r.whole.clone(), r.start)); + } + let region = open_region(device, at & !(K64 - 1), end.max(at + 1).next_multiple_of(K64))?; + let found = (region.whole.clone(), region.start); + STATS[OPENED].fetch_add(1, Ordering::Relaxed); + STATS[OPENED_BYTES].fetch_add(region.end - region.start, Ordering::Relaxed); + regions.push(region); + bounds(®ions); + Ok(found) } /// Opens the stretch around `[at, end)` (64 KiB aligned) as a heap through -/// a view of ours of the same pages. +/// a view of ours of the same pages, with one buffer over all of it. fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usize, String)> { let Some((first, bytes, section, offset)) = stretch(at as usize, (end - at) as usize) else { - return Err((3, format!("not one stretch of a section: {:?}", cover(at as usize, (end - at) as usize)))); + return Err((NOT_STRETCH, format!("not one stretch of a section: {:?}", cover(at as usize, (end - at) as usize)))); }; - // The whole stretch, kept to what may be ported: the next buffer in it + // The whole stretch, kept to what may be ported: the next ask in it // finds the region made. let (mut first, mut bytes, mut offset) = (first as u64, bytes as u64, offset); if first < LOW && first + bytes > LOW { @@ -185,44 +412,52 @@ fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usiz (first, bytes) = (at, end - at); } if bytes > MOST { - return Err((3, format!("{bytes:#x} bytes, over the most of a region"))); + return Err((NOT_STRETCH, format!("{bytes:#x} bytes, over the most of a region"))); } if first > at || first + bytes < end || offset % K64 != 0 { - return Err((3, format!("the stretch {first:#x}+{bytes:#x} does not hold it"))); + return Err((NOT_STRETCH, format!("the stretch {first:#x}+{bytes:#x} does not hold it"))); } // SAFETY: the section of a view the title has; the runtime keeps its // handle open while a view of it is there, and the range is inside it. let view = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, (offset >> 32) as u32, offset as u32, bytes as usize) }.Value as usize; if view == 0 { - return Err((5, format!("no view of the stretch: {}", std::io::Error::last_os_error()))); + return Err((NO_VIEW, format!("no view of the stretch: {}", std::io::Error::last_os_error()))); } let unmap = || { - // SAFETY: our own view, nothing opened on it. + // SAFETY: our own view, nothing opened on it any more. unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; }; if !committed(view, bytes as usize) { unmap(); - return Err((4, "pages of the stretch are not committed".to_owned())); - } - match crate::inplace::open(device, crate::inplace::From::Part(view, bytes as usize)) { - Ok(heap) => { - tracing::info!( - start = format_args!("{first:#x}"), - bytes, - section = format_args!("{section:#x}"), - offset = format_args!("{offset:#x}"), - view = format_args!("{view:#x}"), - "renderer port 1: a stretch of the title's graphics memory opened as a host heap through a view of ours" - ); - // shortcut: the view stays mapped for good (the heap holds its - // pages while anything names it). - Ok(Region { start: first, end: first + bytes, heap }) + return Err((NOT_COMMITTED, "pages of the stretch are not committed".to_owned())); + } + let heap = match crate::inplace::open(device, crate::inplace::From::Part(view, bytes as usize)) { + Ok(heap) => heap, + Err(e) => { + unmap(); + return Err((HOST_REFUSED, format!("refused by the host: {e}"))); } + }; + let whole = match crate::inplace::place(device, &heap, 0, bytes) { + Ok(whole) => whole, Err(e) => { + drop(heap); unmap(); - Err((5, format!("refused by the host: {e}"))) + return Err((NO_BUFFER, format!("no buffer placed over the region: {e}"))); } - } + }; + crate::host::name(&whole, || format!("title memory {first:#x}+{bytes:#x} in place")); + tracing::info!( + start = format_args!("{first:#x}"), + bytes, + section = format_args!("{section:#x}"), + offset = format_args!("{offset:#x}"), + view = format_args!("{view:#x}"), + "renderer port 1: a stretch of the title's graphics memory opened as a host heap through a view of ours" + ); + // shortcut: the view stays mapped for good (the heap holds its pages + // while anything names it). + Ok(Region { start: first, end: first + bytes, whole, _heap: heap }) } /// Whether every page of `[at, at + len)` is committed. @@ -248,16 +483,16 @@ fn bounds(regions: &[Region]) { } /// The title maps other pages at `[at, at + len)`: the regions over it are -/// forgotten (what is placed in them is let go by the caller). +/// forgotten (lists and slots that hold their buffers keep them alive). pub(crate) fn forget(at: usize, len: usize) { let (at, end) = (at as u64, (at as u64).saturating_add(len as u64)); if BOUNDS[1].load(Ordering::Relaxed) <= at || BOUNDS[0].load(Ordering::Relaxed) >= end { return; } - let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let mut regions = REGIONS.write().unwrap_or_else(|e| e.into_inner()); let before = regions.len(); regions.retain(|r| r.end <= at || r.start >= end); - STATS[7].fetch_add((before - regions.len()) as u64, Ordering::Relaxed); + STATS[FORGOTTEN].fetch_add((before - regions.len()) as u64, Ordering::Relaxed); bounds(®ions); } @@ -270,44 +505,59 @@ fn touches(at: usize, len: usize) -> bool { /// A fill of upload memory read `len` bytes at `src` on the CPU. pub(crate) fn filled(src: usize, len: usize) { if touches(src, len) { - STATS[9].fetch_add(1, Ordering::Relaxed); - STATS[10].fetch_add(len as u64, Ordering::Relaxed); + STATS[FILLS].fetch_add(1, Ordering::Relaxed); + STATS[FILL_BYTES].fetch_add(len as u64, Ordering::Relaxed); } } /// A title buffer copy was done on the CPU. pub(crate) fn copied(dst: usize, src: usize, len: usize) { if touches(dst, len) || touches(src, len) { - STATS[11].fetch_add(1, Ordering::Relaxed); - STATS[12].fetch_add(len as u64, Ordering::Relaxed); + STATS[COPIES].fetch_add(1, Ordering::Relaxed); + STATS[COPY_BYTES].fetch_add(len as u64, Ordering::Relaxed); } } -/// For the frame-rate line: what is in place, and what of ours read or -/// wrote it on the CPU per frame. +/// For the frame-rate line: what is in place, what was bound there, and +/// what was not and why. pub(crate) fn log(frames: f64) { - if !on() { + let s: Vec<u64> = STATS[..READ].iter().map(|s| s.load(Ordering::Relaxed)).collect(); + let taken: Vec<f64> = STATS[READ..].iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if s[OPENED] == 0 && s[NOT_STRETCH..=NO_BUFFER].iter().all(|&n| n == 0) { return; } - let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); - let per: Vec<f64> = STATS[9..].iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let per = |at: usize| taken[at - READ]; + let stream_reads = per(STREAM_READ); + let stream_bytes = per(STREAM_READ_BYTES) / 1024.0; tracing::info!( - "renderer port 1 (VICTORY_PORT_CONSTANTS=1): {} regions of the title's graphics memory in place ({} MB), {} title buffers and windows placed in them \ - (no host copy, nothing sent up or fetched back for them); per frame on the CPU: {:.0} fills read out of them ({:.1} KB), {:.1} buffer copies \ - touching them ({:.1} KB); since the start refused: {} not one stretch of a section, {} not committed, {} by the host, {} no buffer; {} regions \ - forgotten (other pages mapped there)", - s[0], - s[1] >> 20, - s[2], - per[0], - per[1] / 1024.0, - per[2], - per[3] / 1024.0, - s[3], - s[4], - s[5], - s[6], - s[7], + "renderer port 1: {} regions of the title's graphics memory in place ({} MB); per frame: {:.0} constant views read in place ({:.1} KB: \ + nothing refreshed, filled or waited for; {:.0} in tables' slots, {:.0} in title slots, the rest root views), {:.0} small stream views in place ({:.1} KB), \ + not in place: off 4 bytes {:.0} root, {:.0} in tables' slots, {:.0} in title slots, {:.0} on pages shaders write, {:.0} outside the regions; \ + on the CPU {:.0} fills read out of them ({:.1} KB), {:.1} buffer copies touching them ({:.1} KB); since the start not opened: \ + {} not one stretch of a section, {} not committed, {} no view, {} by the host, {} no buffer; {} regions forgotten (other pages mapped there)", + s[OPENED], + s[OPENED_BYTES] >> 20, + per(READ), + per(READ_BYTES) / 1024.0, + per(READ_TABLE), + per(READ_MIRROR), + stream_reads, + stream_bytes, + per(MISALIGNED), + per(MISALIGNED_TABLE), + per(MISALIGNED_MIRROR), + per(SHADERS), + per(OUTSIDE), + per(FILLS), + per(FILL_BYTES) / 1024.0, + per(COPIES), + per(COPY_BYTES) / 1024.0, + s[NOT_STRETCH], + s[NOT_COMMITTED], + s[NO_VIEW], + s[HOST_REFUSED], + s[NO_BUFFER], + s[FORGOTTEN], ); } @@ -315,26 +565,49 @@ pub(crate) fn log(frames: f64) { mod tests { use super::*; - /// Only the title's 32-bit memory is asked for. + /// Only the title's 32-bit memory is read in place, and only views + /// with bytes. #[test] - fn only_memory_below_4_gib_is_wanted_with_the_switch() { - // The switch is read once from the environment; tests do not set - // it, so nothing is wanted. - if !on() { - assert!(!wanted(0x3431_0000, 0x1000)); - } - let low = |at: u64, len: u64| at.checked_add(len).is_some_and(|end| end <= LOW && len > 0); - assert!(low(0x34e1_0000, 0xae0_0000)); - assert!(!low(0xffff_0000, 0x2_0000)); - assert!(!low(0xe1c80_0000, 0x1000)); - assert!(!low(u64::MAX, 2)); + fn only_memory_below_4_gib_is_read_in_place() { + assert!(constants(0xe1c80_0000, 256, Use::Table).is_none()); + assert!(constants(0xffff_ff00, 0x1000, Use::Mirror).is_none()); + assert!(constants(0x3431_0000, 0, Use::Table).is_none()); + assert!(constants(u64::MAX - 255, 16, Use::Root).is_none()); + assert!(stream_bytes(0xe1c80_0000, 64).is_none()); + assert!(stream_bytes(0x3431_0000, 0).is_none()); + assert!(stream_bytes(0x3431_0000, CONSTANTS_MOST + 1).is_none()); + assert!(stream_bytes(0xffff_ffc0, 128).is_none()); + } + + /// A page a write on the card is bound for is the shaders' for good; + /// its neighbours are not. + #[test] + fn pages_bound_for_shader_writes_are_not_read_in_place() { + let at = 0x7ff0_0000u64; + assert!(written_by_no_shader(at, 0x3000)); + gpu_bound(at as usize + 0x1100, 0x10); + assert!(!written_by_no_shader(at, 0x3000)); + assert!(!written_by_no_shader(at + 0x1000, 0x100)); + assert!(written_by_no_shader(at, 0x1000)); + assert!(written_by_no_shader(at + 0x2000, 0x1000)); + // A copy recorded into a page: not read in place this frame. + assert!(written_by_no_shader(at + 0x4000, 0x100)); + copy_bound(at as usize + 0x4080, 0x20); + assert!(!written_by_no_shader(at + 0x4000, 0x100)); + assert!(written_by_no_shader(at + 0x5000, 0x100)); + // Past the memory read in place: nothing noted, nothing panics. + gpu_bound(0xffff_f000, 0x10_0000); + gpu_bound(0x1_0000_0000, 0x1000); + copy_bound(0x1_0000_0000, 0x1000); + assert_eq!(stamp(0), 1); + assert_ne!(stamp(u64::from(u32::MAX)), FOR_GOOD); } /// A stretch of a reserved section, mapped as `xmem` maps physical /// pages (views of consecutive pages in turn, committed), is opened /// through a view of ours: the card reads the bytes the title's views /// show, at the buffer's offset, and its writes show in them; a second - /// buffer in the stretch is placed in the same region. + /// ask in the stretch finds the same region. #[test] fn warp_a_stretch_of_a_reserved_section_is_used_in_place_through_a_view_of_ours() { let _turn = crate::indirect::tests::warp_turn(); @@ -371,23 +644,24 @@ mod tests { } let base = hole as u64; let (start, len) = (base + K as u64 + 0x40, 5 * K as u64); - let placed = place_in(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); - assert_eq!(placed.bias, 0x40); + let (whole, first) = region_for(&device, start, start + len).unwrap_or_else(|e| panic!("not opened: {e:?}")); + assert!(first <= start && first % K as u64 == 0); + let offset = start - first; let mut rig = crate::inplace::Rig::new(&device).unwrap(); for (i, b) in std::slice::from_raw_parts_mut(start as *mut u8, len as usize).iter_mut().enumerate() { *b = (i * 7 + 3) as u8; } - let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + let got = rig.fetch(&whole, offset, len as usize).unwrap(); assert!(got == std::slice::from_raw_parts(start as *const u8, len as usize), "the card reads the title's bytes, across both views"); - rig.store(&placed.buffer, placed.bias + 3 * K as u64, &[0x5a; 256]).unwrap(); + rig.store(&whole, offset + 3 * K as u64, &[0x5a; 256]).unwrap(); assert!(std::slice::from_raw_parts((start + 3 * K as u64) as *const u8, 256).iter().all(|&b| b == 0x5a), "the card's write shows in the title's view"); - // Another buffer in the same stretch: the same region. - let regions = REGIONS.lock().unwrap().len(); - let second = place_in(&device, base + 6 * K as u64, 100).unwrap_or_else(|e| panic!("not placed: {e:?}")); - assert_eq!(REGIONS.lock().unwrap().len(), regions, "one region for the stretch"); - assert_eq!(second.bias, 0); + // Another ask in the same stretch: the same region. + let regions = REGIONS.read().unwrap().len(); + let (second, again) = region_for(&device, base + 6 * K as u64, base + 6 * K as u64 + 100).unwrap_or_else(|e| panic!("not opened: {e:?}")); + assert_eq!(REGIONS.read().unwrap().len(), regions, "one region for the stretch"); + assert_eq!(again, first); // The title's views may change under the heap. - drop((placed, second)); + drop((whole, second)); forget(base as usize, 8 * K); for view in views { assert!(mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0, "the title's own view can be unmapped"); diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index 0d43ef11b..ae9c9ee70 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -106,8 +106,31 @@ pub(super) trait Work: Send { /// Told just before [`Work::go`] of a submission: the highest mark of /// what it is made of and of the waits its queue went past. fn marked(&mut self, _mark: u64) {} + /// What `ask` stands at, for the line's report of a stall ([`stall_limit`]). + fn describe(_ask: &Self::Ask) -> String { + String::new() + } +} + +/// How long the line may stand with nothing free to run and no present in it +/// before its oldest entry goes regardless (`VICTORY_LINE_STALL_MS`, 1500 by +/// default; 0: never), as a present makes it go every frame +/// (`super::forces`). The title's threads stand at a fence on the CPU while +/// the signal it waits for stands behind a queue's wait: no present comes, +/// and the line stood for good until the title's own watchdog ended it +/// ("Unsignaled CrossQueueBarrier" in its crash report, a write to address 0 +/// after some 30 s without a frame: run of 2026-11-27 15:29, and 25 more +/// crash reports since 2026-11-24). On the console a wait of the card's lasts +/// microseconds; a line that stood this long would never move on its own. +fn stall_limit() -> Option<Duration> { + static LIMIT: OnceLock<u64> = OnceLock::new(); + let ms = *LIMIT.get_or_init(|| number("VICTORY_LINE_STALL_MS").map_or(1500, |n| n as u64)); + (ms > 0 && super::forces()).then(|| Duration::from_millis(ms)) } +/// Stalls of the line broken since the start ([`stall_limit`]). +static STALLS: AtomicU64 = AtomicU64::new(0); + struct Entry<W> { number: u64, queue: usize, @@ -265,6 +288,8 @@ impl<W: Work> Lane<W> { /// Looks at the line for as long as the process runs. fn serve(&self) -> ! { + // When the line last moved (or was empty). + let mut moved_at = Instant::now(); loop { let (asked, limit) = { let mut state = self.lock(); @@ -284,7 +309,19 @@ impl<W: Work> Lane<W> { } (state.asked, state.next) }; - self.look(limit); + if self.look(limit) > 0 || self.lock().items.is_empty() { + moved_at = Instant::now(); + } else if let Some(stall) = stall_limit() + && moved_at.elapsed() >= stall + { + // Nothing free to run for this long and no present to make + // the oldest go: it goes now (see [`stall_limit`]). + self.report_stall(limit, moved_at.elapsed()); + if self.step(limit, true) { + self.look(limit); + } + moved_at = Instant::now(); + } let mut state = self.lock(); state.served = state.served.max(asked); drop(state); @@ -292,9 +329,49 @@ impl<W: Work> Lane<W> { } } - /// Does what is free to run of the entries before number `limit`. - pub(super) fn look(&self, limit: u64) { - while self.step(limit) {} + /// Does what is free to run of the entries before number `limit`: how + /// many entries were done. + pub(super) fn look(&self, limit: u64) -> usize { + let mut done = 0; + while self.step(limit, false) { + done += 1; + } + done + } + + /// Says what each queue's first entry stands at when the line stood + /// `stood` with nothing free to run ([`stall_limit`]). + fn report_stall(&self, limit: u64, stood: Duration) { + let n = STALLS.fetch_add(1, Relaxed) + 1; + let state = self.lock(); + let mut heads: Vec<String> = Vec::new(); + let mut seen: Vec<usize> = Vec::new(); + for e in state.items.iter().take_while(|e| e.number < limit) { + if seen.contains(&e.queue) { + continue; + } + seen.push(e.queue); + let what = match e.what.ask() { + Some(ask) => format!("stands at {}", W::describe(&ask)), + None if e.what.shows() => "a present".to_owned(), + None => "free to go".to_owned(), + }; + heads.push(format!("queue {:#x} (kind {:?}) #{}: {what}", e.queue, super::kind_of(e.queue), e.number)); + } + let (items, presents, runs) = (state.items.len(), state.presents, state.runs); + drop(state); + // (Every stall while there are few; then one in a hundred.) + if n <= 32 || n.is_multiple_of(100) { + tracing::warn!( + stalls = n, + stood_ms = stood.as_millis() as u64, + items, + presents, + runs, + heads = %heads.join("; "), + "the line of submissions stood with nothing free to run and no present to move it: its oldest entry goes (VICTORY_LINE_STALL_MS)" + ); + } } /// The parts of `entry`, which stands for them, in place `at`. @@ -311,8 +388,9 @@ impl<W: Work> Lane<W> { } /// Does one entry: the oldest that is the first of its queue and free to - /// run. Whether there was one. Only one thread calls this. - fn step(&self, limit: u64) -> bool { + /// run (`stalled`: the oldest, free or not, as a present would make it + /// go). Whether there was one. Only one thread calls this. + fn step(&self, limit: u64, stalled: bool) -> bool { // Each queue's first entry, oldest first. let mut heads: Vec<(u64, usize, Option<W::Ask>, bool)> = Vec::new(); // Whether one of them stands for others not known yet. @@ -345,7 +423,7 @@ impl<W: Work> Lane<W> { return false; } let state = self.lock(); - if !super::forces() || !state.items.iter().any(|e| e.number < limit && e.what.shows()) { + if !stalled && (!super::forces() || !state.items.iter().any(|e| e.number < limit && e.what.shows())) { return false; } (first, true) @@ -546,6 +624,20 @@ impl Work for Job { } } + fn describe(ask: &Ask) -> String { + match ask { + &Ask::Wait(fence, value) => { + format!("a fence {fence:#x} to reach {value} (it is at {})", crate::fence::completed(fence as This)) + } + Ask::Value(wait) => format!("a memory value {wait:?} (met: {})", super::value_met(wait)), + Ask::Lists(recordings) => format!( + "lists being translated ({} of {} done)", + recordings.iter().filter(|r| r.done()).count(), + recordings.len() + ), + } + } + fn shows(&self) -> bool { matches!(self, Job::Present(..)) } @@ -619,6 +711,12 @@ impl Work for Job { fn go(self, forced: bool) { let began = Instant::now(); + // Where the thread's time goes (the frame line): showing frames, signals and waits. + let kind = match &self { + Job::Present(..) => Some(BUSY_PRESENT), + Job::Signal(..) | Job::Wait(..) | Job::Value(..) => Some(BUSY_SIGNALS), + _ => None, + }; let _doing = crate::timeline::span(match self { Job::Run(..) => "the line: a submission", Job::Joined(..) => "the line: submissions joined", @@ -690,7 +788,11 @@ impl Work for Job { } // (The mark was this submission's alone.) crate::heap_marks::set_mark(0); - STATS[BUSY].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + let took = began.elapsed().as_micros() as u64; + STATS[BUSY].fetch_add(took, Relaxed); + if let Some(kind) = kind { + STATS[kind].fetch_add(took, Relaxed); + } } } @@ -706,7 +808,7 @@ static QUEUED: AtomicU64 = AtomicU64::new(0); /// present, and for a drain, and the drains; what our thread worked; waits /// not met at a present; parts joined; what our thread spent taking the /// lists of submissions whose translation was done out of the line. -static STATS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12]; +static STATS: [AtomicU64; 14] = [const { AtomicU64::new(0) }; 14]; const RUNS: usize = 0; const PRESENTS: usize = 1; const DEPTH: usize = 2; @@ -722,6 +824,10 @@ const JOINED: usize = 10; /// Microseconds of [`Lane::unfold`] (the lists detached, new host lists /// given to the title's lists), under the line's lock and not in [`BUSY`]. const UNFOLDING: usize = 11; +/// Of [`BUSY`]: presents (the swap chain's Present, unless it is on the presenting thread, +/// `crate::host` `shown`), and signals and met waits. +const BUSY_PRESENT: usize = 12; +const BUSY_SIGNALS: usize = 13; /// How many submissions may be in the line when a submit call returns /// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's). @@ -833,18 +939,33 @@ pub(super) fn drain() { } let began = Instant::now(); LANE.drain(); - STATS[DRAINING].fetch_add(began.elapsed().as_micros() as u64, Relaxed); + let elapsed = began.elapsed().as_micros() as u64; + STATS[DRAINING].fetch_add(elapsed, Relaxed); + if crate::host::render_trace::active() { + crate::host::render_trace::event("title_queue_drained", format_args!("duration_us={elapsed}")); + } STATS[DRAINS].fetch_add(1, Relaxed); } /// A submission of `lists` to queue `this`. pub(super) fn submit(this: This, lists: &[This]) { let queue = this as usize; + if crate::host::render_trace::active() { + crate::host::render_trace::event("title_submit", format_args!("queue={queue:#x}\tlists={}\tqueued={}", lists.len(), QUEUED.load(Relaxed))); + } if crate::list::thin::on() { let recordings = crate::list::thin::submitted(lists); if recordings.is_empty() { return; } + if crate::host::render_trace::active() { + for (index, recording) in recordings.iter().enumerate() { + crate::host::render_trace::event( + "title_submit_list", + format_args!("queue={queue:#x}\tindex={index}\trecording={:#x}", std::sync::Arc::as_ptr(recording) as usize), + ); + } + } let before = QUEUED.fetch_add(1, Relaxed); STATS[DEPTH].fetch_add(before, Relaxed); STATS[DEEPEST].fetch_max(before + 1, Relaxed); @@ -937,7 +1058,8 @@ pub(super) fn present( LANE.push(this as usize, [Job::Present(texture, overlay, shown)]); let began = Instant::now(); let _waiting = crate::timeline::span("a present waits for the one before it to be sent"); - LANE.wait_presents(frames_most()); + let most = if crate::memory::take_sizes_frame() { 0 } else { frames_most() }; + LANE.wait_presents(most); STATS[AT_PRESENT].fetch_add(began.elapsed().as_micros() as u64, Relaxed); } @@ -947,7 +1069,8 @@ pub(super) fn line(frames: f64) { let ms = |i: usize| s[i] / 1000.0 / frames; tracing::info!( "submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \ - when one was added (at most {:.0}); that thread worked {:.1} ms, and {:.2} ms more taking translated lists out of the \ + when one was added (at most {:.0}); that thread worked {:.1} ms (of it {:.1} ms showing frames and {:.2} ms signals and \ + met waits), and {:.2} ms more taking translated lists out of the \ line (under its lock); threads of the title waited {:.1} ms for room in the \ line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}; {:.1} of the \ submissions were prepared together with the one before them (VICTORY_JOIN_PARTS)", @@ -956,6 +1079,8 @@ pub(super) fn line(frames: f64) { s[DEPTH] / s[RUNS].max(1.0), s[DEEPEST], ms(BUSY), + ms(BUSY_PRESENT), + ms(BUSY_SIGNALS), ms(UNFOLDING), ms(ROOM), ms(AT_PRESENT), @@ -1208,6 +1333,30 @@ mod tests { assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0)); } + /// A queue stands at a wait nothing meets, its signal behind it, and no + /// present comes (the title stands at that signal on the CPU): a look + /// leaves it, a stalled step makes the wait go and the signal follow, as a + /// present would have (`stall_limit`). + #[test] + fn a_stalled_line_goes_on_without_a_present() { + let lane = Lane::new(); + let log: Log = Default::default(); + let (never, signalled) = (fence(), fence()); + lane.push(2, [T::Wait(never, 1), T::Run("held", log.clone()), T::Signal(signalled, 1, log.clone())]); + look(&lane); + assert!(log.lock().unwrap().is_empty(), "the wait holds its queue"); + assert_eq!(value(signalled), 0); + let forced = FORCED_HERE.get(); + let limit = lane.lock().next; + assert!(lane.step(limit, true), "the oldest goes"); + assert_eq!(lane.look(limit), 2, "what was behind it is free now"); + assert_eq!(*log.lock().unwrap(), ["held", "signal 1"]); + assert_eq!(value(signalled), 1); + assert_eq!(FORCED_HERE.get(), forced + 1); + let state = lane.lock(); + assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0)); + } + /// With the thread: a fence behind a submission is not reached before the /// submission has been done, presents hold the title back a frame later, /// and a drain comes back when everything was done. diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs index 0e701e5df..7d7755eb2 100644 --- a/crates/victory-gpu/src/residency.rs +++ b/crates/victory-gpu/src/residency.rs @@ -95,6 +95,33 @@ pub(crate) fn limited_host_ram() -> bool { *LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB)) } +/// [`limited_host_ram`] for the texture queue and its uploads: a 32 GB +/// machine is not limited here. The title's working set peaks near 21 GB +/// there (measured), and what is left is sized from what is free +/// ([`staging_ceiling`]), not from the installed total. 16 GB machines are. +/// (The other users of [`limited_host_ram`] keep its 32 GB line.) +pub(crate) fn textures_limited_by_ram() -> bool { + static LIMITED: OnceLock<bool> = OnceLock::new(); + *LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys < 24 * GIB)) +} + +/// Bytes of title memory the copy queue's uploads may have on their way: +/// `floor` when host memory is short or pressured; otherwise a third of what +/// is free (half while a loading screen is up), between `floor` and 6 GiB. +pub(crate) fn staging_ceiling(floor: u64, loading: bool) -> u64 { + if textures_limited_by_ram() { + return 32 * MIB; + } + if pressured() { + return floor.min(64 * MIB); + } + let Some(free) = headroom() else { + return floor; + }; + let share = if loading { free / 2 } else { free / 3 }; + share.clamp(floor, 6 * GIB) +} + fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { if was { physical < 5 * GIB || commit < 6 * GIB @@ -103,6 +130,30 @@ fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { } } +fn log_sample(physical: u64, commit: u64, pressure: bool) { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + + let mut counters = PROCESS_MEMORY_COUNTERS { + cb: std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32, + ..Default::default() + }; + // SAFETY: the output buffer and its byte count match the Windows structure. + if unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) } != 0 { + tracing::info!( + target: "victory_gpu::memory", + frame = crate::frame::current(), + physical_available_mib = physical / MIB, + commit_available_mib = commit / MIB, + working_set_mib = counters.WorkingSetSize as u64 / MIB, + private_commit_mib = counters.PagefileUsage as u64 / MIB, + page_faults_total = counters.PageFaultCount, + pressure, + "host memory sample" + ); + } +} + /// Called by the once-per-second submission sweep. A failed sample keeps the last good state. pub(crate) fn refresh() { let Some(status) = memory_status() else { return }; @@ -110,6 +161,10 @@ pub(crate) fn refresh() { HEADROOM.store(physical.min(commit), Ordering::Relaxed); let was = pressured(); let pressure = next_pressure(was, physical, commit); + static LOG: OnceLock<bool> = OnceLock::new(); + if *LOG.get_or_init(|| crate::switch::on("VICTORY_MEMORY_SAMPLES")) { + log_sample(physical, commit, pressure); + } if pressure != was { PRESSURED.store(pressure, Ordering::Relaxed); if pressure { diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index ab2931ab6..d4893c325 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -11,6 +11,8 @@ use std::ptr::NonNull; use victory_formats::texture; +#[cfg(windows)] +use crate::host::memory_samples::{Allocation, Kind}; use crate::object::{ self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This, guid, @@ -509,7 +511,8 @@ fn twin_texture( TWINS[1].fetch_add(1, Relaxed); return None; }; - let _ = crate::host::resident(&host.device, &texture); + let allocation = Allocation::texture(Kind::DepthTwin, &host.device, &texture); + let _ = crate::host::resident(&host.device, &texture, allocation); crate::host::name(&texture, || { format!("depth twin {}x{} f{}", d.width, d.height, d.format) }); @@ -534,7 +537,7 @@ fn twin_texture( Some(&mut bytes), ); } - let Some(buffer) = host.uav_buffer(bytes) else { + let Some(buffer) = host.uav_buffer_for(bytes, Kind::UavTextureSupport) else { TWINS[1].fetch_add(1, Relaxed); return None; }; @@ -570,7 +573,8 @@ fn twin_texture( tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane"); } texture.map(|texture| { - let _ = crate::host::resident(&host.device, &texture); + let allocation = Allocation::texture(Kind::DepthTwin, &host.device, &texture); + let _ = crate::host::resident(&host.device, &texture, allocation); crate::host::name(&texture, || { format!("depth plane twin {}x{} f{}", d.width, d.height, d.format) }); @@ -1792,26 +1796,30 @@ fn texture_floor_bytes(vram_budget: Option<u64>) -> u64 { } } -/// Whether more host copies of textures the title fills may be made for -/// shaders that pick textures by index (`draw.rs` `heap_textures`): always -/// up to [`texture_floor_bytes`] bytes of them, beyond that while the card's -/// memory in use by this process is under nine tenths of the budget the system -/// gives it ([`room_percent`] says another share; `VICTORY_TEXTURE_BUDGET_MB` -/// sets a limit on those copies' bytes instead). Past the budget the system moves the card's memory into the PC's, -/// which ended runs 20 and 24. #[cfg(windows)] -pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { - use std::sync::atomic::Ordering::Relaxed; - const WITHOUT_BUDGET: u64 = 4 << 30; +fn texture_budget_limit() -> Option<u64> { static LIMIT: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); - let limit = *LIMIT.get_or_init(|| { + *LIMIT.get_or_init(|| { let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; mb.trim().parse::<u64>().ok().map(|mb| mb << 20) - }); + }) +} + +#[cfg(windows)] +fn filled_texture_bytes() -> u64 { // (With the tiles of the copies made level by level, whose own bytes // count as none: `crate::tiles`.) - let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total(); - if let Some(limit) = limit { + KINDS[1].load(std::sync::atomic::Ordering::Relaxed) + crate::tiles::given_total() +} + +/// Admission for copies of textures picked by index. An explicit +/// `VICTORY_TEXTURE_BUDGET_MB` limits their bytes directly. Otherwise, +/// the texture floor and the DXGI budget determine admission. +#[cfg(windows)] +pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { + const WITHOUT_BUDGET: u64 = 4 << 30; + let filled = filled_texture_bytes(); + if let Some(limit) = texture_budget_limit() { return filled < limit; } let floor = texture_floor_bytes(memory.map(|[budget, ..]| budget)); @@ -1819,13 +1827,9 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { return true; } match memory { - // What is kept for card copies of title buffers not made yet - // (`crate::shadow::card_room_kept`) and for the render targets a - // world makes in its first frame ([`targets_room_kept`]) counts as - // used. Some([budget, used, ..]) => { - used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() - < room_line(budget) + let weights = RoomWeights::new(budget, used); + weights.weighed() < weights.line } None => filled < WITHOUT_BUDGET, } @@ -1877,6 +1881,10 @@ pub(crate) fn targets_room_kept() -> u64 { }); // Every host texture's bytes less those of the copies the title fills. let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed)); + // The most the targets have held this run: what the room is sized by + // (`targets_kept_from_peak`), unless the switch above set it flat. + static PEAK: AtomicU64 = AtomicU64::new(0); + let peak = PEAK.fetch_max(targets, Relaxed).max(targets); // The targets' bytes at their last change of 64 MiB or more, and when // they last grew by that much. static GREW: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; @@ -1885,7 +1893,11 @@ pub(crate) fn targets_room_kept() -> u64 { let (last, since) = targets_seen(last, since, targets, now); GREW[0].store(last, Relaxed); GREW[1].store(since, Relaxed); - targets_kept(most, targets, now.saturating_sub(since), settle) + static FLAT: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *FLAT.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_TARGETS_MB").is_some()) { + return targets_kept(most, targets, now.saturating_sub(since), settle); + } + targets_kept_from_peak(most, targets, peak) } /// [`targets_room_kept`]'s record of the targets' bytes (`last`) and of @@ -1916,28 +1928,86 @@ fn targets_kept(most: u64, targets: u64, still_ms: u64, settle: u64) -> u64 { } } -/// What [`room`] weighs now, in MB, for the log: the card's budget, its -/// use, the free part of the texture blocks, what is kept for card copies -/// of title buffers and for render targets, and the line. `None` without -/// the system's numbers, or under `VICTORY_TEXTURE_BUDGET_MB` (which -/// weighs the textures' own bytes instead). +/// What [`targets_room_kept`] keeps of `most` without the flat switch: half +/// as much again as the targets have held at their most (`peak`), and at +/// least 256 MiB, never more than `most`. +/// +/// The flat 3,072 MB is only ever given back once the targets hold half of +/// it, which the runtime's own targets of a 720p world (the SeriesS and +/// SeriesX2 profiles) never do: measured on an 8 GB card (RTX 4060 Laptop, +/// 2026-11-27) the targets held 390 MB, so 2,675 MB stayed reserved for +/// them for the whole run, and the texture queue weighed 6,182 MB against a +/// line of 6,181 MB with the card 41 % used ("no room, new textures wait"): +/// the skin textures of passers-by and the coffee shop's waitress were never +/// uploaded (black faces, the phone's screen empty) until the reserve was +/// cut by hand. Sized by the peak, the same run keeps 195 MB, and the +/// targets of a 1440p world (peak 2.9 GB) still get what they had. +#[cfg(any(windows, test))] +fn targets_kept_from_peak(most: u64, targets: u64, peak: u64) -> u64 { + /// Room for targets to grow into while they are still being made. + const LEAST: u64 = 256 << 20; + peak.saturating_add(peak / 2).max(LEAST).min(most).saturating_sub(targets) +} + +/// Shared by the texture admission check and its log. All values are bytes. #[cfg(windows)] -pub(crate) fn room_terms(memory: Option<[u64; 4]>) -> Option<[u64; 6]> { - if std::env::var_os("VICTORY_TEXTURE_BUDGET_MB").is_some() { - return None; - } - let [budget, used, ..] = memory?; - Some( - [ - budget, +struct RoomWeights { + used: u64, + free_in_blocks: u64, + credit: u64, + buffers: u64, + targets: u64, + line: u64, +} + +#[cfg(windows)] +impl RoomWeights { + fn new(budget: u64, used: u64) -> Self { + let free_in_blocks = crate::pool::texture_room(); + // DXGI charges entire heaps. Crediting the full internal free space + // hid exhaustion when it was fragmented across live heaps. + let credit = free_in_blocks.min(budget / 32); + Self { used, - crate::pool::texture_room(), - crate::shadow::card_room_kept(), - targets_room_kept(), - room_line(budget), - ] - .map(|bytes| bytes >> 20), - ) + free_in_blocks, + credit, + buffers: crate::shadow::card_room_kept(), + targets: targets_room_kept(), + line: room_line(budget), + } + } + + fn weighed(&self) -> u64 { + self.used.saturating_sub(self.credit) + self.buffers + self.targets + } +} + +/// The exact texture admission verdict for a sample with a DXGI budget. +#[cfg(windows)] +pub(crate) fn log_room(memory: Option<[u64; 4]>) { + let Some([budget, used, ..]) = memory else { return }; + if texture_budget_limit().is_some() { + return; + } + let weights = RoomWeights::new(budget, used); + let weighed = weights.weighed(); + let below_floor = filled_texture_bytes() < texture_floor_bytes(Some(budget)); + let verdict = match (below_floor, weighed < weights.line) { + (true, _) => "room (below the texture floor)", + (false, true) => "room", + (false, false) => "no room, new textures wait", + }; + let [budget, used, free, credit, buffers, targets, weighed, line] = [ + budget, used, weights.free_in_blocks, weights.credit, weights.buffers, weights.targets, weighed, weights.line, + ] + .map(|bytes| bytes >> 20); + tracing::info!( + target: "victory_gpu::host", + "the texture queue's room: {used} MB in use - {credit} MB texture block credit (of {free} MB free) + \ + {buffers} MB kept for card copies of title buffers + {targets} MB kept for render targets = {weighed} MB \ + against a line of {line} MB ({:.1} % of a budget of {budget} MB): {verdict}", + line as f64 * 100.0 / budget.max(1) as f64 + ); } /// [`room`] as it was at most a tenth of a second ago, for a question @@ -1987,10 +2057,36 @@ pub(crate) fn room_line(budget: u64) -> u64 { if *SET.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_ROOM_PERCENT").is_some()) { budget / 100 * room_percent() } else { - line_for(budget) + match framegen_planned() { + // Frame generation takes 1.5 to 2 GB of the card's memory when on; + // the targets' own reserve (`targets_room_kept`) is on top of this. + Some(true) => line_for(budget).min(budget / 100 * LINE_FRAMEGEN_PERCENT), + Some(false) => line_for(budget).min(budget / 100 * LINE_FRAMEGEN_READY_PERCENT), + None => line_for(budget), + } } } +/// The texture line's share of the budget with frame generation on from the +/// start, and ready but off. (The launcher set 80 and 86 by a switch; the +/// textures the title asks for are the budget now, and 4.7 GB of 9 GB was +/// used at the 80 % line in the last measured run, so these are nearer 90.) +#[cfg(windows)] +const LINE_FRAMEGEN_PERCENT: u64 = 83; +#[cfg(windows)] +const LINE_FRAMEGEN_READY_PERCENT: u64 = 87; + +/// Whether frame generation was planned at the start (`Some(true)`: on, +/// `Some(false)`: ready but off), from what the launcher told the GPU side. +#[cfg(windows)] +fn framegen_planned() -> Option<bool> { + static PLANNED: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new(); + *PLANNED.get_or_init(|| { + (std::env::var("VICTORY_FRAMEGEN").is_ok_and(|v| v.trim() == "1")) + .then(|| !std::env::var("VICTORY_FRAMEGEN_X").is_ok_and(|x| x.trim() == "0")) + }) +} + /// The budget less what is left free for the host's own needs that are /// made with no room test (render target bursts, buffer copies, upload /// buffers): 768 MiB or a twentieth of the budget, whichever is more; never @@ -2000,7 +2096,7 @@ pub(crate) fn room_line(budget: u64) -> u64 { /// to textures there, and keeps 90 % on cards of 7.5 GB or less. #[cfg(any(windows, test))] fn line_for(budget: u64) -> u64 { - budget.saturating_sub((768u64 << 20).max(budget / 20)).max(budget / 100 * 90) + budget.saturating_sub((768u64 << 20).max(budget / 10)).max(budget / 100 * 88) } /// For the card accounting line ([`card_accounting`]): the title texture @@ -2268,10 +2364,8 @@ pub(crate) fn let_go_idle() { .get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1"))); let (idle_ms, most) = match memory { Some([budget, used, ..]) if keep => { - let used = used.saturating_sub(crate::pool::texture_room()) - + crate::shadow::card_room_kept() - + targets_room_kept(); - crate::host::vram_keep_below(budget, used, room_line(budget)) + let weights = RoomWeights::new(budget, used); + crate::host::vram_keep_below(budget, weights.weighed(), weights.line) } _ => (crate::host::vram_idle_ms(memory), u64::MAX), }; @@ -2770,10 +2864,13 @@ fn host_texture_as( if !reserved && made.is_ok() && let Some(t) = &texture - && let Err(e) = crate::host::resident(&host.device, t).and_then(|()| crate::host::mapped(&host.device)) { - tracing::warn!(error = %e, desc = ?d, "a host texture is not resident"); - texture = None; + let kind = if fills(desc) { Kind::SampledTexture } else { Kind::WritableTexture }; + let allocation = Allocation::texture(kind, &host.device, t); + if let Err(e) = crate::host::resident_and_mapped(&host.device, t, allocation) { + tracing::warn!(error = %e, desc = ?d, "a host texture is not resident"); + texture = None; + } } if let Some(t) = &texture { crate::host::name(t, || { @@ -3320,6 +3417,9 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { return None; } map.insert((address, *desc), out as usize); + // What lives at that address is known from now on: a DirectStorage + // request landing there later can be made ready (`texture::ledger`). + crate::texture::ledger::desc_known(address, desc); crate::texture::placed_in_host_written(address, desc); placed_inside_target(address, out); resource(out) @@ -4810,17 +4910,17 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB); } - /// The texture queue's line: the budget less 768 MiB or 5 %, never under - /// 90 % of it. + /// The texture queue's line: the budget less 768 MiB or 10 %, never under + /// 88 % of it. #[test] fn room_line_follows_the_budget() { const MIB: u64 = 1 << 20; - // 10,600 MB: 768 MiB free (92.8 %), not 1,060 MB. - assert_eq!(line_for(10_600 * MIB), 9_832 * MIB); - // 24 GB: 5 % free. - assert_eq!(line_for(24_000 * MIB), 22_800 * MIB); - // 6 GB: 90 % (768 MiB would be more than a tenth). - assert_eq!(line_for(6_000 * MIB), 6_000 * MIB / 100 * 90); + // 10,600 MB: 10 % free (1,060 MiB), matching the headroom needed before DXGI paging/OOM. + assert_eq!(line_for(10_600 * MIB), 9_540 * MIB); + // 24 GB: 10 % free. + assert_eq!(line_for(24_000 * MIB), 21_600 * MIB); + // 6 GB: 88 % floor (768 MiB would leave 87.2 %). + assert_eq!(line_for(6_000 * MIB), 6_000 * MIB / 100 * 88); assert_eq!(line_for(0), 0); } @@ -4849,6 +4949,25 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(targets_seen(last, since, 2400 * MIB, 30_000), (2400 * MIB, 30_000)); } + /// The room kept for render targets follows the most they have held, + /// not a flat 3,072 MB. + #[test] + fn room_for_targets_follows_their_peak() { + const MIB: u64 = 1 << 20; + let most = 3072 * MIB; + // The SeriesS profile on an 8 GB card: the targets stay at 390 MB, + // and 195 MB is kept where the flat reserve kept 2,682 MB. + assert_eq!(targets_kept_from_peak(most, 390 * MIB, 390 * MIB), 195 * MIB); + // A world's first frames: half as much again as their peak so far. + assert_eq!(targets_kept_from_peak(most, 650 * MIB, 650 * MIB), 325 * MIB); + // 1440p: the peak passes what the switch allows; never more than it. + assert_eq!(targets_kept_from_peak(most, 2900 * MIB, 2900 * MIB), 172 * MIB); + // A scene's targets given back: the peak still holds what they may want. + assert_eq!(targets_kept_from_peak(most, 0, 2900 * MIB), most); + // Nothing made yet: at least 256 MiB. + assert_eq!(targets_kept_from_peak(most, 0, 0), 256 * MIB); + } + /// A placed texture viewed from a later level has a host copy of that /// and the smaller levels; a view from an earlier one gets another. #[cfg(windows)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 94102b882..1bc30f87d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,11 +16,12 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; +use crate::host::memory_samples::Kind; use crate::host::{HostList, host}; use crate::watch::PAGE; @@ -48,11 +49,27 @@ pub(crate) struct Shadow { /// a range holds in part cannot say so in `copied`. Locked inside /// `copied`'s lock. ranged: Mutex<[(usize, usize, u64); 2]>, + /// Of pages taken in part (by index, as `copied`): the asking after + /// which each 4 KiB part was last taken whole ([`stamp_taken`]). Without + /// it a page a refresh held only in part (at a range's end, beside a + /// range shaders may be writing) kept the note of its last whole take, + /// and once the title wrote any of it the refresh took its part again + /// at every refresh, written or not, until one took it whole: beside + /// the ranges flights keep declaring that was never. Locked inside + /// `copied`'s lock; `ranged`'s is never held while it is taken. + parts_taken: Mutex<crate::watch::PartsTaken>, /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex<Vec<(usize, usize)>>, + /// Lock-free mirror of `!pending.is_empty()` (`0` when empty). + pending_len: AtomicU32, + /// Lock-free clean-range memoization for `fast_nothing_new`: + /// `(from..to)` slots verified clean against `watch::block_write_sig`. + clean: [CleanSlot; CLEAN_SLOTS], + /// Round-robin eviction cursor when all [`CLEAN_SLOTS`] are occupied. + clean_next: AtomicU32, /// With [`relay`]: how many submissions not yet copied back declared /// each range of `pending` ([`Flights`]). Locked inside `pending`'s /// lock. @@ -107,6 +124,34 @@ pub(crate) struct Shadow { place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, } +const CLEAN_SLOTS: usize = 4; + +/// One slot of [`Shadow::clean`]: a range `(from..to)` verified clean at +/// `(sig, ask_end)`, guarded by an even/odd `revision` seqlock. +struct CleanSlot { + from: AtomicU64, + to: AtomicU64, + sig: AtomicU64, + ask_end: AtomicU64, + revision: AtomicU64, +} + +impl CleanSlot { + fn new() -> Self { + Self { + from: AtomicU64::new(0), + to: AtomicU64::new(0), + sig: AtomicU64::new(0), + ask_end: AtomicU64::new(0), + revision: AtomicU64::new(0), + } + } + + fn clear(&self) { + self.sig.store(0, Ordering::Release); + } +} + /// What a copy in the card's memory ([`cards`]) has beside the buffer /// shaders see. struct Card { @@ -119,6 +164,8 @@ struct Card { /// first declared for the copy, and compared with the card's side, on /// the card, after each submission that declares some. before: Mutex<Option<ID3D12Resource>>, + /// Lock-free mirror of `before.is_some()` (monotonically set once `before` is made). + has_before: std::sync::atomic::AtomicBool, /// Offsets of the copy whose bytes changed on the CPU's side and have /// not gone to the card's side yet. dirty: Mutex<Vec<(usize, usize)>>, @@ -136,6 +183,21 @@ struct Card { size: u64, } +impl Card { + fn new(staging: ID3D12Resource, size: u64) -> Self { + Self { + staging, + before: Mutex::default(), + has_before: std::sync::atomic::AtomicBool::new(false), + dirty: Mutex::default(), + sent: Mutex::default(), + touched: Default::default(), + me: std::sync::OnceLock::new(), + size, + } + } +} + /// Whether the host copies of big title buffers are in the card's own /// memory (on by default since run 75 showed it holds: the BVH skinning /// list went from 50.5 to 4.5 ms on the card; `VICTORY_CARD_BUFFERS=0` @@ -463,7 +525,7 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> { CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); return None; } - let buffer = host.uav_buffer(size); + let buffer = host.uav_buffer_for(size, Kind::UavShadow); if buffer.is_none() { CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); } @@ -608,7 +670,7 @@ fn window_room_for(size: u64) -> Option<ID3D12Resource> { WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); return None; } - let buffer = host.uav_buffer(size); + let buffer = host.uav_buffer_for(size, Kind::UavShadow); if buffer.is_none() { WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); } @@ -764,10 +826,45 @@ pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize /// Copies of memory (from, to, bytes: apart), on several threads if they are /// many. +/// +/// The sends of copies in the card's memory (`host::send`) come here once a +/// submission, some 3 MB each, 56 MB a frame into write-combined upload +/// memory: below the old 4 MB line all of it went one copy after another on +/// the submitting thread, the critical path. Now anything past [`PIECE`] is +/// cut into pieces of that size and spread over the kept threads +/// (`crate::land::each_under`), the submitting thread one of them. pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) { + const PIECE: usize = 256 << 10; let bytes: usize = copies.iter().map(|c| c.2).sum(); - if bytes > 4 << 20 { - wide(copy_jobs(copies)); + if bytes > 2 * PIECE { + let mut pieces: Vec<(usize, usize, usize)> = Vec::with_capacity(copies.len() + bytes / PIECE); + let (mut group, mut grouped) = (Vec::new(), 0usize); + let mut starts = vec![0usize]; + for (src, dst, len) in copies { + let mut at = 0; + while at < len { + let n = (PIECE - grouped).min(len - at); + group.push((src + at, dst + at, n)); + at += n; + grouped += n; + if grouped >= PIECE { + pieces.append(&mut group); + starts.push(pieces.len()); + grouped = 0; + } + } + } + if !group.is_empty() { + pieces.append(&mut group); + starts.push(pieces.len()); + } + let one = |i: usize| { + for &(src, dst, len) in &pieces[starts[i]..starts[i + 1]] { + // SAFETY: the caller's ranges, apart from one another. + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) }; + } + }; + crate::land::each_under(starts.len() - 1, &one); return; } for (src, dst, len) in copies { @@ -805,14 +902,18 @@ fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { // (The sort that finds what is in order already: they come as a few // stretches of tens of thousands in order, put behind one another.) ranges.sort(); - let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); - for (from, to) in ranges { - match out.last_mut() { - Some(last) if from <= last.1 => last.1 = last.1.max(to), - _ => out.push((from, to)), + let mut kept = 0; + for i in 0..ranges.len() { + let (from, to) = ranges[i]; + if kept != 0 && from <= ranges[kept - 1].1 { + ranges[kept - 1].1 = ranges[kept - 1].1.max(to); + } else { + ranges[kept] = (from, to); + kept += 1; } } - out + ranges.truncate(kept); + ranges } /// Runs of pieces to hash again (`Host::card_before`), those that overlap @@ -1529,11 +1630,16 @@ struct Workers { } /// Waits awake until `there` says so, `VICTORY_WIDE_SPIN` microseconds at -/// most (0, the default: not at all): asleep, a thread is woken in 50 us and -/// more, 95 times a frame. +/// most (unset: 60 us while `Host::submit` is preparing, 0 otherwise): asleep, +/// a thread is woken in 50 us and more, 95 times a frame. fn spin(there: impl Fn() -> bool) { - static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); - let most = *MOST.get_or_init(|| std::env::var("VICTORY_WIDE_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + static MOST: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let configured = *MOST.get_or_init(|| std::env::var("VICTORY_WIDE_SPIN").ok().and_then(|v| v.trim().parse().ok())); + let most = match configured { + Some(us) => us, + None if crate::host::submitting_active() => 60, + None => 0, + }; if most == 0 { return; } @@ -1649,10 +1755,38 @@ pub(crate) fn wide_run(jobs: Vec<Box<dyn FnOnce() + Send>>) { wide(jobs); } +/// Take the scratch buffer out of the cache while using it. A worker that +/// helps with nested refresh work then gets its own buffer. +fn with_title_buffer<R>(work: impl FnOnce(&mut Vec<u8>) -> R) -> R { + thread_local! { + static TITLE: std::cell::Cell<Vec<u8>> = const { std::cell::Cell::new(Vec::new()) }; + } + TITLE.with(|cache| { + let mut bytes = cache.take(); + let result = work(&mut bytes); + cache.set(bytes); + result + }) +} + +#[test] +fn nested_refreshes_own_separate_scratch_buffers() { + with_title_buffer(|outer| { + outer.clear(); + outer.extend_from_slice(&[1, 2]); + with_title_buffer(|inner| inner.extend_from_slice(&[3, 4])); + assert_eq!(outer, &[1, 2]); + }); +} + /// Calls `work` with every number under `n`, on the kept threads and on /// this one, the next number to whichever is free: for thousands of small /// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue. pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) { + if n < 2 { + (0..n).for_each(work); + return; + } let next = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let work = Arc::new(work); let threads = (wide_threads() + 1).min(n); @@ -1862,10 +1996,32 @@ pub(crate) fn back_line(frames: f64) { #[cfg(test)] mod wide_tests { - use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide}; + use super::{Job, PIECE, WIDE_JOB, copy_all, copy_jobs, find_pieces, wide}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + /// `copy_all` cut into pieces over threads puts every byte where a + /// plain copy would, for sizes on both sides of its line and copies that + /// end in the middle of a piece. + #[test] + fn copy_all_puts_every_byte() { + for sizes in [vec![100usize], vec![300 << 10, 300 << 10], vec![1 << 20, 7, (256 << 10) + 3, 3 << 20]] { + let total: usize = sizes.iter().sum(); + let src: Vec<u8> = (0..total).map(|i| (i * 31 + 7) as u8).collect(); + let mut dst = vec![0u8; total + 64]; + let mut copies = Vec::new(); + let (mut s, mut d) = (0usize, 32usize); + for n in &sizes { + copies.push((src.as_ptr() as usize + s, dst.as_mut_ptr() as usize + d, *n)); + s += n; + d += n; + } + copy_all(copies); + assert_eq!(&dst[32..32 + total], &src[..]); + assert!(dst[..32].iter().all(|&b| b == 0) && dst[32 + total..].iter().all(|&b| b == 0)); + } + } + /// Every job runs once, however many there are, and `wide` returns /// only when all have. #[test] @@ -2138,8 +2294,11 @@ fn is_write_combined(start: u64, len: u64) -> bool { /// Whether what shaders write into copies in the card's memory of /// write-combined title memory stays on the card and is not compared, -/// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by -/// default: an experiment). +/// fetched and merged into title memory. Always, for copies of +/// [`wc_no_back_min`] and more (the switch `VICTORY_WC_NO_BACK` is gone: the +/// launcher had set it in every run since run xd-wcnoback). In the unified +/// memory model (docs/performance/UNIFIED_MEMORY_ARCHITECTURE.md) this is the +/// class "written by the card, never read by the CPU": its home is the card. /// /// The write-back of shader writes (`Shadow::gpu_writes`: hashes after /// sends, compare passes after the lists, fetches of the pieces that differ @@ -2162,20 +2321,17 @@ fn is_write_combined(start: u64, len: u64) -> bool { /// - Another host copy of the same bytes (a texture placed there) does not /// see what shaders wrote through title memory. fn wc_no_back() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WC_NO_BACK").is_some_and(|v| v == "1")) + true } /// The smallest copy whose shader writes [`wc_no_back`] leaves on the card, -/// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 0 unset: all). With every copy -/// left, the 4070 SUPER's cutscenes went near black (run xd-wcnoback, -/// 2026-11-26: small results the title reads back, such as exposure, came -/// back stale) while most of the saving is in a few ranges of hundreds of MB. +/// in bytes: 1 MiB (the launcher's `VICTORY_WC_NO_BACK_MIN_KB=1024`, now the +/// code's; the switch is gone). With every copy left, the 4070 SUPER's +/// cutscenes went near black (run xd-wcnoback, 2026-11-26: small results the +/// title reads back, such as exposure, came back stale) while most of the +/// saving is in a few ranges of hundreds of MB. fn wc_no_back_min() -> u64 { - static MIN: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); - *MIN.get_or_init(|| { - std::env::var("VICTORY_WC_NO_BACK_MIN_KB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) * 1024 - }) + 1 << 20 } /// Bytes shaders were declared to write in write-combined copies and that @@ -2328,7 +2484,7 @@ fn word_runs(at: usize, title: &[u8], held: &[u8]) -> Vec<(usize, usize)> { #[target_feature(enable = "avx2")] unsafe fn word_runs_avx2(title: &[u8], held: &[u8]) -> Vec<(usize, usize)> { use std::arch::x86_64::*; - let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut runs: Vec<(usize, usize)> = Vec::with_capacity(64); let mut push = |from: usize, len: usize| match runs.last_mut() { Some((a, n)) if *a + *n == from => *n += len, _ => runs.push((from, len)), @@ -2373,6 +2529,26 @@ fn under_wide() -> bool { crate::toggled!("VICTORY_UNDER_WIDE") } +thread_local! { + /// Set while this thread merges one copy of several merged at once + /// ([`merge_across`]): its pages are compared here, not spread again. + static ACROSS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` (a [`Shadow::merge_under_writes`] of one of several copies merged +/// on several threads at once) with its pages compared on this thread. +pub(crate) fn merge_across<R>(f: impl FnOnce() -> R) -> R { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + ACROSS.with(|a| a.set(false)); + } + } + ACROSS.with(|a| a.set(true)); + let _reset = Reset; + f() +} + /// What shaders wrote goes into title memory from `at` on: `title` is what /// was read there, `merged` the same with their bytes put in. Only the /// dwords that differ are written. The whole stretch from the first changed @@ -2415,7 +2591,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { } return merged.len(); } - let mut runs = dword_runs(at, title, merged, 0); + let mut runs = word_runs(at, title, merged); if runs.len() > 64 { runs = dword_runs(at, title, merged, 32); PUT[3].fetch_add(1, Ordering::Relaxed); @@ -2681,6 +2857,7 @@ static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::Ato impl Drop for Shadow { fn drop(&mut self) { + crate::demand::drop_shadow(self.id); if self.place.is_some() { // Never counted with the copies (`Shadow::placed`). crate::inplace::gone(self.window, self.len); @@ -2793,12 +2970,8 @@ mod piece_tests { } } -/// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose -/// first page is `base` must take from title memory before it holds the -/// title's bytes: those it never took (`copied` 0), whether or not the -/// title wrote them since tracking began, and those `written` (as -/// `crate::watch::writes` gives it, by page in order) shows written after -/// the copy took them. As [`Shadow::copy_stale`] decides it. +/// Byte intervals within individual pages of `[a, e)` that the copy has +/// never taken, or that the journal shows were written since it took them. /// /// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked /// at `written` alone, so a page of a range shaders may be writing that the @@ -2806,22 +2979,246 @@ mod piece_tests { /// merged nor a reason to settle; the refresh leaves such ranges alone, and /// shaders read zeros there (fxceless/victory-fork#206: missing geometry /// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`). -fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec<usize> { - (a / PAGE..e.div_ceil(PAGE)) - .filter(|&page| page >= base) - .filter(|&page| match copied.get(page - base) { - None => false, - Some(0) => true, - Some(&at) => written - .binary_search_by_key(&page, |&(p, _)| p) - .is_ok_and(|i| written[i].1 > at), - }) - .collect() +/// +/// Use 4 KiB stamps wherever available so a write to one part does not +/// force a read and comparison of the rest of its 64 KiB page. +fn stale_ranges_in( + base: usize, + copied: &[u64], + parts: &crate::watch::PartsTaken, + a: usize, + e: usize, + written: &[(usize, u64)], + each: &dyn Fn(usize) -> Option<[u64; PARTS]>, +) -> Vec<(usize, usize)> { + const CHUNK_PAGES: usize = 16; + let mut stale: Vec<(usize, usize)> = Vec::new(); + let push_whole = |stale: &mut Vec<(usize, usize)>, lo: usize, hi: usize| { + if let Some((prev_lo, prev_hi)) = stale.last_mut() + && *prev_hi == lo + && *prev_lo % PAGE == 0 + && lo % PAGE == 0 + && hi % PAGE == 0 + && hi - *prev_lo <= CHUNK_PAGES * PAGE + { + *prev_hi = hi; + } else { + stale.push((lo, hi)); + } + }; + let first = (a / PAGE).max(base); + let last = e.div_ceil(PAGE).min(base + copied.len()); + let mut writes = written.iter().skip_while(|&&(page, _)| page < first).peekable(); + for page in first..last { + let at = copied[page - base]; + let write = writes.next_if(|&&(p, _)| p == page).map_or(0, |&(_, write)| write); + if at != 0 && write <= at { + continue; + } + let taken = parts.get(&(page - base)); + let lo = a.max(page * PAGE); + let hi = e.min((page + 1) * PAGE); + if at == 0 && taken.is_none() { + push_whole(&mut stale, lo, hi); + continue; + } + let part_writes = (write > at).then(|| each(page)).flatten(); + if taken.is_none() && part_writes.is_none() { + push_whole(&mut stale, lo, hi); + continue; + } + for k in parts_within(page, lo, hi) { + let stamp = at.max(taken.map_or(0, |stamps| stamps[k])); + if stamp != 0 && part_writes.as_ref().map_or(write, |stamps| stamps[k]) <= stamp { + continue; + } + let (from, to) = part_span(page, k, lo, hi); + if from > lo && let Some((_, end)) = stale.last_mut() && *end == from { + *end = to; + } else { + stale.push((from, to)); + } + } + } + stale +} + +/// The parts of a page: 4 KiB each, as the kernel names them. +const PARTS: usize = crate::watch::PARTS; + +/// Since the last line, of refreshes that looked at title memory +/// ([`Shadow::copy_stale`]): how many, how many took something, the bytes of +/// parts never taken before, the bytes of parts taken again (written +/// since), and the ends of ranges that held a page in part. +static REFRESHED: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// For the frame-rate line, every few seconds: what the refreshes took +/// ([`REFRESHED`]) and how the questions to the journal were answered, per +/// second of `seconds`. +pub(crate) fn refreshed_line(seconds: f64) { + let r: Vec<f64> = REFRESHED.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / seconds).collect(); + let [asks, ranges] = [0, 1].map(|i| crate::watch::COVER_ASKS[i].swap(0, Ordering::Relaxed) as f64); + if r[0] == 0.0 { + return; + } + tracing::info!( + "refreshes that looked at title memory, per second: {:.0}, {:.0} of them took something; {:.1} MB never taken before, \ + {:.1} MB taken again (written since; 4 KiB parts where the kernel names them, else 64 KiB pages); {:.0} ends of ranges \ + in the middle of a page (their parts are noted one by one); questions answered from the submissions' askings {:.0}, \ + {:.1} ranges asked on average (looked for by halves)", + r[0], + r[1], + r[2] / 1e6, + r[3] / 1e6, + r[4], + asks / seconds, + ranges / asks.max(1.0), + ); +} + +/// The parts of page `page` (a page number) that hold bytes of `[a, b)`. +fn parts_within(page: usize, a: usize, b: usize) -> std::ops::Range<usize> { + let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(b)); + if lo >= hi { + return 0..0; + } + (lo - page * PAGE) / KERNEL_PAGE..(hi - page * PAGE).div_ceil(KERNEL_PAGE) +} + +/// Part `k` of page `page`, cut to `[start, end)` (the buffer). +fn part_span(page: usize, k: usize, start: usize, end: usize) -> (usize, usize) { + ((page * PAGE + k * KERNEL_PAGE).max(start), (page * PAGE + (k + 1) * KERNEL_PAGE).min(end)) +} + +/// What a refresh of `[from, to)` takes ([`Shadow::copy_stale`]): runs +/// (from, to, whether the copy held them before), in order. The range lies +/// in the buffer `[start, end)`, whose first page is `base`. A 4 KiB part is +/// taken if it was never taken whole, or was written after it last was: its +/// note is the latest of its page's (`copied`), its own (`parts`) and that of +/// a range taken whole that holds `[from, to)` (`ranged`, or 0); its writes +/// are its page's in `written` (pages in order and their last write, as +/// `crate::watch::writes` gives them) or, where the journal tells a page's +/// parts apart, those in `each` (by page of `written`). +/// +/// As before parts were noted: a page never taken is taken whole, a page +/// taken and written since in the parts written (all of it where they are +/// not known, `by_parts`). +#[allow(clippy::too_many_arguments)] +fn stale_runs( + from: usize, + to: usize, + (_, _, base): (usize, usize, usize), + copied: &[u64], + parts: &crate::watch::PartsTaken, + ranged: u64, + written: &[(usize, u64)], + each: &[Option<[u64; PARTS]>], +) -> Vec<(usize, usize, bool)> { + let mut runs: Vec<(usize, usize, bool)> = Vec::new(); + let mut push = |a: usize, b: usize, known: bool| { + if a >= b { + return; + } + match runs.last_mut() { + Some(last) if last.1 == a && last.2 == known => last.1 = b, + _ => runs.push((a, b, known)), + } + }; + if from >= to { + return runs; + } + let mut writes = written.iter().zip(each.iter().map(Some).chain(std::iter::repeat(None))).peekable(); + let mut stamps_of = parts.range((from / PAGE).saturating_sub(base)..).peekable(); + for page in from / PAGE..=(to - 1) / PAGE { + while writes.next_if(|((p, _), _)| *p < page).is_some() {} + let (write, each) = match writes.next_if(|((p, _), _)| *p == page) { + Some((&(_, w), e)) => (w, e.copied().flatten()), + None => (0, None), + }; + let i = page - base; + while stamps_of.next_if(|s| *s.0 < i).is_some() {} + let stamps = stamps_of.next_if(|s| *s.0 == i).map(|s| s.1); + let taken = copied[i].max(ranged); + let (lo, hi) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); + match stamps { + None if taken != 0 && write <= taken => {} + None if taken == 0 => push(lo, hi, false), + _ => { + for k in parts_within(page, lo, hi) { + let (a, b) = part_span(page, k, lo, hi); + let at = taken.max(stamps.map_or(0, |s| s[k])); + let w = if write == 0 { 0 } else { each.map_or(write, |e| e[k]) }; + if at == 0 || w > at { + push(a, b, at != 0); + } + } + } + } + } + runs +} + +/// `[from, to)` (inside the buffer `[start, end)`, whose first page is +/// `base`) is in the copy as title memory had it at asking `now`: each page +/// it holds whole is noted so in `copied`, and of each page it holds in part, +/// each 4 KiB part it holds whole in `parts`. A page all of whose parts are +/// noted later than the page is noted at the earliest of them, and its parts' +/// notes go once none is later than the page's. +fn stamp_taken( + from: usize, + to: usize, + (start, end, base): (usize, usize, usize), + copied: &mut [u64], + parts: &mut crate::watch::PartsTaken, + now: u64, +) { + if from >= to { + return; + } + for page in from / PAGE..=(to - 1) / PAGE { + let i = page - base; + let Some(at) = copied.get_mut(i) else { + continue; + }; + if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { + *at = (*at).max(now); + } else { + let mut stamped = false; + let mut stamps = parts.get(&i).copied().unwrap_or([0; PARTS]); + for k in 0..PARTS { + let (a, b) = part_span(page, k, start, end); + if a < b && a >= from && b <= to { + stamps[k] = stamps[k].max(now); + stamped = true; + } + } + if stamped { + parts.insert(i, stamps); + } + } + let Some(stamps) = parts.get(&i) else { + continue; + }; + let held = (0..PARTS) + .filter(|&k| { + let (a, b) = part_span(page, k, start, end); + a < b + }) + .map(|k| stamps[k].max(*at)) + .min() + .unwrap_or(*at); + *at = (*at).max(held); + if stamps.iter().all(|&t| t <= *at) { + parts.remove(&i); + } + } } /// `runs` (from, to, whether the copy held it before), cut in those of pages /// held before (`pages`: page number and asking, in order) to the parts of -/// each page that were written since (`parts`: a bit for each 4 KiB). +/// each page that were written since (`parts`: a bit for each 4 KiB). (What +/// [`stale_runs`] does now, kept for its test as the way it was.) +#[cfg(test)] fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u16]) -> Vec<(usize, usize, bool)> { const PART: usize = PAGE / 16; if parts.iter().all(|&p| p == u16::MAX) { @@ -2926,6 +3323,44 @@ mod parts_tests { mod stale_tests { use super::*; + #[test] + fn an_asking_for_another_page_does_not_validate_a_clean_memo() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + if !crate::watch::once() { + return; + } + // SAFETY: a private write-watched reservation for this test. + let at = unsafe { + VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(at, 0); + let mut data = vec![0u8; PAGE]; + let copy = Shadow::unbacked(at as u64, data.as_mut_ptr(), PAGE as u64, false); + crate::watch::ask_once(&[(at, at + PAGE)]); + assert!((0..100).any(|_| { + crate::watch::ask_once(&[(at, at + PAGE)]); + if !crate::watch::kept_covers(at, at + PAGE) { + return false; + } + // The zeroed host copy already matches the untouched title page. + copy.watched.store(1, Ordering::Relaxed); + let (sig, asking) = crate::watch::block_write_sig(at, at + PAGE).unwrap(); + copy.stamp_clean(at, at + PAGE, sig, asking); + copy.fast_nothing_new(at, PAGE) + })); + crate::watch::ask_once_end(); + + // SAFETY: a committed page in the reservation of this test. + unsafe { (at as *mut u8).write_volatile(2) }; + crate::watch::ask_once(&[(at + PAGE, at + 2 * PAGE)]); + assert!(!copy.fast_nothing_new(at, PAGE)); + assert!(copy.update(at, PAGE) > 0); + crate::watch::ask_once_end(); + assert_eq!(data[0], 2); + } + #[test] fn pages_never_taken_are_stale_written_or_not() { let base = 0x100; @@ -2934,10 +3369,186 @@ mod stale_tests { // Page 0x101 was never taken; page 0x102 was written after it was // taken, page 0x103 before. let written = [(0x102, 6), (0x103, 4)]; - assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]); - // Part of a page counts as the page; pages outside the copy do not. - assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]); - assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty()); + let none = crate::watch::PartsTaken::new(); + let whole = |_: usize| None; + assert_eq!( + stale_ranges_in(base, &copied, &none, at(0x100), at(0x104), &written, &whole), + [(at(0x101), at(0x103))] + ); + // Adjacent whole stale pages coalesce into chunks of at most 16 pages (1 MiB). + let many_copied = vec![0u64; 20]; + assert_eq!( + stale_ranges_in(base, &many_copied, &none, at(0x100), at(0x100 + 20), &[], &whole), + [(at(0x100), at(0x100 + 16)), (at(0x100 + 16), at(0x100 + 20))] + ); + // Clip to the requested bytes and ignore pages outside the copy. + assert_eq!( + stale_ranges_in(base, &copied, &none, at(0x101) + 8, at(0x101) + 16, &[], &whole), + [(at(0x101) + 8, at(0x101) + 16)] + ); + assert!(stale_ranges_in(base, &copied, &none, at(0x104), at(0x106), &[(0x104, 9)], &whole).is_empty()); + // Page 0x101 never taken whole, its part 0 taken at 7: what lies in + // part 0 is as it was, what lies in part 1 never was taken. + let mut parts = crate::watch::PartsTaken::new(); + let mut stamps = [0; PARTS]; + stamps[0] = 7; + parts.insert(1, stamps); + assert!(stale_ranges_in(base, &copied, &parts, at(0x101) + 8, at(0x101) + 16, &[], &whole).is_empty()); + assert_eq!( + stale_ranges_in(base, &copied, &parts, at(0x101) + 8, at(0x101) + 5000, &[], &whole), + [(at(0x101) + KERNEL_PAGE, at(0x101) + 5000)] + ); + // Adjacent dirty parts merge, while the clean gap stays untouched. + parts.insert(2, stamps); + let each = |_: usize| { + let mut w = [0; PARTS]; + w[0] = 6; + w[3] = 6; + w[4] = 6; + w[6] = 6; + Some(w) + }; + assert!(stale_ranges_in(base, &copied, &parts, at(0x102), at(0x102) + 100, &written, &each).is_empty()); + let page = at(0x102); + assert_eq!( + stale_ranges_in(base, &copied, &parts, page, page + 6 * KERNEL_PAGE + 8, &written, &each), + [(page + 3 * KERNEL_PAGE, page + 5 * KERNEL_PAGE), (page + 6 * KERNEL_PAGE, page + 6 * KERNEL_PAGE + 8)] + ); + } + + #[test] + fn clean_cache_holds_four_disjoint_ranges_and_card_has_before_tracks_twin() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + if !crate::watch::once() { + return; + } + let total = 8 * PAGE; + // SAFETY: private write-watched reservation freed at the end of the test. + let at = unsafe { + VirtualAlloc(std::ptr::null(), total, MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(at, 0); + let mut data = vec![0u8; total]; + let copy = Shadow::unbacked(at as u64, data.as_mut_ptr(), total as u64, true); + assert!(!copy.card_has_before()); + copy.watched.store(1, Ordering::Relaxed); + let ranges: [(usize, usize); 4] = [ + (at, at + PAGE), + (at + 2 * PAGE, at + 3 * PAGE), + (at + 4 * PAGE, at + 5 * PAGE), + (at + 6 * PAGE, at + 7 * PAGE), + ]; + crate::watch::ask_once(&ranges); + if crate::watch::kept() { + for &(from, to) in &ranges { + let (sig, asking) = crate::watch::block_write_sig(from, to).unwrap(); + copy.stamp_clean(from, to, sig, asking); + } + for &(from, to) in &ranges { + assert!(copy.fast_nothing_new(from, to - from), "disjoint slot {from:#x}..{to:#x} was evicted"); + } + } + crate::watch::ask_once_end(); + // SAFETY: test allocation. + unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; + } + + #[test] + fn non_overlapping_register_does_not_bump_buffers_changed() { + let base = 0x7e00_0000_0000u64; + register(0x1001, base, 0x1_0000); + let gen0 = BUFFERS_CHANGED.load(Ordering::Acquire); + register(0x1002, base + 0x2_0000, 0x1_0000); + assert_eq!(BUFFERS_CHANGED.load(Ordering::Acquire), gen0); + // Overlapping registration must bump. + register(0x1003, base + 0x8000, 0x1000); + let gen1 = BUFFERS_CHANGED.load(Ordering::Acquire); + assert!(gen1 > gen0); + unregister(0x1003, base + 0x8000); + assert!(BUFFERS_CHANGED.load(Ordering::Acquire) > gen1); + unregister(0x1002, base + 0x2_0000); + unregister(0x1001, base); + } +} + +#[cfg(test)] +mod part_notes_tests { + use super::*; + + const K: usize = KERNEL_PAGE; + + /// Without notes of parts the runs are those of the pages, cut to the + /// parts written, as `by_parts` cut them. + #[test] + fn runs_without_notes_of_parts_are_as_before() { + let base = 10; + let (start, end) = (base * PAGE, 15 * PAGE); + let copied = [5, 5, 0, 0, 6]; + let none = crate::watch::PartsTaken::new(); + let written = [(10, 6), (11, 6), (14, 6)]; + let mut p10 = [0; PARTS]; + p10[1] = 6; + p10[15] = 6; + let each = [Some(p10), None, Some([6; PARTS])]; + let (from, to) = (10 * PAGE + K + 100, 14 * PAGE + 9 * K + 7); + let runs = stale_runs(from, to, (start, end, base), &copied, &none, 0, &written, &each); + let before = by_parts( + vec![(from, 12 * PAGE, true), (12 * PAGE, 14 * PAGE, false)], + &[(10, 5), (11, 5)], + &[1 << 1 | 1 << 15, u16::MAX], + ); + assert_eq!(runs, before); + // Page 14, taken at 6 and written at 6: as it was. + assert!(stale_runs(14 * PAGE, 15 * PAGE, (start, end, base), &copied, &none, 0, &written, &each).is_empty()); + // A range taken whole later than the writes: nothing. + assert!(stale_runs(from, to - 8 * K, (start, end, base), &copied, &none, 9, &written, &each).is_empty()); + } + + /// A page taken in part is taken again only where it was written since, + /// or never taken; and once all of it is taken it is noted whole. + #[test] + fn a_page_taken_in_part_is_not_taken_again_unwritten() { + let base = 0; + let (start, end) = (0, 2 * PAGE); + let mut copied = [0u64, 0]; + let mut parts = crate::watch::PartsTaken::new(); + // Page 0 written whole at 3; taken from part 2 on to the middle of + // page 1 (beside a range shaders write). + let written = [(0, 3), (1, 3)]; + let each = [None, None]; + let (from, to) = (2 * K + 10, PAGE + 5 * K + 1); + let runs = stale_runs(from, to, (start, end, base), &copied, &parts, 0, &written, &each); + assert_eq!(runs, [(from, to, false)]); + stamp_taken(from, to, (start, end, base), &mut copied, &mut parts, 4); + assert_eq!(copied, [0, 0]); + // Part 2 begins before `from`; parts 3..16 of page 0, 0..5 of page 1. + assert_eq!(parts[&0][2], 0); + assert_eq!(parts[&0][3], 4); + assert_eq!(parts[&1][4], 4); + assert_eq!(parts[&1][5], 0); + // Nothing written since: taken again, only what never was. + let runs = stale_runs(2 * K, PAGE + 5 * K, (start, end, base), &copied, &parts, 0, &written, &each); + assert_eq!(runs, [(2 * K, 3 * K, false)]); + // Part 7 of page 0 written at 5 (the journal tells it apart). + let mut p0 = [3; PARTS]; + p0[7] = 5; + let written = [(0, 5), (1, 3)]; + let each = [Some(p0), None]; + let runs = stale_runs(3 * K, PAGE + 5 * K, (start, end, base), &copied, &parts, 0, &written, &each); + assert_eq!(runs, [(7 * K, 8 * K, true)]); + // Taken whole at last: noted as a page, the parts' notes gone. + stamp_taken(0, PAGE, (start, end, base), &mut copied, &mut parts, 6); + assert_eq!(copied[0], 6); + assert!(!parts.contains_key(&0)); + // Page 1's parts all taken one by one: noted whole at the earliest. + stamp_taken(PAGE, PAGE + 4 * K, (start, end, base), &mut copied, &mut parts, 7); + stamp_taken(PAGE + 5 * K, 2 * PAGE, (start, end, base), &mut copied, &mut parts, 8); + // (Part 4 was taken at 4, above.) + assert_eq!(copied[1], 4); + stamp_taken(PAGE + 4 * K, PAGE + 5 * K, (start, end, base), &mut copied, &mut parts, 9); + assert_eq!(copied[1], 7); } } @@ -3153,6 +3764,9 @@ impl Shadow { /// Brings `len` bytes at `address` up to date when `list` is submitted, /// and keeps the copy alive until the list is reset. pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { + if self.place.is_some() { + return; + } let len = len.min(self.start + self.len - address); list.defer_refresh(self, address as usize, len as usize); } @@ -3178,8 +3792,12 @@ impl Shadow { len, copied: Mutex::new(vec![0; pages as usize]), ranged: Mutex::default(), + parts_taken: Mutex::default(), watched: AtomicU8::new(0), pending: Mutex::default(), + pending_len: std::sync::atomic::AtomicU32::new(0), + clean: std::array::from_fn(|_| CleanSlot::new()), + clean_next: AtomicU32::new(0), flights: Mutex::default(), before: Mutex::default(), merging: RwLock::default(), @@ -3292,6 +3910,8 @@ impl Shadow { // lists). if self.card.is_some() { pending.push(range); + self.pending_len.store(pending.len() as u32, Ordering::Release); + self.invalidate_clean(); return; } // The parts no declared range holds yet: their bytes are taken now, @@ -3316,6 +3936,8 @@ impl Shadow { parts = rest; } pending.push(range); + self.pending_len.store(pending.len() as u32, Ordering::Release); + self.invalidate_clean(); let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); let total = self.len as usize; @@ -3605,6 +4227,7 @@ impl Shadow { } else { pending.retain(|r| !ranges.contains(r)); } + self.pending_len.store(pending.len() as u32, Ordering::Release); if !pending.is_empty() || self.card.is_some() { return; } @@ -3647,6 +4270,9 @@ impl Shadow { /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is /// not current there any more. fn changed(&self, from: usize, to: usize) { + if from < to { + self.invalidate_clean(); + } if !keeps() || from >= to { return; } @@ -3662,12 +4288,15 @@ impl Shadow { /// Whether shaders of a submission not yet copied back may be writing /// the copy. pub(crate) fn writes_pending(&self) -> bool { - !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + self.pending_len.load(Ordering::Acquire) != 0 } /// Whether one of those submissions may be writing in title memory /// `[from, to)`. pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool { + if self.pending_len.load(Ordering::Acquire) == 0 { + return false; + } self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) } @@ -3683,6 +4312,9 @@ impl Shadow { /// (`crate::host::late`): the ranges are those of flights in the air, /// which are then settled before this refresh. pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool { + if self.pending_len.load(Ordering::Acquire) == 0 { + return false; + } 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 { @@ -3705,7 +4337,10 @@ impl Shadow { let base = start / PAGE; let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { - Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), + Some((_, written)) => { + let parts = self.parts_taken.lock().unwrap_or_else(|e| e.into_inner()); + !stale_ranges_in(base, &copied, &parts, a, e, &written, &crate::watch::part_write).is_empty() + } None => true, }) } @@ -3764,13 +4399,17 @@ impl Shadow { note_stale(1); return true; }; - let stale: Vec<usize> = { + let stale = { let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - stale_pages_in(base, &copied, a, e, &written) + let parts = self.parts_taken.lock().unwrap_or_else(|e| e.into_inner()); + stale_ranges_in(base, &copied, &parts, a, e, &written, &crate::watch::part_write) }; if stale.is_empty() { continue; } + let pin_from = stale[0].0 / PAGE * PAGE; + let pin_to = stale[stale.len() - 1].1.next_multiple_of(PAGE); + let _demand_pin = crate::demand::pin_range(pin_from, pin_to.saturating_sub(pin_from)); // The lock of the copy's reference (the snapshot, or the // CPU's side of a copy in the card's memory), from before // title memory is read until the title's bytes are in: with @@ -3790,60 +4429,73 @@ impl Shadow { note_stale(3); return true; } - // A page's part in the range, compared and put in: the runs it - // changed; none for a page that is not there (left as it is, and - // looked at again next time) or that had too many. - type Done = Option<Vec<(usize, usize)>>; + // A chunk's part in the range, compared and put in: the runs it + // changed (`(offset_in_shadow, len)`) and sub-ranges read; none + // if unreadable or `runs_left` ran out. + struct Slot<T>(std::cell::UnsafeCell<T>); + // SAFETY: each index `i` in `0..stale.len()` is written exclusively by + // the single worker assigned `i`, and all workers finish before `done` + // is consumed. + unsafe impl<T: Send> Sync for Slot<T> {} let left = std::sync::atomic::AtomicI64::new(*runs_left as i64); let over = std::sync::atomic::AtomicBool::new(false); - let done: Vec<Mutex<Done>> = stale.iter().map(|_| Mutex::new(None)).collect(); - let page_of = |i: usize| -> (usize, usize) { ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)) }; + let done: Vec<Slot<Option<(Vec<(usize, usize)>, Vec<(usize, usize)>)>>> = + (0..stale.len()).map(|_| Slot(std::cell::UnsafeCell::new(None))).collect(); let one = |i: usize| { - let (lo, hi) = page_of(i); - if lo < hi && !over.load(Ordering::Relaxed) { + let (lo, hi) = stale[i]; + if !over.load(Ordering::Relaxed) { // SAFETY: the reference holds the copy's bytes at the // copy's offsets, and these are in a declared range; the // locks held above keep out what else writes them, and - // no two pages are the same. - let runs = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) }; - match runs { - Ok(runs) => *done[i].lock().unwrap_or_else(|e| e.into_inner()) = runs, + // the intervals are disjoint. + let chunk = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) }; + match chunk { + Ok(chunk) => { + // SAFETY: index `i` is unique to this invocation. + unsafe { *done[i].0.get() = chunk }; + } Err(()) => over.store(true, Ordering::Relaxed), } } }; // (Not on the threads of `wide`: the thread that waits there // takes whatever work comes, and a landing's takes the lock.) - if stale.len() > 2 && under_wide() { + if stale.len() >= 2 && under_wide() && !ACROSS.with(std::cell::Cell::get) { crate::land::each_under(stale.len(), &one); } else { (0..stale.len()).for_each(one); } *runs_left = left.into_inner().max(0) as usize; let mut taken = Vec::new(); - for (i, runs) in done.into_iter().enumerate() { - let Some(runs) = runs.into_inner().unwrap_or_else(|e| e.into_inner()) else { + let mut changed = Vec::new(); + let mut changed_runs = 0; + let mut changed_bytes = 0; + for slot in done { + let Some((runs, sub_taken)) = slot.0.into_inner() else { continue; }; - let (lo, hi) = ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)); - MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed); - MERGED[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); - self.card_changed_runs(runs.into_iter().map(|(r, m)| (lo - start + r, lo - start + r + m))); - // Taken, if the range holds all of the page that is in the - // copy; else the rest of it is the refresh's, which notes - // only whole pages, and the page is looked at again. - if lo < hi && (stale[i] * PAGE).max(start) >= a && ((stale[i] + 1) * PAGE).min(end) <= e { - taken.push(stale[i]); + changed_runs += runs.len() as u64; + changed_bytes += runs.iter().map(|r| r.1 as u64).sum::<u64>(); + changed.extend(runs.into_iter().map(|(at, m)| (at, at + m))); + taken.extend(sub_taken); + } + if changed_runs != 0 { + MERGED[1].fetch_add(changed_runs, Ordering::Relaxed); + MERGED[2].fetch_add(changed_bytes, Ordering::Relaxed); + if self.card.is_some() { + self.card_changed_runs(changed.iter().copied()); } } drop(before); drop(merging); + if !changed.is_empty() { + crate::copystat_footprint::pending_wrote(self.id, self.start, self.len, &changed); + } { let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - for page in taken { - if let Some(at) = copied.get_mut(page - base) { - *at = now; - } + let mut parts = self.parts_taken.lock().unwrap_or_else(|e| e.into_inner()); + for (lo, hi) in taken { + stamp_taken(lo, hi, (start, end, base), &mut copied, &mut parts, now); } } if over.into_inner() { @@ -3854,10 +4506,56 @@ impl Shadow { false } - /// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)`, in one - /// page, compared with the reference, which begins at `held`, and put in. - /// The runs that changed, none if it cannot be read, and an error if - /// there were more to copy one by one than `left`. + /// Compares already-read `title` bytes at `[lo, lo + title.len())` against + /// `held`, updates `held` (and `self.data` for PC-memory copies), and + /// returns changed runs as `(offset_in_shadow, len)`. + /// + /// # Safety + /// Same as [`Shadow::merge_page_under_writes`]. + unsafe fn merge_slice_under_writes( + &self, + lo: usize, + title: &[u8], + held: *mut u8, + left: &std::sync::atomic::AtomicI64, + ) -> Result<Vec<(usize, usize)>, ()> { + let n = title.len(); + MERGED[0].fetch_add(n.div_ceil(PAGE) as u64, Ordering::Relaxed); + let at = lo - self.start as usize; + // SAFETY: the caller's. + let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) }; + if self.card.is_some() { + // Whole words go up as pairs, all of them in one + // dispatch: only what is a copy of its own counts. + let runs = if crate::host::words_under() { word_runs(lo, title, held) } else { changed_runs(title, held) }; + let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m); + let copies = runs.iter().filter(own).count() as i64; + if copies > 0 && left.fetch_sub(copies, Ordering::Relaxed) < copies { + return Err(()); + } + let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec()); + for &(r, m) in &runs { + held[r..r + m].copy_from_slice(&title[r..r + m]); + } + if let Some(was) = was { + crate::host::upcheck::note(self.id, at, &was, held); + } + return Ok(runs.into_iter().map(|(r, m)| (at + r, m)).collect()); + } + let runs = changed_runs(title, held); + for &(r, m) in &runs { + // SAFETY: inside the copy's mapping. The card may be + // writing the copy beside these bytes; they are + // written here and nothing around them. + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + held[r..r + m].copy_from_slice(&title[r..r + m]); + } + Ok(runs.into_iter().map(|(r, m)| (at + r, m)).collect()) + } + + /// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)` (a page, + /// part of a page, or a coalesced chunk of whole pages), compared with the + /// reference starting at `held`, and put in. /// /// # Safety /// The reference holds the copy's length, and nothing else writes these @@ -3868,47 +4566,34 @@ impl Shadow { n: usize, held: *mut u8, left: &std::sync::atomic::AtomicI64, - ) -> Result<Option<Vec<(usize, usize)>>, ()> { - thread_local! { - static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; - } - TITLE.with_borrow_mut(|title| { - title.resize(PAGE, 0); - let title = &mut title[..n]; - if !crate::host::read_into(lo as *const u8, title) { + ) -> Result<Option<(Vec<(usize, usize)>, Vec<(usize, usize)>)>, ()> { + with_title_buffer(|title| { + if title.len() < n.max(PAGE) { + title.resize(n.max(PAGE), 0); + } + if crate::host::read_into(lo as *const u8, &mut title[..n]) { + // SAFETY: caller's invariants cover `[lo, lo + n)`. + let runs = unsafe { self.merge_slice_under_writes(lo, &title[..n], held, left) }?; + return Ok(Some((runs, vec![(lo, lo + n)]))); + } + if n <= PAGE { return Ok(None); } - MERGED[0].fetch_add(1, Ordering::Relaxed); - let at = lo - self.start as usize; - // SAFETY: the caller's. - let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) }; - if self.card.is_some() { - // Whole words go up as pairs, all of them in one - // dispatch: only what is a copy of its own counts. - let runs = if crate::host::words_under() { word_runs(lo, title, held) } else { changed_runs(title, held) }; - let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m); - let copies = runs.iter().filter(own).count() as i64; - if copies > 0 && left.fetch_sub(copies, Ordering::Relaxed) < copies { - return Err(()); - } - let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec()); - for &(r, m) in &runs { - held[r..r + m].copy_from_slice(&title[r..r + m]); - } - if let Some(was) = was { - crate::host::upcheck::note(self.id, at, &was, held); + let mut all_runs = Vec::new(); + let mut taken = Vec::new(); + let mut sub_lo = lo; + let hi = lo + n; + while sub_lo < hi { + let sub_n = (PAGE - sub_lo % PAGE).min(hi - sub_lo); + if crate::host::read_into(sub_lo as *const u8, &mut title[..sub_n]) { + // SAFETY: caller's invariants cover `[sub_lo, sub_lo + sub_n)`. + let runs = unsafe { self.merge_slice_under_writes(sub_lo, &title[..sub_n], held, left) }?; + all_runs.extend(runs); + taken.push((sub_lo, sub_lo + sub_n)); } - return Ok(Some(runs)); - } - let runs = changed_runs(title, held); - for &(r, m) in &runs { - // SAFETY: inside the copy's mapping. The card may be - // writing the copy beside these bytes; they are - // written here and nothing around them. - unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; - held[r..r + m].copy_from_slice(&title[r..r + m]); + sub_lo += sub_n; } - Ok(Some(runs)) + Ok((!taken.is_empty()).then_some((all_runs, taken))) }) } @@ -3925,38 +4610,212 @@ impl Shadow { if from >= to { return 0; } - let mut busy: Vec<(usize, usize)> = self - .pending - .lock() - .unwrap_or_else(|e| e.into_inner()) - .iter() - .copied() - .filter(|&(a, e)| a < to && e > from) - .collect(); - if !busy.is_empty() { - // Around ranges shaders are writing: the gaps, each as below - // (in the world most submissions have such ranges; copying the - // gaps whole cost ~1 s per frame). - busy.sort_unstable(); - let (mut at, mut bytes) = (from, 0); - for (a, e) in busy { - if a > at { - bytes += self.update_free(at, a); + if self.pending_len.load(Ordering::Acquire) != 0 { + let mut busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .copied() + .filter(|&(a, e)| a < to && e > from) + .collect(); + if !busy.is_empty() { + // Around ranges shaders are writing: the gaps, each as below + // (in the world most submissions have such ranges; copying the + // gaps whole cost ~1 s per frame). + busy.sort_unstable(); + let (mut at, mut bytes) = (from, 0); + for (a, e) in busy { + if a > at { + bytes += self.update_free(at, a); + } + at = at.max(e); } - at = at.max(e); - } - if at < to { - bytes += self.update_free(at, to); + if at < to { + bytes += self.update_free(at, to); + } + return bytes; } - return bytes; } self.update_free(from, to) } + fn was_copied_before(&self, address: usize, len: usize) -> bool { + if self.place.is_some() { + return true; + } + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), address.saturating_add(len).min(end)); + if from >= to { + return false; + } + let cf = self.clean_from(from, to); + if cf { + return true; + } + let base = start / PAGE; + let (first, last) = (from / PAGE - base, to.div_ceil(PAGE) - base); + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + copied.get(first..last).is_some_and(|slice| slice.iter().all(|&at| at != 0)) + } + + /// Checks the memo before looking up the copy's per-page stamps. + /// The range needs a current guard or write-watch answer as well. + pub(crate) fn fast_nothing_new(&self, address: usize, len: usize) -> bool { + self.fast_nothing_new_known(address, len, &crate::watch::kept_covers) + } + + /// [`Shadow::fast_nothing_new`] with the submission's one asking's cover + /// given (`kept`: [`crate::watch::kept_covers`], or a submission's copy of + /// that asking, [`crate::watch::kept_covers_cached`]). Asks nothing under + /// a lock but what `kept` does. + pub(crate) fn fast_nothing_new_known(&self, address: usize, len: usize, mut kept: impl FnMut(usize, usize) -> bool) -> bool { + if self.place.is_some() { + return true; + } + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), address.saturating_add(len).min(end)); + if from >= to { + return true; + } + let watched = self.watched.load(Ordering::Relaxed); + if !matches!(watched, 1 | GUARDED) || self.pending_len.load(Ordering::Acquire) != 0 { + return false; + } + let mut known_cache = None; + for slot in &self.clean { + let revision = slot.revision.load(Ordering::Acquire); + let cs = slot.sig.load(Ordering::Acquire); + if revision % 2 != 0 || cs == 0 { + continue; + } + let cf = slot.from.load(Ordering::Relaxed) as usize; + let ct = slot.to.load(Ordering::Relaxed) as usize; + if from < cf || to > ct { + continue; + } + let known = *known_cache.get_or_insert_with(|| { + (watched == GUARDED && crate::watch::published(from, to)) || kept(from, to) + }); + if !known { + return false; + } + if crate::watch::block_write_sig(cf, ct).is_some_and(|(sig, _)| sig == cs) + && slot.sig.load(Ordering::Acquire) == cs + && slot.revision.load(Ordering::Acquire) == revision + { + return true; + } + } + false + } + + fn clean_from(&self, from: usize, to: usize) -> bool { + for slot in &self.clean { + let revision = slot.revision.load(Ordering::Acquire); + let cs = slot.sig.load(Ordering::Acquire); + if revision % 2 != 0 || cs == 0 { + continue; + } + let cf = slot.from.load(Ordering::Relaxed) as usize; + let ct = slot.to.load(Ordering::Relaxed) as usize; + if cf <= from && to <= ct && slot.revision.load(Ordering::Acquire) == revision { + return true; + } + } + false + } + + fn invalidate_clean(&self) { + for slot in &self.clean { + slot.clear(); + } + } + + fn stamp_clean(&self, from: usize, to: usize, sig: u64, ask_end: u64) { + let mut target = None; + let mut empty = None; + for (i, slot) in self.clean.iter().enumerate() { + let revision = slot.revision.load(Ordering::Acquire); + let prev_sig = slot.sig.load(Ordering::Acquire); + if revision % 2 != 0 || prev_sig == 0 { + if empty.is_none() && prev_sig == 0 { + empty = Some(i); + } + continue; + } + let cf = slot.from.load(Ordering::Relaxed) as usize; + let ct = slot.to.load(Ordering::Relaxed) as usize; + if slot.revision.load(Ordering::Acquire) != revision { + continue; + } + if cf <= from && to <= ct && crate::watch::block_write_sig(cf, ct) == Some((prev_sig, slot.ask_end.load(Ordering::Relaxed))) { + return; + } + if from <= ct && to >= cf { + target = Some(i); + break; + } + } + let idx = target + .or(empty) + .unwrap_or_else(|| self.clean_next.fetch_add(1, Ordering::Relaxed) as usize % CLEAN_SLOTS); + let slot = &self.clean[idx]; + let revision = slot.revision.load(Ordering::Relaxed); + if revision % 2 != 0 + || slot.revision.compare_exchange(revision, revision + 1, Ordering::AcqRel, Ordering::Relaxed).is_err() + { + return; + } + let prev_sig = slot.sig.load(Ordering::Relaxed); + slot.sig.store(0, Ordering::Release); + let (mut new_from, mut new_to, mut new_sig, mut new_ask_end) = (from, to, sig, ask_end); + if prev_sig != 0 { + let cf = slot.from.load(Ordering::Relaxed) as usize; + let ct = slot.to.load(Ordering::Relaxed) as usize; + let ca = slot.ask_end.load(Ordering::Relaxed); + // Merge contiguous/overlapping clean spans only when the previous + // span is still verified clean with the same write state. + if from <= ct + && to >= cf + && (cf < from || ct > to) + && crate::watch::block_write_sig(cf, ct) == Some((prev_sig, ca)) + { + let u_from = cf.min(from); + let u_to = ct.max(to); + if let Some((u_sig, u_ask)) = crate::watch::block_write_sig(u_from, u_to) + // Neither span can have changed while we sampled the union. + && crate::watch::block_write_sig(from, to) == Some((sig, ask_end)) + && crate::watch::block_write_sig(cf, ct) == Some((prev_sig, ca)) + { + (new_from, new_to, new_sig, new_ask_end) = (u_from, u_to, u_sig, u_ask); + } + } + } + slot.from.store(new_from as u64, Ordering::Release); + slot.to.store(new_to as u64, Ordering::Release); + slot.ask_end.store(new_ask_end, Ordering::Release); + slot.sig.store(new_sig, Ordering::Release); + slot.revision.store(revision + 2, Ordering::Release); + } + /// Whether [`Shadow::update`] of `[address, address + len)` would copy /// nothing, and knows it without asking anything /// (`crate::watch::nothing_new`). `false` if it would have to ask. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + if self.fast_nothing_new(address, len) { + #[cfg(feature = "diagnostics")] + { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), address.saturating_add(len).min(end)); + if from < to { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from) as u64); + } + } + return true; + } if self.place.is_some() { return true; } @@ -3969,11 +4828,19 @@ impl Shadow { return false; } // Around ranges shaders are writing the refresh asks gap by gap. - if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { + let pending = self.pending_len.load(Ordering::Acquire) != 0; + if pending && self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { return false; } let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to)); + let ranged = self.ranged(from, to); + let parts = self.parts_taken.lock().unwrap_or_else(|e| e.into_inner()); + let clean_before = (!pending).then(|| crate::watch::block_write_sig(from, to)).flatten(); + let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, &parts, ranged); + drop((copied, parts)); + if same && let Some((sig, ask_end)) = clean_before { + self.stamp_clean(from, to, sig, ask_end); + } #[cfg(feature = "diagnostics")] if same { use crate::copystat::{C, add}; @@ -3994,11 +4861,17 @@ impl Shadow { /// shader writes. fn update_free(&self, from: usize, to: usize) -> usize { if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { + let clean_before = (self.pending_len.load(Ordering::Acquire) == 0) + .then(|| crate::watch::block_write_sig(from, to)) + .flatten(); if let Some((now, written)) = crate::watch::writes(from, to, true) { // (A range whose blocks rest after a write has no guard now.) let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED; self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); + if let Some((sig, ask_end)) = clean_before { + self.stamp_clean(from, to, sig, ask_end); + } self.refresh_check(from, to); #[cfg(feature = "diagnostics")] { @@ -4077,61 +4950,36 @@ impl Shadow { } } - /// Copies the pages of `[from, to)` written after their last copy - /// (`written`: last writes by page, in page order; `now`: this - /// asking), whole pages within the buffer. + /// Copies the parts of `[from, to)` written after their last copy + /// (`written`: last writes by page, in page order; `now`: this asking): + /// 4 KiB parts where the journal tells them apart, else whole pages, + /// within the buffer ([`stale_runs`]); then notes what the range holds + /// as taken ([`stamp_taken`]). fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { - let base = self.start as usize / PAGE; + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let buffer = (start, end, start / PAGE); let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - let mut writes = written.iter().peekable(); - // Pages the range holds in part are never noted in `copied`, and - // were copied again at every refresh of the range, written or not: - // of the heap's buffer views alone two ends for each of 4,400 - // copies, every frame. A range that was taken whole, and not written - // since, is as it was. + // A range that was taken whole, and not written since, is as it was + // (of the heap's buffer views alone two ends for each of 4,400 + // copies, every frame, were copied again before it was known). let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 }; - let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>); - // Pages taken before and written since: in the order of their runs. - let mut again_at: Vec<(usize, u64)> = Vec::new(); - let last = (to - 1) / PAGE; - for page in from / PAGE..=last { - let write = match writes.peek() { - Some(&&(p, w)) if p == page => { - writes.next(); - w - } - _ => 0, - }; - let at = &mut copied[page - base]; - let taken = (*at).max(ranged); - if taken == 0 || write > taken { - // A page only partly in the range is copied in part: it - // stays stale for the rest. - let (start, end) = (self.start as usize, (self.start + self.len) as usize); - if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { - *at = now; - } - // Cut where pages taken before meet pages never taken. - let again = taken != 0; - if again { - again_at.push((page, taken)); - } - if let Some((first, known)) = run - && known != again - { - runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); - run = None; - } - run.get_or_insert((page, again)); - } else if let Some((first, known)) = run.take() { - runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); - } - } - // Cut to the range: next to it shaders may be writing the copy. - if let Some((first, known)) = run { - runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known)); - } - let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at)); + let mut parts = self.parts_taken.lock().unwrap_or_else(|e| e.into_inner()); + let pages: Vec<usize> = written.iter().map(|w| w.0).collect(); + let each = crate::watch::part_writes(&pages); + let runs = stale_runs(from, to, buffer, &copied, &parts, ranged, written, &each); + { + use std::sync::atomic::Ordering::Relaxed; + let [never, again] = [false, true].map(|known| runs.iter().filter(|r| r.2 == known).map(|r| (r.1 - r.0) as u64).sum::<u64>()); + REFRESHED[0].fetch_add(1, Relaxed); + REFRESHED[1].fetch_add(u64::from(!runs.is_empty()), Relaxed); + REFRESHED[2].fetch_add(never, Relaxed); + REFRESHED[3].fetch_add(again, Relaxed); + REFRESHED[4].fetch_add(u64::from(from % PAGE != 0) + u64::from(to % PAGE != 0 && to != end), Relaxed); + } + // Noted before the bytes go in, under the same lock: no other refresh + // of the copy looks at the notes before they are. + stamp_taken(from, to, buffer, &mut copied, &mut parts, now); + drop(parts); let bytes = self.take_all(runs); if crate::watch::light() { // All of the range is in the copy as of this asking. @@ -4180,6 +5028,7 @@ impl Shadow { /// What shaders wrote in `[from, to)` (offsets) was put into title memory. fn note_landing(&self, from: usize, to: usize) { + self.invalidate_clean(); let first = self.start as usize / KERNEL_PAGE; let pages = (self.start as usize + from) / KERNEL_PAGE - first..(self.start as usize + to).div_ceil(KERNEL_PAGE) - first; let mut bits = self.landings.lock().unwrap_or_else(|e| e.into_inner()); @@ -4198,9 +5047,6 @@ impl Shadow { /// 4 KiB that title memory and the CPU's side have alike are left as they /// are, and nothing of them is sent ([`land_echo`]). fn take_landed(&self, from: usize, to: usize) -> usize { - thread_local! { - static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; - } let start = self.start as usize; let first = start / KERNEL_PAGE; // Runs of pages noted, and not noted (any more). @@ -4223,7 +5069,7 @@ impl Shadow { at = next; } } - TITLE.with_borrow_mut(|title| { + with_title_buffer(|title| { for (from, to, noted) in runs { if !noted { self.copy(from, to); @@ -4244,6 +5090,7 @@ impl Shadow { ECHO[0].fetch_add((next - at) as u64, Ordering::Relaxed); } else { ECHO[1].fetch_add((next - at) as u64, Ordering::Relaxed); + crate::copystat_footprint::cpu_wrote(self.id, self.start, self.len, at - start, next - start); held.copy_from_slice(title); self.changed(at - start, next - start); self.card_changed(at - start, next - start); @@ -4258,50 +5105,82 @@ impl Shadow { /// Copies title memory `[from, to)` (inside the buffer) into the copy; /// `known`: the copy held it before ([`send_changed`]). fn take(&self, from: usize, to: usize, known: bool) -> usize { - thread_local! { - /// A page of title memory, as read. - static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; - } let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else { if known && self.card.is_some() && self.landing.load(Ordering::Acquire) && land_echo() && !crate::host::upcheck::on() { return self.take_landed(from, to); } return self.copy(from, to); }; - let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); + let whole = !known && !card.has_before.load(Ordering::Acquire); let start = self.start as usize; - TITLE.with_borrow_mut(|title| { - title.resize(PAGE, 0); + // Title memory is read through the kernel in chunks of up to this + // many pages, not a call a page: the call's own cost was paid some + // 1,100 times a frame (73 MB of refreshes in 64 KiB pages) on the + // submitting thread's critical path. A chunk with a page that is not + // there still reads it as zeros (`copy_mapped` falls back piece by + // piece), as a read of that page alone did. + const CHUNK_PAGES: usize = 16; + // Per take, not per page: the counters are shared by every refreshing + // thread (four contended adds a page were a line the threads passed + // between them), and the card side's list of what changed is one lock + // a chunk, not one a page. + let mut sent = [0u64; 4]; + let mut card_runs: Vec<(usize, usize)> = Vec::new(); + with_title_buffer(|chunk| { + let mut chunk_at = from; + let mut chunk_end = from; let mut at = from; while at < to { let n = (PAGE - at % PAGE).min(to - at); - let title = &mut title[..n]; - // (Pages that are not there read as zeros.) - crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); + if at + n > chunk_end { + if !card_runs.is_empty() { + self.card_changed_runs(card_runs.drain(..)); + } + chunk_at = at; + chunk_end = (at + CHUNK_PAGES * PAGE - at % PAGE).min(to); + chunk.resize(chunk_end - chunk_at, 0); + // (Pages that are not there read as zeros.) + crate::host::copy_mapped(chunk.as_mut_ptr(), chunk_at as *const u8, chunk_end - chunk_at, false); + } + let title = &mut chunk[at - chunk_at..at - chunk_at + n]; // SAFETY: inside the mapping of the copy's CPU side, which // nothing else reads or writes there (the card copies from // it): no shader's range holds it, and the parts of a // refresh lie apart. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); - let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + // (AVX2 where the page and its length are whole dwords: the + // same runs as `dword_runs`.) + let runs = if whole { vec![(0, n)] } else { word_runs(at, held, title) }; for &(a, len) in &runs { held[a..a + len].copy_from_slice(&title[a..a + len]); - self.changed(at - start + a, at - start + a + len); + crate::copystat_footprint::cpu_wrote(self.id, self.start, self.len, at - start + a, at - start + a + len); + } + // The snapshot's notes: once for the stretch of the page's runs. + if let (Some(first), Some(last)) = (runs.first(), runs.last()) { + self.changed(at - start + first.0, at - start + last.0 + last.1); } - self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len))); + card_runs.extend(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len))); if let Some(was) = was { crate::host::upcheck::note(self.id, at - start, &was, held); } - SEND[0].fetch_add(n as u64, Ordering::Relaxed); + sent[0] += n as u64; if runs.is_empty() { - SEND[1].fetch_add(n as u64, Ordering::Relaxed); + sent[1] += n as u64; } - SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); - SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed); + sent[2] += runs.iter().map(|r| r.1 as u64).sum::<u64>(); + sent[3] += runs.len() as u64; at += n; } }); + if !card_runs.is_empty() { + self.card_changed_runs(card_runs.into_iter()); + } + for (i, n) in sent.into_iter().enumerate() { + if n != 0 { + SEND[i].fetch_add(n, Ordering::Relaxed); + } + } to - from } @@ -4324,6 +5203,7 @@ impl Shadow { // After the bytes are in: a snapshot taken meanwhile is not current. self.changed(from - start, to - start); self.card_changed(from - start, to - start); + crate::copystat_footprint::cpu_wrote(self.id, self.start, self.len, from - start, to - start); to - from } @@ -4426,6 +5306,11 @@ impl Shadow { self.card.as_ref().map_or_else(Vec::new, |c| c.dirty.lock().unwrap_or_else(|e| e.into_inner()).clone()) } + /// Whether a copy in the card's memory has its "before" twin yet (lock-free). + pub(crate) fn card_has_before(&self) -> bool { + self.card.as_ref().is_some_and(|card| card.has_before.load(Ordering::Acquire)) + } + /// Of a copy in the card's memory: the CPU's side (PC memory), the /// card side's bytes from before if made yet, and their size. pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> { @@ -4443,12 +5328,16 @@ impl Shadow { let Some(card) = &self.card else { return false; }; + if card.has_before.load(Ordering::Acquire) { + return false; + } let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner()); if before.is_some() { return false; } *before = make(card.size); if before.is_some() { + card.has_before.store(true, Ordering::Release); CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed); } before.is_some() @@ -4652,6 +5541,33 @@ impl Shadow { } } +/// For `victory bench` (and the tests below): copies with no host buffer +/// behind them, whose refreshes run the code a submission's do. Nothing that +/// asks the buffer (its width, the card's side as a resource) may be called on +/// one: a refresh does neither. +impl Shadow { + /// A copy at `data` of title memory `[start, start + len)`, with a card + /// side if `card`. It is never let go: there is no buffer to release. + pub(crate) fn unbacked_for_bench(start: u64, data: *mut u8, len: u64, card: bool) -> Arc<Shadow> { + // SAFETY: an interface pointer nothing calls (and that is never + // released: the copy is never let go). + let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) }; + let mut shadow = Shadow::new(none(), data, 0, start, len); + if card { + shadow.card = Some(Card::new(none(), len.next_multiple_of(PIECE as u64))); + } + let shadow = Arc::new(shadow); + std::mem::forget(shadow.clone()); + shadow + } + + /// What is to go up to the card, taken (`victory bench` empties it between + /// its rounds, as a submission's sending does). + pub(crate) fn take_card_dirty(&self) -> usize { + self.card.as_ref().map_or(0, |card| std::mem::take(&mut *card.dirty.lock().unwrap_or_else(|e| e.into_inner())).len()) + } +} + /// For tests: copies with no host buffer behind them. #[cfg(test)] impl Shadow { @@ -4662,15 +5578,7 @@ impl Shadow { let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) }; let mut shadow = Shadow::new(none(), data, 0, start, len); if card { - shadow.card = Some(Card { - staging: none(), - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - me: std::sync::OnceLock::new(), - size: len.next_multiple_of(PIECE as u64), - }); + shadow.card = Some(Card::new(none(), len.next_multiple_of(PIECE as u64))); } let shadow = Arc::new(shadow); std::mem::forget(shadow.clone()); @@ -4747,6 +5655,7 @@ impl Shadow { self.walls_merged(hi - lo, merged as usize); if merged > 0 { self.note_landing(lo, hi); + crate::copystat_footprint::gpu_wrote(self.id, self.start, self.len, lo, hi); } put += merged; } @@ -4776,7 +5685,11 @@ impl Shadow { // keeps out what else writes them. Title memory that is not there // is looked at again when the next flight that declared the range // lands. - unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) } + let put = unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) }; + if put > 0 { + crate::copystat_footprint::gpu_wrote(self.id, self.start, self.len, at, at + n); + } + put } /// What shaders wrote in 64 KiB block `block` (of title memory) of this @@ -4809,7 +5722,6 @@ impl Shadow { #[cfg(test)] mod land_tests { use super::{Card, PIECE, Shadow}; - use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; /// A copy in the card's memory of title memory at `title` (its card side @@ -4819,15 +5731,7 @@ mod land_tests { // SAFETY: the mapping, `len` bytes. unsafe { std::ptr::write_bytes(data, 0, len) }; let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64); - shadow.card = Some(Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - me: std::sync::OnceLock::new(), - size: len as u64, - }); + shadow.card = Some(Card::new(buffer, len as u64)); Some(shadow) } @@ -5001,14 +5905,15 @@ struct Entry { /// written when a buffer comes, goes or gets its copy: readers share it. static BUFFERS: std::sync::RwLock<BTreeMap<(u64, usize), Entry>> = std::sync::RwLock::new(BTreeMap::new()); -fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { - let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner()); - // What threads remember of it ([`FOUND`]) is of before. - BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst); - map +fn buffers_write() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.write().unwrap_or_else(|e| e.into_inner()) +} + +fn bump_buffers_changed() { + BUFFERS_CHANGED.fetch_add(1, Ordering::AcqRel); } -/// How often [`BUFFERS`] was taken to be changed. +/// How often an entry in [`BUFFERS`] was removed, let go, or overlapped. static BUFFERS_CHANGED: AtomicU64 = AtomicU64::new(1); /// Answers a thread remembers. @@ -5038,16 +5943,16 @@ fn found_at(address: u64, len: u64) -> usize { /// What this thread remembers of an ask, if nothing changed since. fn found(address: u64, len: u64) -> Option<Arc<Shadow>> { - let changed = BUFFERS_CHANGED.load(Ordering::SeqCst); + let changed = BUFFERS_CHANGED.load(Ordering::Acquire); let shadow = FOUND.with(|f| { let f = f.borrow(); let (a, n, at, shadow) = f.get(found_at(address, len))?; ((*a, *n, *at) == (address, len, changed)).then(|| shadow.upgrade()).flatten() })?; - // Whoever takes the map to let a copy go that nobody holds finds it held - // now, or had counted before: then it is not handed out. - std::sync::atomic::fence(Ordering::SeqCst); - (BUFFERS_CHANGED.load(Ordering::SeqCst) == changed).then_some(shadow) + // `Weak::upgrade` performs an atomic Acquire RMW on the strong count; + // re-checking `BUFFERS_CHANGED` with Acquire ensures no removal or + // overlapping registration occurred before the upgrade completed. + (BUFFERS_CHANGED.load(Ordering::Acquire) == changed).then_some(shadow) } /// Remembers an answer given while `changed` was the count. @@ -5067,10 +5972,17 @@ fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), /// A title buffer exists at `start` (`len` bytes). pub(crate) fn register(resource: usize, start: u64, len: u64) { - buffers().insert( + let end = start.saturating_add(len); + let mut map = buffers_write(); + let overlaps = map.contains_key(&(start, resource)) + || map.range(..(end, 0)).rev().take(64).any(|(_, e)| e.end > start); + if overlaps { + bump_buffers_changed(); + } + map.insert( (start, resource), Entry { - end: start + len, + end, shadow: None, }, ); @@ -5078,14 +5990,18 @@ pub(crate) fn register(resource: usize, start: u64, len: u64) { /// The title released it; lists that still hold its copy keep it alive. pub(crate) fn unregister(resource: usize, start: u64) { - buffers().remove(&(start, resource)); + let mut map = buffers_write(); + if let Some(removed) = map.remove(&(start, resource)) { + bump_buffers_changed(); + drop(removed); + } } /// The title buffer holding `address`, as (start, length), without making /// its copy (diagnostics: which buffer a dropped program's root view names). #[cfg(feature = "diagnostics")] pub(crate) fn extent(address: u64) -> Option<(u64, u64)> { - buffers() + buffers_read() .range(..=(address, usize::MAX)) .rev() .take(64) @@ -5111,12 +6027,15 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { } { // As `lookup` finds a buffer: among the 256 that start below. - let mut map = buffers(); + let mut map = buffers_write(); for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) { if entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()) { gone.extend(entry.shadow.take()); } } + if !gone.is_empty() { + bump_buffers_changed(); + } } let n = gone.len() as u64; for shadow in gone { @@ -5173,6 +6092,39 @@ pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> { buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone()) } +/// Whether `[address, address + len)` should stay in the card's memory +/// (`carded`) rather than streaming directly in place (`port::stream_bytes`): +/// true for unmaterialized/static carded buffers, false for dynamic ranges +/// already seen once by the shadow and dirtied again by CPU writes without +/// pending shader writes. +pub(crate) fn in_card_static(address: u64, len: u64) -> bool { + let Some(end) = address.checked_add(len.max(1)) else { + return false; + }; + let shadow = { + let map = buffers_read(); + let Some((k, e)) = map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) else { + return false; + }; + if let Some(shadow) = &e.shadow { + shadow.clone() + } else { + let size = (e.end - k.0).next_multiple_of(1 << 16); + return cards() && (size >= card_limits().0 || card_all()); + } + }; + if !shadow.carded() { + return false; + } + if shadow.was_copied_before(address as usize, len as usize) + && !shadow.nothing_new(address as usize, len as usize) + && !shadow.writes_pending_in(address as usize, end as usize) + { + return false; + } + true +} + fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { let quick = quick_find(); if quick && let Some(shadow) = found(address, len) { @@ -5186,7 +6138,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { Some((_, Entry { shadow: Some(shadow), .. })) => { if quick { // (Nobody changes the map while this lock is held.) - remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow); + remember(address, len, BUFFERS_CHANGED.load(Ordering::Acquire), shadow); } return Some(shadow.clone()); } @@ -5197,7 +6149,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { } } } - let mut map = buffers(); + let mut map = buffers_write(); let key = map .range(..=(address, usize::MAX)) .rev() @@ -5219,12 +6171,10 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { // memory. Not the big ones `cards` puts in the card's memory: those // are read too often to stay in the PC's. let big = cards() && (size >= card_limits().0 || card_all()); - // Renderer port 1 (`crate::port`, `VICTORY_PORT_CONSTANTS=1`): the - // title's 32-bit graphics heap in place, big or not. - if let Some(placed) = crate::port::place_for(key.0, len, false) { - entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); - return entry.shadow.clone(); - } + // (Title memory in place for constants that no shader writes is + // `crate::port`'s, per access, not a buffer's copy: the copy here + // stays the home of every other access, in the card's memory for + // the big ones. docs/performance/UNIFIED_MEMORY_ARCHITECTURE.md.) if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); return entry.shadow.clone(); @@ -5264,15 +6214,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { len, "a buffer's host copy is in the card's memory" ); - let card = Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - me: std::sync::OnceLock::new(), - size, - }; + let card = Card::new(buffer, size); (on_card, Some(card)) } None => (buffer, None), @@ -5474,9 +6416,9 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { mb.unwrap_or(4096) << 20 }); let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97); - let (staging, data) = host.shared_buffer(len)?; + let (staging, data) = host.shared_buffer_cpu(len)?; let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most { - host.uav_buffer(len) + host.uav_buffer_for(len, Kind::UavShadow) } else { None }; @@ -5493,15 +6435,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { let mut shadow = Shadow::new(buffer, data, gpu, start, len); shadow.window = true; shadow.changes_only.store(true, Ordering::Relaxed); - shadow.card = Some(Card { - staging, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - me: std::sync::OnceLock::new(), - size: len, - }); + shadow.card = Some(Card::new(staging, len)); let shadow = Arc::new(shadow); carded(&shadow); Some(shadow) @@ -5557,7 +6491,7 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha } // In place, if asked for and the window's memory can be opened: the // window is the title's own memory, with nothing to copy. - if let Some(placed) = crate::port::place_for(start, len, true).or_else(|| crate::inplace::place_for(start, len, true)) { + if let Some(placed) = crate::inplace::place_for(start, len, true) { let shadow = Arc::new(Shadow::placed(placed, start, len, true)); note(&shadow); map.insert((start, len), shadow.clone()); @@ -5583,15 +6517,7 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha let (buffer, card) = match window_card_for(len) { Some(on_card) => { crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); - let card = Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - me: std::sync::OnceLock::new(), - size: len, - }; + let card = Card::new(buffer, len); (on_card, Some(card)) } None => (buffer, None), @@ -5887,7 +6813,7 @@ mod window_tests { /// For device-removed reports: the copy of title memory whose host range /// starts closest below host GPU address `va`, and where `va` is in it. pub(crate) fn near(va: u64) -> String { - let mut all: Vec<(u64, u64, u64)> = buffers() + let mut all: Vec<(u64, u64, u64)> = buffers_read() .values() .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len))) .collect(); diff --git a/crates/victory-gpu/src/sharded.rs b/crates/victory-gpu/src/sharded.rs new file mode 100644 index 000000000..9278c9024 --- /dev/null +++ b/crates/victory-gpu/src/sharded.rs @@ -0,0 +1,283 @@ +//! Shared state that the threads translating list calls touch on every draw, +//! spread over cache lines of their own. +//! +//! Why: eight threads of ours (`list::thin`) and the title's recording +//! threads each ran one atomic add on the same few process-wide counters per +//! draw (draws recorded, dropped, dispatched), and one read lock of the +//! table of views per descriptor a draw reads. An atomic add or a read lock +//! is a write: the line moves to the core that does it, and with eight cores +//! doing it on every draw it moves on every one (50 to 300 ns a time). A +//! list call cost 3.5 us alone and 11.5 us with the street chase's eight +//! threads busy (log play-20261127-104020, 70,418 calls in 813 ms of thread +//! time): what grows with the threads is what they share. +//! +//! So each thread takes one of [`SHARDS`] places, numbered on its first use, +//! and writes only its own: a [`Counter`] is summed when it is read (the +//! 5-second line, the frame line), and a [`ReadMostly`] value is read under +//! the thread's own lock and written under all of them. +#![cfg_attr(not(windows), allow(dead_code))] + +use std::cell::{Cell, UnsafeCell}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; +use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError}; + +/// Places: more than the threads that record or translate lists at once +/// (two threads that share one only share a line again). +pub(crate) const SHARDS: usize = 32; + +/// A value alone on its cache lines (two: the processor fetches lines in +/// pairs). +#[repr(align(128))] +struct Padded<T>(T); + +static NEXT: AtomicUsize = AtomicUsize::new(0); + +thread_local! { + static SHARD: Cell<usize> = const { Cell::new(usize::MAX) }; +} + +/// This thread's place. +#[inline] +pub(crate) fn shard() -> usize { + SHARD + .try_with(|s| { + let mut at = s.get(); + if at == usize::MAX { + at = NEXT.fetch_add(1, Relaxed) % SHARDS; + s.set(at); + } + at + }) + .unwrap_or(0) +} + +/// A count many threads add to and one reads now and then. +pub(crate) struct Counter([Padded<AtomicU64>; SHARDS]); + +impl Counter { + pub(crate) const fn new() -> Self { + Counter([const { Padded(AtomicU64::new(0)) }; SHARDS]) + } + + #[inline] + pub(crate) fn add(&self, n: u64) { + self.0[shard()].0.fetch_add(n, Relaxed); + } + + /// The count so far. + pub(crate) fn load(&self) -> u64 { + self.0.iter().fold(0u64, |sum, c| sum.wrapping_add(c.0.load(Relaxed))) + } + + /// The count so far, set to 0 (nothing added meanwhile is lost: each + /// place is taken whole). + pub(crate) fn take(&self) -> u64 { + self.0.iter().fold(0u64, |sum, c| sum.wrapping_add(c.0.swap(0, Relaxed))) + } +} + +/// A value read by many threads at once and written seldom: a reader takes +/// only its thread's lock, a writer takes all of them (in order, so writers +/// do not hold each other up halfway). As an `RwLock` for what it allows. +pub(crate) struct ReadMostly<T> { + locks: [Padded<RwLock<()>>; SHARDS], + value: UnsafeCell<T>, +} + +// SAFETY: the value is reached only through the guards below: shared while a +// thread holds one of the locks for reading (no writer then holds all of +// them), alone while a thread holds all of them for writing. +unsafe impl<T: Send + Sync> Sync for ReadMostly<T> {} +// SAFETY: as for `RwLock<T>`. +unsafe impl<T: Send> Send for ReadMostly<T> {} + +/// A thread's share of a [`ReadMostly`] value. +pub(crate) struct ReadGuard<'a, T> { + _held: RwLockReadGuard<'a, ()>, + value: &'a T, +} + +/// A [`ReadMostly`] value held alone. +pub(crate) struct WriteGuard<'a, T> { + _held: Vec<RwLockWriteGuard<'a, ()>>, + value: &'a mut T, +} + +impl<T> std::ops::Deref for ReadGuard<'_, T> { + type Target = T; + fn deref(&self) -> &T { + self.value + } +} + +impl<T> std::ops::Deref for WriteGuard<'_, T> { + type Target = T; + fn deref(&self) -> &T { + self.value + } +} + +impl<T> std::ops::DerefMut for WriteGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + self.value + } +} + +impl<T> ReadMostly<T> { + pub(crate) const fn new(value: T) -> Self { + ReadMostly { + locks: [const { Padded(RwLock::new(())) }; SHARDS], + value: UnsafeCell::new(value), + } + } + + fn reading<'a>(&'a self, held: RwLockReadGuard<'a, ()>) -> ReadGuard<'a, T> { + // SAFETY: a lock is held for reading (see `Sync`). + ReadGuard { _held: held, value: unsafe { &*self.value.get() } } + } + + fn writing<'a>(&'a self, held: Vec<RwLockWriteGuard<'a, ()>>) -> WriteGuard<'a, T> { + debug_assert_eq!(held.len(), SHARDS); + // SAFETY: every lock is held for writing (see `Sync`). + WriteGuard { _held: held, value: unsafe { &mut *self.value.get() } } + } + + /// Shared, without waiting; `None` if a writer holds this thread's lock. + pub(crate) fn try_read(&self) -> Option<ReadGuard<'_, T>> { + match self.locks[shard()].0.try_read() { + Ok(held) => Some(self.reading(held)), + Err(TryLockError::Poisoned(e)) => Some(self.reading(e.into_inner())), + Err(TryLockError::WouldBlock) => None, + } + } + + /// Shared. + pub(crate) fn read(&self) -> ReadGuard<'_, T> { + let held = self.locks[shard()].0.read().unwrap_or_else(|e| e.into_inner()); + self.reading(held) + } + + /// Alone, without waiting; `None` if any lock is held. + pub(crate) fn try_write(&self) -> Option<WriteGuard<'_, T>> { + let mut held = Vec::with_capacity(SHARDS); + for lock in &self.locks { + match lock.0.try_write() { + Ok(g) => held.push(g), + Err(TryLockError::Poisoned(e)) => held.push(e.into_inner()), + Err(TryLockError::WouldBlock) => return None, + } + } + Some(self.writing(held)) + } + + /// Alone. + pub(crate) fn write(&self) -> WriteGuard<'_, T> { + let held = self.locks.iter().map(|lock| lock.0.write().unwrap_or_else(|e| e.into_inner())).collect(); + self.writing(held) + } +} + +/// Unique numbers from a process-wide count, taken by each thread +/// [`BLOCK`] at a time: one add to the shared count every [`BLOCK`] numbers. +/// The numbers are unique, not in order across threads. +pub(crate) struct Numbers { + next: AtomicU64, +} + +/// Numbers a thread takes at a time ([`Numbers`]). +const BLOCK: u64 = 1024; + +impl Numbers { + /// Numbers from `first` on. + pub(crate) const fn new(first: u64) -> Self { + Numbers { next: AtomicU64::new(first) } + } + + /// A number not given before; `own` is this thread's block of this + /// count (`(next, end)`, `(0, 0)` at first). + #[inline] + pub(crate) fn next(&self, own: &Cell<(u64, u64)>) -> u64 { + let (mut at, mut end) = own.get(); + if at == end { + at = self.next.fetch_add(BLOCK, Relaxed); + end = at + BLOCK; + } + own.set((at + 1, end)); + at + } + + /// One number, without a block (a thread whose own is gone). + pub(crate) fn one(&self) -> u64 { + self.next.fetch_add(1, Relaxed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_counter_sums_what_every_thread_added() { + static C: Counter = Counter::new(); + let threads: Vec<_> = (0..8) + .map(|_| { + std::thread::spawn(|| { + for _ in 0..1000 { + C.add(1); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(C.load(), 8000); + assert_eq!(C.take(), 8000); + assert_eq!(C.load(), 0); + } + + #[test] + fn a_writer_excludes_readers_and_sees_their_world() { + static V: ReadMostly<Vec<u32>> = ReadMostly::new(Vec::new()); + let threads: Vec<_> = (0..8) + .map(|i| { + std::thread::spawn(move || { + for k in 0..200 { + if k % 10 == 0 { + V.write().push(i); + } else { + let v = V.read(); + let n = v.len(); + assert_eq!(v.iter().count(), n); + } + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(V.read().len(), 8 * 20); + assert!(V.try_write().is_some()); + let held = V.read(); + assert!(V.try_write().is_none()); + drop(held); + } + + #[test] + fn numbers_are_unique_across_threads() { + static N: Numbers = Numbers::new(1); + thread_local! { + static OWN: Cell<(u64, u64)> = const { Cell::new((0, 0)) }; + } + let threads: Vec<_> = (0..8) + .map(|_| std::thread::spawn(|| (0..3000).map(|_| OWN.with(|own| N.next(own))).collect::<Vec<u64>>())) + .collect(); + let mut all: Vec<u64> = threads.into_iter().flat_map(|t| t.join().unwrap()).collect(); + all.sort_unstable(); + let n = all.len(); + all.dedup(); + assert_eq!(all.len(), n); + assert!(all[0] >= 1); + } +} diff --git a/crates/victory-gpu/src/stages.rs b/crates/victory-gpu/src/stages.rs new file mode 100644 index 000000000..367e83fcd --- /dev/null +++ b/crates/victory-gpu/src/stages.rs @@ -0,0 +1,872 @@ +//! Where every thread's time goes, in release builds (`VICTORY_CPU_STAGES`, on unless `0`): +//! a sampling profiler of our own process, summed up in a few lines beside each frame-rate +//! line. +//! +//! A thread of its own (`victory-stages`) stops each thread of the process a few hundred times +//! a second (`VICTORY_CPU_STAGES_HZ`, 250), reads where it is and walks its stack back through +//! every module but the title's image (their `.pdata`, read here once a second, and +//! `RtlVirtualUnwind`) until it reaches the title's code, then lets it go on. Nothing is +//! allocated, locked or logged while a thread stands: what a stopped thread may hold, nothing +//! here waits for. A sample is weighed by the time since the round before, so the sums are +//! milliseconds whatever the timer's grain. +//! +//! Per frame (the frame-rate line's frames) it says: +//! - **the title's threads**: time in the title's own code, in ours (by the function of ours the +//! title called: an import of the runtime's, a method of a D3D12 object of ours) busy, waiting +//! (the system's wait calls under it) or handling faults (our exception handlers: guards, soft +//! views); the three busiest title threads split the same way, the busiest one's own time +//! being the title's floor; +//! - **our threads**, by name (`victory-submit`, `victory-present`, `victory-relay`, the pools +//! `victory-list`, `victory-land`, `victory-under`, …): CPU time (the kernel's count, every +//! thread of the process, the unnamed ones (driver, system) together) and the functions of +//! ours they were found in most, busy or waiting; +//! - **the critical path**: while a title thread waited in a present of ours, where the +//! submitting thread was. +//! +//! Function names come from the program's own symbols (`dbghelp`, beside the program), looked +//! up on this thread when a report is written, never while a thread stands. + +use std::collections::HashMap; +use std::sync::Once; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE, LocalFree}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, IMAGE_RUNTIME_FUNCTION_ENTRY, RtlVirtualUnwind, UNW_FLAG_NHANDLER, +}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, MODULEENTRY32W, Module32FirstW, Module32NextW, TH32CS_SNAPMODULE, TH32CS_SNAPTHREAD, + THREADENTRY32, Thread32First, Thread32Next, +}; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, GetThreadTimes, OpenThread, ResumeThread, + SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_LIMITED_INFORMATION, THREAD_SUSPEND_RESUME, +}; + +/// Frames walked at most, and functions of ours kept of them. +const DEPTH: usize = 40; +const KEPT: usize = 8; + +/// Whether it runs (`VICTORY_CPU_STAGES=0`: not). +fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CPU_STAGES").is_none_or(|v| v != "0")) +} + +fn hz() -> u64 { + std::env::var("VICTORY_CPU_STAGES_HZ").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250u64).clamp(10, 2000) +} + +/// Presented frames since the sampler's last report request was taken. +static PENDING_FRAMES: AtomicU64 = AtomicU64::new(0); + +/// Called beside the frame-rate line with all frames since the previous call. +/// The first call starts sampling. Later calls request a report. +pub(crate) fn frame_line(frames: u64) { + if !on() || frames == 0 { + return; + } + static START: Once = Once::new(); + let mut starting = false; + START.call_once(|| { + starting = true; + let _ = std::thread::Builder::new().name("victory-stages".into()).spawn(run); + }); + if !starting { + PENDING_FRAMES.fetch_add(frames, Ordering::Relaxed); + } +} + +/// `.pdata` of a module, as the image has it. +#[repr(C)] +#[derive(Clone, Copy)] +struct RuntimeFunction { + begin: u32, + end: u32, + unwind: u32, +} + +#[derive(Clone, Copy)] +struct Module { + base: usize, + end: usize, + pdata: *const RuntimeFunction, + count: usize, + ours: bool, +} + +/// The process's modules (not the title's image), by base. +struct Modules { + list: Vec<Module>, + /// The title's image. + title: (usize, usize), + /// The system's wait calls (their 32-byte stubs). + waits: Vec<usize>, + /// Where an exception's handling begins on a thread's stack. + dispatcher: usize, +} + +impl Modules { + fn read() -> Modules { + let mut list = Vec::new(); + let mut title = (0, 0); + // SAFETY: plain queries of our own process; the modules stay loaded while listed + // (a module let go later is read no more: the list is read again each second, and an + // address outside every module ends a walk). + unsafe { + let ours = GetModuleHandleW(std::ptr::null()) as usize; + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); + if !snap.is_null() && snap as isize != -1 { + let mut e: MODULEENTRY32W = std::mem::zeroed(); + e.dwSize = size_of::<MODULEENTRY32W>() as u32; + let mut more = Module32FirstW(snap, &mut e) != 0; + while more { + let base = e.modBaseAddr as usize; + let end = base + e.modBaseSize as usize; + let name = String::from_utf16_lossy(&e.szModule[..e.szModule.iter().position(|&c| c == 0).unwrap_or(0)]); + if name.to_ascii_lowercase().starts_with("victory-image") { + title = (base, end); + } else if let Some((pdata, count)) = pdata(base, end) { + list.push(Module { base, end, pdata, count, ours: base == ours }); + } + more = Module32NextW(snap, &mut e) != 0; + } + CloseHandle(snap); + } + } + list.sort_by_key(|m| m.base); + let mut waits = Vec::new(); + let mut dispatcher = 0; + // SAFETY: the system's own library, by name; addresses only. + unsafe { + let ntdll = GetModuleHandleW(windows_sys::core::w!("ntdll.dll")); + if !ntdll.is_null() { + for name in [ + c"NtWaitForSingleObject", + c"NtWaitForMultipleObjects", + c"NtDelayExecution", + c"NtWaitForAlertByThreadId", + c"NtRemoveIoCompletion", + c"NtRemoveIoCompletionEx", + c"NtSignalAndWaitForSingleObject", + c"NtWaitForKeyedEvent", + c"NtYieldExecution", + c"NtWaitForWorkViaWorkerFactory", + c"NtUserMsgWaitForMultipleObjectsEx", + ] { + if let Some(f) = GetProcAddress(ntdll, name.as_ptr().cast()) { + waits.push(f as usize); + } + } + if let Some(f) = GetProcAddress(ntdll, c"KiUserExceptionDispatcher".as_ptr().cast()) { + dispatcher = f as usize; + } + } + } + Modules { list, title, waits, dispatcher } + } + + fn module(&self, at: usize) -> Option<&Module> { + let i = self.list.partition_point(|m| m.base <= at); + let m = self.list.get(i.checked_sub(1)?)?; + (at < m.end).then_some(m) + } + + fn in_title(&self, at: usize) -> bool { + at >= self.title.0 && at < self.title.1 + } + + fn waiting(&self, at: usize) -> bool { + self.waits.iter().any(|&w| at >= w && at < w + 0x20) + } +} + +/// The exception directory of the image at `base`. +/// +/// # Safety +/// `base..end` is a loaded image. +unsafe fn pdata(base: usize, end: usize) -> Option<(*const RuntimeFunction, usize)> { + // SAFETY: the image's headers, inside it. + unsafe { + if end - base < 0x400 || *(base as *const u16) != 0x5A4D { + return None; + } + let nt = base + *((base + 0x3C) as *const u32) as usize; + if nt + 0x108 > end || *(nt as *const u32) != 0x4550 || *((nt + 0x18) as *const u16) != 0x20B { + return None; + } + // (the optional header's data directories begin 112 bytes in; the exception one is the 4th) + let dir = nt + 0x18 + 112 + 3 * 8; + let rva = *(dir as *const u32) as usize; + let size = *((dir + 4) as *const u32) as usize; + if rva == 0 || size < 12 || base + rva + size > end { + return None; + } + Some(((base + rva) as *const RuntimeFunction, size / 12)) + } +} + +/// The function `at` lies in: its entry, if it has one. +/// +/// # Safety +/// `m` is loaded. +unsafe fn lookup(m: &Module, at: usize) -> Option<*const RuntimeFunction> { + let rva = (at - m.base) as u32; + // SAFETY: the module's own table. + let table = unsafe { std::slice::from_raw_parts(m.pdata, m.count) }; + let i = table.partition_point(|f| f.begin <= rva); + let mut f = table.get(i.checked_sub(1)?)? as *const RuntimeFunction; + // SAFETY: as above; an entry that points at another (its low bit) is followed once. + unsafe { + if rva >= (*f).end { + return None; + } + if (*f).unwind & 1 != 0 { + f = (m.base + ((*f).unwind & !1) as usize) as *const RuntimeFunction; + } + } + Some(f) +} + +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// What a stopped thread was found doing. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +enum Kind { + /// In the title's own code. + Title, + /// In ours (or a library's under ours), running. + Busy, + /// In one of the system's wait calls. + Wait, + /// In our handling of an exception (a fault on a guarded page and the like). + Fault, + /// Nowhere we know (no module, a walk that broke off). + Other, +} + +/// One sample: what kind, the function of ours the title called (0 on our threads or in the +/// title's code) and the functions of ours on the stack, innermost first. +#[derive(Clone, Copy)] +struct Sample { + kind: Kind, + entry: usize, + ours: [usize; KEPT], +} + +/// Stops `thread`, reads it, lets it go. Nothing here allocates or takes a lock between the +/// stop and the go. +/// +/// # Safety +/// `thread` is a handle with the rights to stop and read it, not this thread. +unsafe fn sample(thread: HANDLE, stack: (usize, usize), m: &Modules) -> Option<Sample> { + let mut ctx: Aligned = Aligned(unsafe { std::mem::zeroed() }); + ctx.0.ContextFlags = CONTEXT_FULL_AMD64; + // SAFETY: the caller's handle. + if unsafe { SuspendThread(thread) } == u32::MAX { + return None; + } + // SAFETY: a stopped thread of ours, an aligned context. + let read = unsafe { GetThreadContext(thread, &mut ctx.0) } != 0; + let out = if read { Some(walk(&mut ctx, stack, m)) } else { None }; + // SAFETY: as above. + unsafe { ResumeThread(thread) }; + out +} + +/// The stack of a stopped thread, from `ctx` back to the title's code. +fn walk(ctx: &mut Aligned, stack: (usize, usize), m: &Modules) -> Sample { + let first = ctx.0.Rip as usize; + let mut s = Sample { kind: Kind::Other, entry: 0, ours: [0; KEPT] }; + if m.in_title(first) { + s.kind = Kind::Title; + return s; + } + let waiting = m.waiting(first); + let mut kept = 0; + let mut last_ours = 0; + let mut fault = false; + let mut reached = false; + for _ in 0..DEPTH { + let rip = ctx.0.Rip as usize; + if rip == 0 { + break; + } + if m.in_title(rip) { + reached = true; + break; + } + let Some(module) = m.module(rip) else { break }; + let rsp = ctx.0.Rsp as usize; + // (a stack pointer outside the thread's stack ends the walk: nothing is read there) + if rsp & 7 != 0 || rsp < stack.0 || rsp + 64 > stack.1 { + break; + } + // SAFETY: the module is loaded (listed this second). + let entry = unsafe { lookup(module, rip) }; + if let Some(f) = entry { + // SAFETY: as above. + let begin = module.base + unsafe { (*f).begin } as usize; + if begin == m.dispatcher { + fault = true; + } + if module.ours { + if kept < KEPT { + s.ours[kept] = begin; + kept += 1; + } + last_ours = begin; + } + let mut handler: *mut std::ffi::c_void = std::ptr::null_mut(); + let mut frame = 0u64; + // SAFETY: the function's own unwind data, a context of a stopped thread whose + // stack is where its RSP says (checked above). + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + module.base as u64, + rip as u64, + f as *const IMAGE_RUNTIME_FUNCTION_ENTRY, + &mut ctx.0, + &mut handler, + &mut frame, + std::ptr::null_mut(), + ); + } + } else { + // A leaf: its return address is on top of the stack. + if module.ours && kept < KEPT { + s.ours[kept] = rip; + kept += 1; + } + // SAFETY: the top of a stopped thread's stack. + ctx.0.Rip = unsafe { *(rsp as *const u64) }; + ctx.0.Rsp += 8; + } + if (ctx.0.Rsp as usize) <= rsp { + break; + } + } + s.kind = if fault { + Kind::Fault + } else if waiting { + Kind::Wait + } else if kept > 0 || m.module(first).is_some() { + Kind::Busy + } else { + Kind::Other + }; + if reached { + s.entry = last_ours; + } + s +} + +/// A thread of the process: whether the title's, its group's name. +struct Thread { + handle: HANDLE, + /// Its stack: the lowest address it may grow to, and its base. + stack: (usize, usize), + title: bool, + group: usize, + /// CPU time (100 ns) at the last report. + cpu: u64, +} + +/// A group of threads' name: the thread's name without a trailing number. +fn group_of(name: &str) -> String { + let t = name.trim_end_matches(|c: char| c.is_ascii_digit()).trim_end_matches(['-', ' ', '#', '_']); + if t.is_empty() { "(unnamed)".to_owned() } else { t.to_owned() } +} + +fn cpu_time(h: HANDLE) -> u64 { + let z = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut c, mut e, mut k, mut u) = (z, z, z, z); + // SAFETY: a handle with the right to ask. + if unsafe { GetThreadTimes(h, &mut c, &mut e, &mut k, &mut u) } == 0 { + return 0; + } + let t = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32) | u64::from(f.dwLowDateTime); + t(k) + t(u) +} + +/// The thread's start address (`ThreadQuerySetWin32StartAddress`). +fn start_of(h: HANDLE) -> usize { + type Query = unsafe extern "system" fn(HANDLE, u32, *mut std::ffi::c_void, u32, *mut u32) -> i32; + static QUERY: std::sync::OnceLock<Option<Query>> = std::sync::OnceLock::new(); + let q = QUERY.get_or_init(|| { + // SAFETY: the system's library and function, by name and signature. + unsafe { + let ntdll = GetModuleHandleW(windows_sys::core::w!("ntdll.dll")); + GetProcAddress(ntdll, c"NtQueryInformationThread".as_ptr().cast()).map(|f| std::mem::transmute::<_, Query>(f)) + } + }); + let mut start = 0usize; + if let Some(q) = q { + // SAFETY: a pointer-sized answer. + unsafe { q(h, 9, (&mut start as *mut usize).cast(), size_of::<usize>() as u32, std::ptr::null_mut()) }; + } + start +} + +/// The thread's stack, from its TEB: (`DeallocationStack`, `StackBase`); (0, 0) if unknown. +fn stack_of(h: HANDLE) -> (usize, usize) { + type Query = unsafe extern "system" fn(HANDLE, u32, *mut std::ffi::c_void, u32, *mut u32) -> i32; + // SAFETY: the system's library and function, by name and signature. + let q: Option<Query> = unsafe { + let ntdll = GetModuleHandleW(windows_sys::core::w!("ntdll.dll")); + GetProcAddress(ntdll, c"NtQueryInformationThread".as_ptr().cast()).map(|f| std::mem::transmute::<_, Query>(f)) + }; + let Some(q) = q else { return (0, 0) }; + // THREAD_BASIC_INFORMATION: the TEB's address 8 bytes in (48 bytes in all). + let mut info = [0usize; 6]; + // SAFETY: a buffer of the class's size. + if unsafe { q(h, 0, info.as_mut_ptr().cast(), 48, std::ptr::null_mut()) } < 0 || info[1] == 0 { + return (0, 0); + } + let teb = info[1]; + // SAFETY: a live thread's TEB (the thread is ours and its handle open): `NT_TIB.StackBase` + // at 8, `DeallocationStack` at 0x1478 (x64). + unsafe { (*((teb + 0x1478) as *const usize), *((teb + 8) as *const usize)) } +} + +fn name_of(h: HANDLE) -> String { + let mut p: *mut u16 = std::ptr::null_mut(); + // SAFETY: the system's string, freed after. + unsafe { + if GetThreadDescription(h, &mut p) < 0 || p.is_null() { + return String::new(); + } + let n = (0..).take_while(|&i| *p.add(i) != 0).count(); + let s = String::from_utf16_lossy(std::slice::from_raw_parts(p, n)); + LocalFree(p.cast()); + s + } +} + +/// The function names of our program, by address (dbghelp, loaded on first use). +struct Names { + from_address: Option<(unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32, HANDLE)>, + known: HashMap<usize, String>, +} + +impl Names { + fn new() -> Names { + use windows_sys::Win32::System::LibraryLoader::{LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + type Initialize = unsafe extern "system" fn(HANDLE, *const u16, i32) -> i32; + type Options = unsafe extern "system" fn(u32) -> u32; + // SAFETY: the system's library and functions, by name and signature. + let from_address = unsafe { + let module = LoadLibraryExA(c"dbghelp.dll".as_ptr().cast(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); + (|| { + if module.is_null() { + return None; + } + let options: Options = std::mem::transmute(GetProcAddress(module, c"SymSetOptions".as_ptr().cast())?); + let initialize: Initialize = std::mem::transmute(GetProcAddress(module, c"SymInitializeW".as_ptr().cast())?); + let from = std::mem::transmute::< + unsafe extern "system" fn() -> isize, + unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32, + >(GetProcAddress(module, c"SymFromAddr".as_ptr().cast())?); + let process = GetCurrentProcess(); + options(0x2 | 0x4 | 0x200); + let beside = std::env::current_exe().ok().and_then(|p| Some(p.parent()?.to_path_buf())).unwrap_or_default(); + let beside: Vec<u16> = std::os::windows::ffi::OsStrExt::encode_wide(beside.as_os_str()).chain([0]).collect(); + initialize(process, beside.as_ptr(), 1); + Some((from, process)) + })() + }; + Names { from_address, known: HashMap::new() } + } + + fn name(&mut self, at: usize) -> String { + if at == 0 { + return "(none)".to_owned(); + } + if let Some(n) = self.known.get(&at) { + return n.clone(); + } + const NAME: usize = 84; + const ROOM: usize = 512; + let mut info = [0u64; (NAME + ROOM) / 8 + 1]; + let p = info.as_mut_ptr().cast::<u8>(); + let mut off = 0u64; + let found = self.from_address.and_then(|(from, process)| { + // SAFETY: a buffer of the structure's size and the name's, sizes set as asked. + unsafe { + p.cast::<u32>().write(88); + p.add(80).cast::<u32>().write(ROOM as u32); + if from(process, at as u64, &mut off, p) == 0 { + return None; + } + Some(std::ffi::CStr::from_ptr(p.add(NAME).cast()).to_string_lossy().into_owned()) + } + }); + let n = short(&found.unwrap_or_else(|| format!("{at:#x}"))); + self.known.insert(at, n.clone()); + n + } +} + +/// A function's name without its generic arguments and hash, and only its last three parts. +fn short(name: &str) -> String { + let mut out = String::new(); + let mut depth = 0i32; + for c in name.chars() { + match c { + '<' => depth += 1, + '>' => depth -= 1, + _ if depth == 0 => out.push(c), + _ => {} + } + } + // (a legacy symbol's hash: `::h` and 16 hex digits) + let out = match out.rfind("::h") { + Some(i) if out.len() - i == 19 && out[i + 3..].bytes().all(|b| b.is_ascii_hexdigit()) => &out[..i], + _ => out.as_str(), + }; + let parts: Vec<&str> = out.split("::").filter(|p| !p.is_empty() && !p.starts_with("{{closure")).collect(); + let tail = parts.len().saturating_sub(3); + parts[tail..].join("::") +} + +/// The innermost function of ours on a stack whose name says it is the runtime's own (not the +/// standard library's), else the innermost. +fn stage(names: &mut Names, s: &Sample) -> String { + let mut first = None; + for &f in s.ours.iter().filter(|&&f| f != 0) { + let n = names.name(f); + let full = names.full(f); + if full.starts_with("victory") { + return n; + } + first.get_or_insert(n); + } + first.unwrap_or_else(|| "(not ours)".to_owned()) +} + +impl Names { + /// The name as dbghelp has it (for telling ours from the standard library's). + fn full(&mut self, at: usize) -> String { + // (`name` keeps the last parts; the crate is the first) + let key = at ^ (1usize << 63); + if let Some(n) = self.known.get(&key) { + return n.clone(); + } + let short = self.name(at); + let crate_of = self + .from_address + .and_then(|(from, process)| { + const NAME: usize = 84; + const ROOM: usize = 512; + let mut info = [0u64; (NAME + ROOM) / 8 + 1]; + let p = info.as_mut_ptr().cast::<u8>(); + let mut off = 0u64; + // SAFETY: as in `name`. + unsafe { + p.cast::<u32>().write(88); + p.add(80).cast::<u32>().write(ROOM as u32); + if from(process, at as u64, &mut off, p) == 0 { + return None; + } + Some(std::ffi::CStr::from_ptr(p.add(NAME).cast()).to_string_lossy().into_owned()) + } + }) + .unwrap_or(short); + self.known.insert(key, crate_of.clone()); + crate_of + } +} + +/// What was summed since the last report. +#[derive(Default)] +struct Sums { + /// ms by (group, kind, entry, stage key = innermost function of ours of the sample). + by: HashMap<(usize, Kind, usize, usize), f64>, + /// A sample of each key kept, for its stack. + stacks: HashMap<(usize, Kind, usize, usize), Sample>, + /// The title's threads: ms by thread, (title, busy, wait, fault). + title_threads: HashMap<u32, [f64; 4]>, + /// While a title thread waited in a present: where the submitting thread was (its key). + at_present: HashMap<(Kind, usize), f64>, + present_ms: f64, +} + +/// Threads of the runtime, the driver or NVIDIA's libraries (D3D12's background threads, +/// Streamline's frame generation and logging threads): never stopped to be sampled, only +/// counted by their CPU time. Frame generation paces presents on its threads, and the +/// driver's threads take part in what the card is fed: stopping them, even for tens of +/// microseconds at a few hundred hertz, is a risk to the frames shown and to the device. +fn foreign(group: &str) -> bool { + let g = group.to_ascii_lowercase(); + g.starts_with("d3d") || g.starts_with("nv") || g.starts_with("sl.") || g.starts_with("dxgi") || g.contains("(not ours)") +} + +fn run() { + let period = Duration::from_micros(1_000_000 / hz()); + let me = unsafe { GetCurrentThreadId() }; + let pid = unsafe { GetCurrentProcessId() }; + let mut threads: HashMap<u32, Thread> = HashMap::new(); + let mut groups: Vec<String> = Vec::new(); + let mut modules = Modules::read(); + let mut read_at = Instant::now(); + refresh_threads(pid, me, &modules, &mut threads, &mut groups); + let mut names = Names::new(); + let mut sums = Sums::default(); + let mut last = Instant::now(); + let mut window_started = last; + let mut handles: Vec<(u32, HANDLE, (usize, usize), bool, usize)> = Vec::new(); + let mut round: Vec<(u32, bool, usize, Sample)> = Vec::new(); + // (the submitting thread's group, once named) + let mut submit_group = usize::MAX; + let mut refresh = false; + let mut handles_ready = false; + loop { + if refresh || !handles_ready || read_at.elapsed() >= Duration::from_secs(1) { + handles_ready = true; + modules = Modules::read(); + read_at = Instant::now(); + refresh_threads(pid, me, &modules, &mut threads, &mut groups); + submit_group = groups.iter().position(|g| g == "victory-submit").unwrap_or(usize::MAX); + handles.clear(); + handles.extend(threads.iter().map(|(&id, t)| (id, t.handle, t.stack, t.title, t.group))); + refresh = false; + } + let now = Instant::now(); + let weight = now.duration_since(last).as_secs_f64().min(0.05) * 1e3; + last = now; + round.clear(); + for &(id, h, stack, title, group) in &handles { + // (unnamed threads that are not the title's — the driver's, the system's — are + // only counted by their CPU time) + if !title && (groups[group] == "(unnamed)" || foreign(&groups[group])) { + continue; + } + // SAFETY: a thread of ours other than this one, opened with those rights. + if let Some(s) = unsafe { sample(h, stack, &modules) } { + round.push((id, title, group, s)); + } + } + // Sums (the threads go on now). + let mut presenting = false; + let mut submit_key = None; + for &(id, title, group, s) in &round { + let key = (group, s.kind, s.entry, s.ours[0]); + *sums.by.entry(key).or_insert(0.0) += weight; + sums.stacks.entry(key).or_insert(s); + if title { + let t = sums.title_threads.entry(id).or_insert([0.0; 4]); + let i = match s.kind { + Kind::Title => 0, + Kind::Wait => 2, + Kind::Fault => 3, + _ => 1, + }; + t[i] += weight; + if s.kind == Kind::Wait && s.entry != 0 && names.name(s.entry).to_ascii_lowercase().contains("present") { + presenting = true; + } + } + if group == submit_group { + submit_key = Some((s.kind, s.ours.iter().copied().find(|&f| f != 0).unwrap_or(0), s)); + } + } + if presenting { + sums.present_ms += weight; + if let Some((kind, _, s)) = submit_key { + // (keyed by the innermost function of ours, named at the report) + let at = s.ours[0]; + *sums.at_present.entry((kind, at)).or_insert(0.0) += weight; + sums.stacks.entry((submit_group, kind, 0, at)).or_insert(s); + } + } + if PENDING_FRAMES.load(Ordering::Relaxed) != 0 { + let frames = PENDING_FRAMES.swap(0, Ordering::Relaxed); + refresh_threads(pid, me, &modules, &mut threads, &mut groups); + let seconds = now.duration_since(window_started).as_secs_f64(); + tracing::info!("cpu stages, report window: {frames} presented frames in {seconds:.2} s"); + report(&mut sums, &mut threads, &groups, &mut names, frames as f64, submit_group); + sums = Sums::default(); + window_started = now; + refresh = true; + } + let spent = now.elapsed(); + if spent < period { + std::thread::sleep(period - spent); + } + } +} + +/// The process's threads now: new ones opened and named, gone ones closed. +fn refresh_threads(pid: u32, me: u32, m: &Modules, threads: &mut HashMap<u32, Thread>, groups: &mut Vec<String>) { + let mut alive = Vec::new(); + // SAFETY: plain queries of our own process. + unsafe { + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snap.is_null() || snap as isize == -1 { + return; + } + let mut e: THREADENTRY32 = std::mem::zeroed(); + e.dwSize = size_of::<THREADENTRY32>() as u32; + let mut more = Thread32First(snap, &mut e) != 0; + while more { + if e.th32OwnerProcessID == pid && e.th32ThreadID != me { + alive.push(e.th32ThreadID); + } + more = Thread32Next(snap, &mut e) != 0; + } + CloseHandle(snap); + } + threads.retain(|id, t| { + let keep = alive.contains(id); + if !keep { + // SAFETY: our own handle. + unsafe { CloseHandle(t.handle) }; + } + keep + }); + for id in alive { + if threads.contains_key(&id) { + continue; + } + // SAFETY: a thread of our process. + let h = unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_LIMITED_INFORMATION, 0, id) }; + if h.is_null() { + continue; + } + let title = m.in_title(start_of(h)); + let g = if title { "title".to_owned() } else { group_of(&name_of(h)) }; + let group = match groups.iter().position(|x| *x == g) { + Some(i) => i, + None => { + groups.push(g); + groups.len() - 1 + } + }; + let stack = stack_of(h); + if stack.1 <= stack.0 { + // SAFETY: our own handle. + unsafe { CloseHandle(h) }; + continue; + } + threads.insert(id, Thread { handle: h, stack, title, group, cpu: cpu_time(h) }); + } +} + +fn kind_name(k: Kind) -> &'static str { + match k { + Kind::Title => "title code", + Kind::Busy => "busy", + Kind::Wait => "waiting", + Kind::Fault => "fault handling", + Kind::Other => "unknown", + } +} + +fn report(sums: &mut Sums, threads: &mut HashMap<u32, Thread>, groups: &[String], names: &mut Names, frames: f64, submit_group: usize) { + let per = |ms: f64| ms / frames; + let title_group = groups.iter().position(|g| g == "title"); + // The title's threads. + let mut split = [0.0f64; 4]; + for t in sums.title_threads.values() { + for i in 0..4 { + split[i] += t[i]; + } + } + let mut busiest: Vec<(u32, [f64; 4])> = sums.title_threads.iter().map(|(&id, &t)| (id, t)).collect(); + busiest.sort_by(|a, b| (b.1[0] + b.1[1] + b.1[3]).total_cmp(&(a.1[0] + a.1[1] + a.1[3]))); + let floor = busiest.first().map_or(0.0, |b| per(b.1[0])); + let tops: Vec<String> = busiest + .iter() + .take(3) + .map(|(id, t)| format!("thread {id}: title {:.1}, ours {:.1}, faults {:.1}, waiting {:.1}", per(t[0]), per(t[1]), per(t[3]), per(t[2]))) + .collect(); + tracing::info!( + "cpu stages, the title's threads per frame (VICTORY_CPU_STAGES): title code {:.1} ms, in ours busy {:.1} ms, fault handling {:.1} ms, waiting {:.1} ms; the title's floor (its busiest thread's own code) {floor:.1} ms; busiest: {}", + per(split[0]), + per(split[1]), + per(split[3]), + per(split[2]), + tops.join("; ") + ); + if let Some(tg) = title_group { + // What of ours the title called: busy and waiting, by the function it called. + for (kind, label) in [(Kind::Busy, "busy in"), (Kind::Wait, "waiting in"), (Kind::Fault, "faults under")] { + let mut by: HashMap<usize, f64> = HashMap::new(); + for (&(g, k, entry, _), &ms) in &sums.by { + if g == tg && k == kind { + *by.entry(entry).or_insert(0.0) += ms; + } + } + let mut v: Vec<(usize, f64)> = by.into_iter().collect(); + v.sort_by(|a, b| b.1.total_cmp(&a.1)); + let list: Vec<String> = v.iter().take(15).filter(|x| per(x.1) >= 0.05).map(|(e, ms)| format!("{} {:.2}", names.name(*e), per(*ms))).collect(); + if !list.is_empty() { + tracing::info!("cpu stages, the title's threads {label} ours, ms a frame: {}", list.join(", ")); + } + } + } + // Our threads: CPU time by group, and where they were. + let mut cpu: HashMap<usize, (f64, usize)> = HashMap::new(); + for t in threads.values_mut() { + let now = cpu_time(t.handle); + let d = now.saturating_sub(t.cpu) as f64 / 1e4; + t.cpu = now; + let e = cpu.entry(t.group).or_insert((0.0, 0)); + e.0 += d; + e.1 += 1; + } + let mut order: Vec<(usize, f64, usize)> = cpu.iter().map(|(&g, &(ms, n))| (g, ms, n)).collect(); + order.sort_by(|a, b| b.1.total_cmp(&a.1)); + let cpu_list: Vec<String> = order + .iter() + .filter(|x| per(x.1) >= 0.1) + .map(|(g, ms, n)| format!("{} {:.1}{}", groups[*g], per(*ms), if *n > 1 { format!(" ({n} threads)") } else { String::new() })) + .collect(); + tracing::info!("cpu stages, CPU time per frame by thread (ms, the kernel's count): {}", cpu_list.join(", ")); + for &(g, ms, _) in order.iter().take(14) { + if Some(g) == title_group || groups[g] == "(unnamed)" || per(ms) < 0.5 { + continue; + } + let mut by: HashMap<(Kind, String), f64> = HashMap::new(); + for (key, &w) in &sums.by { + if key.0 != g { + continue; + } + let s = sums.stacks[key]; + *by.entry((key.1, stage(names, &s))).or_insert(0.0) += w; + } + let mut v: Vec<((Kind, String), f64)> = by.into_iter().collect(); + v.sort_by(|a, b| b.1.total_cmp(&a.1)); + let list: Vec<String> = + v.iter().take(8).filter(|x| per(x.1) >= 0.1).map(|((k, n), w)| format!("{n} {} {:.1}", kind_name(*k), per(*w))).collect(); + if !list.is_empty() { + tracing::info!("cpu stages, {} per frame (ms, sampled): {}", groups[g], list.join(", ")); + } + } + // The critical path. + if sums.present_ms > 0.0 && submit_group != usize::MAX { + let mut by: HashMap<(Kind, String), f64> = HashMap::new(); + for (&(k, at), &w) in &sums.at_present { + let s = sums.stacks.get(&(submit_group, k, 0, at)).copied(); + let n = match s { + Some(s) => stage(names, &s), + None => names.name(at), + }; + *by.entry((k, n)).or_insert(0.0) += w; + } + let mut v: Vec<((Kind, String), f64)> = by.into_iter().collect(); + v.sort_by(|a, b| b.1.total_cmp(&a.1)); + let list: Vec<String> = v.iter().take(6).map(|((k, n), w)| format!("{n} {} {:.1}", kind_name(*k), per(*w))).collect(); + tracing::info!( + "cpu stages, critical path: the title's threads waited in a present of ours {:.1} ms a frame; the submitting thread meanwhile: {}", + per(sums.present_ms), + list.join(", ") + ); + } +} diff --git a/crates/victory-gpu/src/streamline.rs b/crates/victory-gpu/src/streamline.rs index 5007fa886..8020845cd 100644 --- a/crates/victory-gpu/src/streamline.rs +++ b/crates/victory-gpu/src/streamline.rs @@ -1138,6 +1138,7 @@ fn evaluate(host: &crate::host::HostList, up: &Upscale, id: u64) -> bool { } textures[i] = Some((texture, legal)); } + host.trace_gpu_pass("DLSS Super Resolution", [camera.render[0].into(), camera.render[1].into(), camera.output[0].into(), camera.output[1].into(), id as i64]); let recorded = match record(host.list.as_raw(), &textures, &camera, up.pre_exposure, id) { Ok(recorded) => recorded, Err(why) => return fail(&why), @@ -2075,7 +2076,7 @@ fn check_run(output: [u32; 2], device: bool, present: bool) -> Vec<String> { host.present_planes(&base, 0, None, frame); std::thread::sleep(std::time::Duration::from_millis(16)); } - crate::host::settle_for_fence(); + crate::host::settle_for_fence(crate::host::FenceDrain::ExternalUpscaler); lines.push(format!( "frame generation: 180 presents, {} with it on, {} frames shown by it, {} presents tagged with a colour without the interface, status {:#x} (0 is fine){}", FG_ON_ALL.load(Relaxed) - on, diff --git a/crates/victory-gpu/src/texback.rs b/crates/victory-gpu/src/texback.rs index cf7b0e326..c9f988ce9 100644 --- a/crates/victory-gpu/src/texback.rs +++ b/crates/victory-gpu/src/texback.rs @@ -126,7 +126,7 @@ impl Target { /// The readback resources and the allocation the pixels belong to. pub(crate) struct Back { - buffer: ID3D12Resource, + buffer: Option<ID3D12Resource>, footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, rows: Vec<u32>, mips: u32, @@ -138,6 +138,13 @@ impl Back { pub(crate) fn range(&self) -> (usize, usize) { (self.ticket.at, self.ticket.end) } + + /// Takes the readback buffer once its texels have landed, so the caller can + /// return it to the host buffer pool. + #[allow(dead_code)] + pub(crate) fn take_buffer(&mut self) -> Option<ID3D12Resource> { + self.buffer.take() + } } /// Records a host copy from a texture already in COPY_SOURCE. @@ -177,7 +184,7 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option .checked_mul(u64::from(format.Depth))?; total = total.max(footprint.Offset.checked_add(pitched)?); } - let buffer = host.read_back_buffer(total)?; + let buffer = host.read_back_pooled(total)?; for (i, footprint) in footprints.iter().enumerate() { let to = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the location never releases. @@ -194,7 +201,7 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option // SAFETY: an open list; the texture is in the copy-source state. unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } - Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket }) + Some(Back { buffer: Some(buffer), footprints, rows, mips, layout: target.layout, ticket: target.ticket }) } /// Once the list has run, tile its texels back into the same title allocation. @@ -210,6 +217,9 @@ pub(crate) fn land(back: &Back) { } return; } + let Some(buffer) = back.buffer.as_ref() else { + return; + }; let (at, end) = back.range(); let size = end - at; let mut tiled = vec![0u8; size]; @@ -220,7 +230,7 @@ pub(crate) fn land(back: &Back) { let mut data = std::ptr::null_mut(); // SAFETY: our read-back buffer, written by the list that has run. unsafe { - if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { + if buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { return; } } @@ -235,12 +245,12 @@ pub(crate) fn land(back: &Back) { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); // SAFETY: mapped above. - unsafe { back.buffer.Unmap(0, None) }; + unsafe { buffer.Unmap(0, None) }; return; } } // SAFETY: mapped above. - unsafe { back.buffer.Unmap(0, None) }; + unsafe { buffer.Unmap(0, None) }; crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true); let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1; if copied == 1 || copied.is_multiple_of(128) { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 17955a108..486588c5d 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -16,12 +16,15 @@ //! (every mip and array slice), depth and stencil planes are not. pub(crate) mod ahead; +pub mod converted; +pub mod ledger; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::*; +use crate::host::memory_samples::Kind; use crate::host::{HostList, host}; use crate::object::This; @@ -245,7 +248,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { if bytes[0] == 0 || bytes[0] != bytes[1] || !alike { return false; } - let Some(buffer) = host.uav_buffer(bytes[0]) else { + let Some(buffer) = host.uav_buffer_for(bytes[0], Kind::UavTextureSupport) else { return false; }; crate::host::name(&buffer, || { @@ -1136,11 +1139,25 @@ fn record_upload( }, }, }; + upload_noted(list, footprint); // SAFETY: an open list; both locations name live resources. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } } +/// An upload of one subresource into `list`: work there, counted with its +/// bytes (`host::gpu_time`'s steps line). +fn upload_noted(list: &HostList, footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT) { + let f = &footprint.Footprint; + let bytes = u64::from(f.RowPitch) * u64::from(f.Height) * u64::from(f.Depth); + if crate::host::render_trace::active() { + list.gpu_step(crate::host::GpuStep::Uploads, bytes); + } else { + list.gpu_work(); + crate::host::count_gpu_step(crate::host::GpuStep::Uploads, bytes); + } +} + fn fill_plane( layout: &victory_formats::texture::Layout, at: usize, @@ -1227,6 +1244,7 @@ pub(crate) fn zeros(list: &HostList, host: &crate::host::Host, texture: &ID3D12R Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, }; + upload_noted(list, footprint); // SAFETY: an open list; both locations name live resources. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } @@ -1295,6 +1313,7 @@ pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resou Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, }; + upload_noted(list, &footprint); // SAFETY: an open list; both locations name live resources. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 2cfdde6a3..93f10dfff 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -30,11 +30,19 @@ const PENDING: u8 = 1; const DONE: u8 = 2; pub(crate) const LISTED: u8 = 3; -/// Bytes of title memory on their way at most: past it uploads go into the -/// lists, as before. +/// Bytes of title memory on their way at most when nothing says more (a +/// machine short of memory, or none measured yet): past it uploads go into +/// the lists, as before. With memory to spare it is +/// [`crate::residency::staging_ceiling`]. const MOST: u64 = 96 << 20; /// Bytes and textures of one submission at most. -const BATCH: (u64, usize) = (16 << 20, 64); +const BATCH: (u64, usize) = (32 << 20, 128); + +/// Threads that read, detile and copy: a quarter of the cores, 2 to 4 (the +/// copy queue is one; the detiling before it is what parallelises). +fn worker_count() -> usize { + std::thread::available_parallelism().map_or(2, |n| (n.get() / 4).clamp(2, 4)) +} /// Whether it is on (`VICTORY_UPLOAD_AHEAD`; off). pub(crate) fn on() -> bool { @@ -104,7 +112,7 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> { let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); } - let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; + let most = crate::residency::staging_ceiling(MOST, super::ledger::loading()); if !crate::residency::allow_staging_growth(false) || BYTES.load(Relaxed) >= most || copy.flags() & 0x7 != 0 @@ -203,7 +211,7 @@ fn workers() -> Option<&'static ID3D12CommandQueue> { }) .ok()? }; - for n in 0..2 { + for n in 0..worker_count() { let worker = Worker::new(&host.device, queue.clone()).ok()?; std::thread::Builder::new().name(format!("uploads ahead {n}")).spawn(move || worker.work()).ok()?; } @@ -273,10 +281,18 @@ impl Worker { job.record(&self.list); } self.list.Close()?; - self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + let lists = [Some(self.list.cast()?)]; + let trace_start = crate::host::render_trace::active().then(crate::host::now_us); + if trace_start.is_some() { + crate::host::render_trace::execute(&self.queue, &lists, Some((self.fence.as_raw() as usize, value))); + } + self.queue.ExecuteCommandLists(&lists); self.queue.Signal(&self.fence, value)?; // (Without an event: this waits.) self.fence.SetEventOnCompletion(value, windows::Win32::Foundation::HANDLE::default())?; + if let Some(start) = trace_start { + crate::host::render_trace::event("texture_copy_queue_complete", format_args!("fence={:#x}\tvalue={value}\tstart_us={start}\tduration_us={}\tjobs={}", self.fence.as_raw() as usize, crate::host::now_us().saturating_sub(start), jobs.len())); + } } Ok(()) } diff --git a/crates/victory-gpu/src/texture/converted.rs b/crates/victory-gpu/src/texture/converted.rs new file mode 100644 index 000000000..d4197ff2e --- /dev/null +++ b/crates/victory-gpu/src/texture/converted.rs @@ -0,0 +1,267 @@ +//! The converted-asset cache: what a DirectStorage request decoded (BCPack, +//! and zlib before it), kept in the user's cache folder so that the same +//! request in a later run (or later in this one) is a read of the result, not +//! a decode. Write-through: the first time a request is served its output is +//! stored ([`store`], on a thread of its own); every later time it is read +//! ([`open`]). +//! +//! An entry is found by the request ([`Key`]: pack file, offset, sizes, +//! options) and checked against a digest of the source bytes the request +//! read (`source`): a pack file that changed under the same name and offset +//! misses. The file is `<cache>/textures/converted/<xx>/<hex>`, where `<hex>` +//! is 32 hex digits of a digest of the key's bytes and `<xx>` its first two: +//! +//! ```text +//! 0 "VCV1" +//! 4 u32 format version (1) +//! 8 u64 file (FNV-1a of the lower-cased path the title opened) +//! 16 u64 offset +//! 24 u32 source size +//! 28 u32 destination size +//! 32 u64 request options (as the title set them) +//! 40 u128 digest of the source bytes (`texture::digest`) +//! 56 u64 output bytes +//! 64 output bytes, as written to the destination +//! ``` +//! +//! Bounded at [`MOST_BYTES`] on disk: the least recently used entries (by +//! file time, touched on every hit) go first. Nothing here is ever written +//! inside the repository or the game's folder: the folder is a sibling of the +//! shader cache, which the configuration checks against the asset policy +//! (docs/asset-policy.md). + +use std::collections::VecDeque; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, OnceLock}; + +use super::ledger::Key; + +const MAGIC: &[u8; 4] = b"VCV1"; +const VERSION: u32 = 1; +const HEADER: usize = 64; +/// Bytes on disk at most; trimmed to nine tenths of it when passed. +const MOST_BYTES: u64 = 24 << 30; +/// Outputs smaller than this are not worth a file (the decode is cheaper +/// than opening one). +const SMALLEST: usize = 64 << 10; +/// Bytes waiting to be written at most: past it a miss is not stored. +const PENDING_MOST: u64 = 512 << 20; + +static DIR: OnceLock<PathBuf> = OnceLock::new(); +static PENDING: AtomicU64 = AtomicU64::new(0); +/// Since the start: hits, their bytes, misses stored, their bytes, misses +/// not stored (queue full), entries evicted. +static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// Keeps the cache in `dir` from now on (`texture::ledger::use_dir` calls +/// this with its `converted` folder). +pub(crate) fn use_dir(dir: PathBuf) { + let _ = DIR.set(dir); +} + +/// A digest of a request's source bytes, to check an entry against. +pub fn source_hash(bytes: &[u8]) -> u128 { + super::digest(bytes).0 +} + +/// Whether outputs of `len` bytes are kept here at all. +pub fn wanted(len: usize) -> bool { + DIR.get().is_some() && len >= SMALLEST +} + +fn key_bytes(key: &Key) -> [u8; 32] { + let mut b = [0u8; 32]; + b[..8].copy_from_slice(&key.file.to_le_bytes()); + b[8..16].copy_from_slice(&key.offset.to_le_bytes()); + b[16..20].copy_from_slice(&key.source_size.to_le_bytes()); + b[20..24].copy_from_slice(&key.dest_size.to_le_bytes()); + b[24..32].copy_from_slice(&key.options.to_le_bytes()); + b +} + +fn path_for(key: &Key) -> Option<PathBuf> { + let hex = format!("{:032x}", super::digest(&key_bytes(key)).0); + Some(DIR.get()?.join(&hex[..2]).join(&hex[2..])) +} + +fn header(key: &Key, source: u128, len: u64) -> [u8; HEADER] { + let mut h = [0u8; HEADER]; + h[..4].copy_from_slice(MAGIC); + h[4..8].copy_from_slice(&VERSION.to_le_bytes()); + h[8..40].copy_from_slice(&key_bytes(key)); + h[40..56].copy_from_slice(&source.to_le_bytes()); + h[56..64].copy_from_slice(&len.to_le_bytes()); + h +} + +/// A stored output, open for reading. +pub struct Hit { + file: std::fs::File, + len: u64, +} + +impl Hit { + /// The output's bytes. + pub fn bytes(&self) -> usize { + self.len as usize + } + + /// Reads the output into `out` (exactly [`Hit::bytes`] bytes); false if + /// the file is cut short (the caller then decodes as without a hit). + pub fn read_into(mut self, out: &mut [u8]) -> bool { + if out.len() != self.len as usize || self.file.read_exact(out).is_err() { + return false; + } + // Used now: the last to go. + let _ = self.file.set_modified(std::time::SystemTime::now()); + STATS[0].fetch_add(1, Relaxed); + STATS[1].fetch_add(self.len, Relaxed); + true + } +} + +/// The stored output of `key`, if there is one made from the same source +/// bytes. +pub fn open(key: &Key, source: u128) -> Option<Hit> { + let path = path_for(key)?; + let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).ok()?; + let mut h = [0u8; HEADER]; + file.read_exact(&mut h).ok()?; + let len = u64::from_le_bytes(h[56..64].try_into().ok()?); + (h == header(key, source, len) && len <= u64::from(key.dest_size)).then_some(Hit { file, len }) +} + +/// Stores `bytes`, the output of `key` from source bytes of digest `source` +/// (on the writer thread; not stored while too much waits). +pub fn store(key: Key, source: u128, bytes: Vec<u8>) { + let len = bytes.len() as u64; + if DIR.get().is_none() || PENDING.load(Relaxed) + len > PENDING_MOST { + STATS[4].fetch_add(1, Relaxed); + return; + } + static STARTED: OnceLock<bool> = OnceLock::new(); + if !*STARTED.get_or_init(|| std::thread::Builder::new().name("converted cache".into()).spawn(writer).is_ok()) { + return; + } + PENDING.fetch_add(len, Relaxed); + let mut q = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()); + q.push_back((key, source, bytes)); + QUEUE.1.notify_one(); +} + +type Entry = (Key, u128, Vec<u8>); +static QUEUE: (Mutex<VecDeque<Entry>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); + +fn writer() { + let mut on_disk = scan().iter().map(|(_, _, n)| n).sum::<u64>(); + if on_disk > MOST_BYTES { + on_disk = trim(on_disk); + } + tracing::info!(mb = on_disk >> 20, "converted cache: decoded DirectStorage outputs kept on disk"); + let mut since_line = std::time::Instant::now(); + loop { + let (key, source, bytes) = { + let mut q = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + match q.pop_front() { + Some(entry) => break entry, + None => q = QUEUE.1.wait(q).unwrap_or_else(|e| e.into_inner()), + } + } + }; + let len = bytes.len() as u64; + PENDING.fetch_sub(len.min(PENDING.load(Relaxed)), Relaxed); + if write(&key, source, &bytes) { + STATS[2].fetch_add(1, Relaxed); + STATS[3].fetch_add(len, Relaxed); + on_disk += len + HEADER as u64; + if on_disk > MOST_BYTES { + on_disk = trim(on_disk); + } + } + if since_line.elapsed().as_secs() >= 30 { + since_line = std::time::Instant::now(); + let s = |i: usize| STATS[i].load(Relaxed); + tracing::info!( + hits = s(0), + hit_mb = s(1) >> 20, + stored = s(2), + stored_mb = s(3) >> 20, + not_stored = s(4), + evicted = s(5), + on_disk_mb = on_disk >> 20, + "converted cache: since the start" + ); + } + } +} + +fn write(key: &Key, source: u128, bytes: &[u8]) -> bool { + let Some(path) = path_for(key) else { return false }; + let Some(dir) = path.parent() else { return false }; + let tmp = dir.join(format!(".tmp-{}", std::process::id())); + let done = std::fs::create_dir_all(dir) + .and_then(|()| std::fs::File::create(&tmp)) + .and_then(|mut f| { + f.write_all(&header(key, source, bytes.len() as u64))?; + f.write_all(bytes) + }) + .and_then(|()| std::fs::rename(&tmp, &path)); + if let Err(e) = done { + let _ = std::fs::remove_file(&tmp); + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| tracing::warn!(error = %e, "converted cache: an output was not stored (said once)")); + return false; + } + true +} + +/// Every entry: when last used, where, bytes. +fn scan() -> Vec<(std::time::SystemTime, PathBuf, u64)> { + let Some(root) = DIR.get() else { return Vec::new() }; + let mut all = Vec::new(); + for dir in std::fs::read_dir(root).into_iter().flatten().flatten() { + for file in std::fs::read_dir(dir.path()).into_iter().flatten().flatten() { + if let Ok(meta) = file.metadata() + && meta.is_file() + { + all.push((meta.modified().unwrap_or(std::time::UNIX_EPOCH), file.path(), meta.len())); + } + } + } + all +} + +/// Lets the least recently used entries go until nine tenths of +/// [`MOST_BYTES`] are left; the bytes left. +fn trim(_counted: u64) -> u64 { + let mut all = scan(); + let mut left: u64 = all.iter().map(|(_, _, n)| n).sum(); + all.sort_unstable_by_key(|(at, _, _)| *at); + for (_, path, n) in all { + if left <= MOST_BYTES / 10 * 9 { + break; + } + if std::fs::remove_file(&path).is_ok() { + left -= n; + STATS[5].fetch_add(1, Relaxed); + } + } + left +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_header_names_its_request_and_source() { + let key = Key { file: 3, offset: 4096, source_size: 100, dest_size: 400, options: 0x1e }; + let h = header(&key, 7, 400); + assert_eq!(&h[..4], MAGIC); + assert_ne!(h, header(&key, 8, 400)); + assert_ne!(h, header(&Key { offset: 0, ..key }, 7, 400)); + } +} diff --git a/crates/victory-gpu/src/texture/ledger.rs b/crates/victory-gpu/src/texture/ledger.rs new file mode 100644 index 000000000..f6a5be91f --- /dev/null +++ b/crates/victory-gpu/src/texture/ledger.rs @@ -0,0 +1,628 @@ +//! The texture book: what the title's DirectStorage stream fills, followed as +//! it happens, and the textures made ready for it as soon as it has landed. +//! +//! The title asks DirectStorage for texture data (`dstorage.rs` +//! `enqueue_request`) and names the texture in a descriptor only when it +//! uses it, often much later (at world entry: 1.8 million slot writes, a +//! queue of 26,000, minutes at 4-13 fps while the frame thread creates, +//! detiles and uploads 82,000 textures). Here each finished request that +//! filled title memory is noted as it completes ([`request_done`]). If the +//! emulator knows what texture lives at that address (a view that named it +//! earlier in this run, [`desc_known`] / [`named`]; or, for a request that +//! was seen to fill a named texture before, the description the book kept, +//! which only fills in metadata and never predicts a load) and the request +//! covers it, a worker makes the host texture, detiles and uploads it on the +//! copy queue (`ahead`). When the title names the slot, the pass finds the +//! host copy holding exactly the memory's bytes (`texture::unchanged`) and +//! adopts it without an upload. +//! +//! Nothing is loaded that the title did not ask for: only completed +//! requests, only into memory that is mapped, only while the card has room +//! (`resource::room`), host RAM admits (`residency`), and not more than +//! [`UNNAMED_MOST`] bytes made ready and not yet named. A made-ready texture +//! nobody names goes the way of any idle host copy (`resource::let_go_idle`). +//! +//! The book on disk keeps `request -> texture description` for requests whose +//! destination was named by a slot and stayed resident (no use count of +//! its own without that; entries seen evicted or overwritten are dropped, +//! entries unused for [`STALE_RUNS`] runs age out). It holds hashes, offsets +//! and layout words only: no asset bytes (docs/asset-policy.md). +//! +//! Also here: the loading gate. A loading screen is seen from the request +//! stream (requests completing, a `.rpf` opening) while few draws are made; +//! [`loading`] stays true for [`HOLD_MS`] after the last such sign. + +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +/// What identifies a DirectStorage request across runs: the pack file's name +/// (hashed), where and how much was read, and how it was decoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Key { + pub file: u64, + pub offset: u64, + pub source_size: u32, + pub dest_size: u32, + pub options: u64, +} + +const MAGIC: &[u8; 4] = b"VTB2"; +/// Entries kept at most, most used first. +const MAX_ENTRIES: usize = 150_000; +/// Runs an entry may go unnamed before it ages out. +const STALE_RUNS: u32 = 6; +/// Named textures a session needs before it may rewrite the book (a session +/// that never left the menu leaves it as it was). +const MIN_NAMED_TO_SAVE: usize = 256; +const SAVE_EVERY_MS: u64 = 30_000; +/// Entries of each map before it is started over. +const MAP_CAP: usize = 1 << 19; +/// A description seen at an address is trusted this long for requests +/// landing there. +const DESC_FRESH_MS: u64 = 120_000; +/// Wait before a made-ready texture is started: a request whose memory is +/// overwritten or freed at once is not worth it. +const PREHEAT_DELAY_MS: u64 = 120; +const PREHEAT_QUEUE: usize = 16_384; +/// Bytes made ready and not named yet at most; they age out after +/// [`UNNAMED_MS`]. +const UNNAMED_MOST: u64 = 2 << 30; +const UNNAMED_MS: u64 = 60_000; +/// Draws per frame under which the title is on a loading screen when its +/// request stream is busy. +const LOADING_DRAWS: u64 = 200; +/// The gate stays on this long after its last sign. +const HOLD_MS: u64 = 3_000; + +/// What the book knows of a request that filled a named texture. +#[derive(Clone, Copy)] +struct Meta { + resource: [u32; 14], + first: u32, + uses: u32, + last_run: u32, +} + +/// A description seen at an address: words, first level of the view that +/// named it (`u32::MAX`: not known), when, and whether a slot of the pass +/// named it (not just a texture made at that address). +#[derive(Clone, Copy)] +struct Seen { + resource: [u32; 14], + first: u32, + at_ms: u64, + by_pass: bool, +} + +#[derive(Clone, Copy)] +struct Output { + len: u64, + key: Option<Key>, +} + +#[derive(Default)] +struct Book { + dir: Option<PathBuf>, + run: u32, + meta: HashMap<Key, Meta>, + descs: BTreeMap<u64, Seen>, + outputs: BTreeMap<u64, Output>, + /// Named and resident in this session, by address. + named: BTreeMap<u64, Output>, + touched: HashSet<Key>, + evicted: HashSet<Key>, + /// Made ready and not named yet: address -> (bytes, when). + ready: HashMap<u64, (u64, u64)>, + dirty: bool, + last_save: u64, +} + +static BOOK: Mutex<Option<Book>> = Mutex::new(None); + +fn book() -> MutexGuard<'static, Option<Book>> { + BOOK.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn with<R>(f: impl FnOnce(&mut Book) -> R) -> R { + f(book().get_or_insert_with(Book::default)) +} + +/// Requests finished and bytes written since the gate last looked. +static WIN: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +static LAST_BUSY: AtomicU64 = AtomicU64::new(0); +static PACK_AT: AtomicU64 = AtomicU64::new(0); +static LOADING_UNTIL: AtomicU64 = AtomicU64::new(0); +static LOADING_SINCE: AtomicU64 = AtomicU64::new(0); +static TICKED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; +/// Bytes made ready and not named. +static UNNAMED: AtomicU64 = AtomicU64::new(0); +static SAVING: AtomicBool = AtomicBool::new(false); +/// Since the start: requests done, with a description at hand, made ready, +/// adopted by the pass (named while made ready), left out for: no room, +/// host memory, not mapped, taken by none. +static STATS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; +const DONE: usize = 0; +const KNOWN: usize = 1; +const READY: usize = 2; +const ADOPTED: usize = 3; +const NO_ROOM: usize = 4; +const NO_HOST_RAM: usize = 5; +const NOT_MAPPED: usize = 6; +const NOT_TAKEN: usize = 7; +const OVERWRITTEN: usize = 8; +const LOADS: usize = 9; + +/// Keeps the book in `dir` (a folder of the user's cache, checked by the +/// caller) from now on, and reads what an earlier run kept. +pub fn use_dir(dir: PathBuf) { + super::converted::use_dir(dir.join("converted")); + let loaded = std::fs::read(dir.join("book.bin")).ok().and_then(|bytes| parse(&bytes)); + with(|b| { + b.dir = Some(dir); + if let Some((run, meta)) = loaded { + tracing::info!(entries = meta.len(), run, "texture book: read what earlier runs kept"); + b.run = run; + b.meta = meta; + } else { + b.run = 1; + } + }); +} + +/// A pack file was opened; the number to put in the [`Key`]s of its requests. +pub fn file_opened(path: &str) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for byte in path.bytes() { + hash = (hash ^ u64::from(byte.to_ascii_lowercase())).wrapping_mul(0x100_0000_01b3); + } + if path.len() > 4 && path[path.len() - 4..].eq_ignore_ascii_case(".rpf") { + PACK_AT.store(crate::host::coarse_ms().max(1), Relaxed); + } + hash | 1 +} + +/// A DirectStorage request finished and wrote `len` bytes at title address +/// `at` (0: not known, or not in one run of addresses). +pub fn request_done(key: Option<Key>, at: usize, len: usize) { + WIN[0].fetch_add(1, Relaxed); + WIN[1].fetch_add(len as u64, Relaxed); + STATS[DONE].fetch_add(1, Relaxed); + // The gate is looked at from here too: on a loading screen the texture + // pass may not run at all (twice a second at most). + tick(crate::frame::current(), crate::draw::drawn()); + if at == 0 || len < 4096 { + return; + } + let (at, len) = (at as u64, len as u64); + let now = crate::host::coarse_ms(); + let job = with(|b| { + let end = at + len; + // Named textures this overwrites (other than by the same request + // again) are not what the title kept. + let overlapped: Vec<(u64, Output)> = b + .named + .range(..at) + .next_back() + .into_iter() + .chain(b.named.range(at..end)) + .filter(|(a, n)| **a + n.len > at) + .map(|(a, n)| (*a, *n)) + .collect(); + for (a, n) in overlapped { + if n.key != key || key.is_none() { + b.named.remove(&a); + if let Some(k) = n.key { + b.evicted.insert(k); + } + b.dirty = true; + STATS[OVERWRITTEN].fetch_add(1, Relaxed); + } + } + if b.outputs.len() > MAP_CAP { + b.outputs.clear(); + } + b.outputs.insert(at, Output { len, key }); + let seen = b.descs.get(&at).filter(|s| now.saturating_sub(s.at_ms) < DESC_FRESH_MS).copied(); + let seen = seen.or_else(|| { + key.and_then(|k| b.meta.get(&k)).map(|m| Seen { resource: m.resource, first: m.first, at_ms: now, by_pass: false }) + })?; + STATS[KNOWN].fetch_add(1, Relaxed); + if seen.by_pass { + link(b, at, &seen.resource, seen.first, Output { len, key }); + } + let first = if seen.first == u32::MAX { 0 } else { seen.first }; + let bytes = crate::resource::placed_bytes_from(&seen.resource, first)?; + // The request must cover the texture's memory. + if bytes == 0 || bytes > len || UNNAMED.load(Relaxed) + bytes > UNNAMED_MOST { + return None; + } + Some(Job { at, resource: seen.resource, first, bytes, key, len, due: now + PREHEAT_DELAY_MS }) + }); + if let Some(job) = job { + queue(job); + } +} + +/// The pass made `address`'s texture (description `resource`, view from level +/// `first`) whole and resident: the title named it and keeps it. +pub(crate) fn named(address: u64, resource: &[u32; 14], first: u32) { + let mut r = *resource; + r[1] = 0; + r[13] = 0; + let now = crate::host::coarse_ms(); + with(|b| { + // Looked at again as it was (most calls): nothing new. + if b.descs.get(&address).is_some_and(|s| s.by_pass && s.resource == r && s.first == first) + && b.named.contains_key(&address) + && !b.ready.contains_key(&address) + { + return; + } + if b.descs.len() > MAP_CAP { + b.descs.clear(); + } + b.descs.insert(address, Seen { resource: r, first, at_ms: now, by_pass: true }); + if let Some((bytes, _)) = b.ready.remove(&address) { + UNNAMED.fetch_sub(bytes.min(UNNAMED.load(Relaxed)), Relaxed); + STATS[ADOPTED].fetch_add(1, Relaxed); + } + if let Some(out) = b.outputs.get(&address).copied() { + link(b, address, &r, first, out); + } + }); +} + +fn link(b: &mut Book, address: u64, r: &[u32; 14], first: u32, out: Output) { + b.named.insert(address, out); + let Some(key) = out.key else { return }; + let fresh = b.touched.insert(key); + let run = b.run; + let m = b.meta.entry(key).or_insert(Meta { resource: *r, first, uses: 0, last_run: run }); + m.resource = *r; + m.first = first; + m.last_run = run; + if fresh { + m.uses = m.uses.saturating_add(1); + b.dirty = true; + } + b.evicted.remove(&key); +} + +/// A texture was made at `address` for a view that names it (first time for +/// that address and description): what lives there is known from now on. +pub(crate) fn desc_known(address: u64, resource: &[u32; 14]) { + let mut r = *resource; + r[1] = 0; + r[13] = 0; + let now = crate::host::coarse_ms(); + with(|b| { + if b.descs.get(&address).is_some_and(|s| s.resource == r) { + return; + } + if b.descs.len() > MAP_CAP { + b.descs.clear(); + } + b.descs.insert(address, Seen { resource: r, first: u32::MAX, at_ms: now, by_pass: false }); + }); +} + +/// The memory of the texture at `address` is gone (streamed out): it is not +/// what the title kept. +pub(crate) fn gone(address: u64) { + with(|b| { + b.descs.remove(&address); + if let Some(out) = b.named.remove(&address) { + if let Some(k) = out.key { + b.evicted.insert(k); + } + b.dirty = true; + } + }); +} + +/// A made-ready job: which texture, from which level, how many bytes, and +/// the request it came from. +struct Job { + at: u64, + resource: [u32; 14], + first: u32, + bytes: u64, + key: Option<Key>, + len: u64, + due: u64, +} + +static QUEUE: (Mutex<VecDeque<Job>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); + +fn queue(job: Job) { + static STARTED: OnceLock<bool> = OnceLock::new(); + let started = *STARTED.get_or_init(|| std::thread::Builder::new().name("texture book".into()).spawn(worker).is_ok()); + if !started { + return; + } + let mut q = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()); + if q.len() >= PREHEAT_QUEUE { + return; + } + q.push_back(job); + QUEUE.1.notify_one(); +} + +fn worker() { + // As the pass's thread: the locks it takes are counted with its own. + crate::descriptor::IN_TEXTURE_PASS.set(true); + loop { + let job = { + let mut q = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + let now = crate::host::coarse_ms(); + match q.front().map(|j| j.due) { + None => q = QUEUE.1.wait(q).unwrap_or_else(|e| e.into_inner()), + Some(due) if due > now => { + q = QUEUE.1.wait_timeout(q, std::time::Duration::from_millis(due - now)).unwrap_or_else(|e| e.into_inner()).0; + } + Some(_) => break q.pop_front(), + } + } + }; + if let Some(job) = job { + make_ready(job); + } + } +} + +/// Makes the host texture of a finished request's destination and sends its +/// upload to the copy queue. +fn make_ready(job: Job) { + // Still what that memory holds: not overwritten by another request since. + let kept = with(|b| b.outputs.get(&job.at).is_some_and(|o| o.key == job.key && o.len == job.len)); + if !kept || !super::ahead::on() { + return; + } + let memory = crate::host::host().and_then(|h| h.video_memory()); + if !crate::resource::room(memory) { + STATS[NO_ROOM].fetch_add(1, Relaxed); + return; + } + if !crate::residency::admit_texture_pass(false) { + STATS[NO_HOST_RAM].fetch_add(1, Relaxed); + return; + } + if crate::texture::mapped_bytes(job.at as *const u8, job.bytes as usize) < job.bytes { + STATS[NOT_MAPPED].fetch_add(1, Relaxed); + return; + } + let Some(texture) = crate::resource::texture_at(job.at, &job.resource) else { + return; + }; + crate::resource::want_level(texture, job.first); + match super::ahead::take(texture, job.first, job.bytes) { + Some(super::ahead::Taken::New(upload)) => { + super::ahead::send(&upload); + // As the pass does after sending: the job holds the staging + // buffer, the texture keeps none (a texture with one is read as + // one draws read through a table). + crate::texture::unstage(texture); + UNNAMED.fetch_add(job.bytes, Relaxed); + with(|b| { + b.ready.insert(job.at, (job.bytes, crate::host::coarse_ms())); + }); + STATS[READY].fetch_add(1, Relaxed); + } + Some(super::ahead::Taken::Known(_)) => {} + None => { + STATS[NOT_TAKEN].fetch_add(1, Relaxed); + } + } +} + +/// Whether the title is on a loading screen: its request stream is busy (or +/// a pack file opened a moment ago) while it draws little. +pub(crate) fn loading() -> bool { + crate::host::coarse_ms() < LOADING_UNTIL.load(Relaxed) +} + +/// From the pass and from finished requests, twice a second at most: the gate, the one line every five seconds, the +/// book's saving, and the made-ready textures nobody named letting go of +/// their count. +pub(crate) fn tick(frame: u64, drawn: u64) { + let now = crate::host::coarse_ms(); + let before = TICKED[0].load(Relaxed); + if now.saturating_sub(before) < 500 || TICKED[0].compare_exchange(before, now, Relaxed, Relaxed).is_err() { + return; + } + let frames = frame.saturating_sub(TICKED[1].swap(frame, Relaxed)); + let draws = drawn.saturating_sub(TICKED[2].swap(drawn, Relaxed)); + // (No frame at all while the stream is busy: a load the title waits for.) + let per_frame = if frames == 0 { 0 } else { draws / frames }; + let (requests, bytes) = (WIN[0].swap(0, Relaxed), WIN[1].swap(0, Relaxed)); + if requests >= 4 || bytes >= 4 << 20 { + LAST_BUSY.store(now, Relaxed); + } + let recently = |at: u64| at != 0 && now.saturating_sub(at) < 2_500; + let opened = PACK_AT.load(Relaxed) != 0 && now.saturating_sub(PACK_AT.load(Relaxed)) < 8_000; + let busy = recently(LAST_BUSY.load(Relaxed)) || opened; + // (`LOADING_SINCE` is not 0 from the line that says the screen is + // there until the one that says it is over.) + let announced = LOADING_SINCE.load(Relaxed) != 0; + if busy && per_frame < LOADING_DRAWS { + LOADING_UNTIL.store(now + HOLD_MS, Relaxed); + if !announced { + LOADING_SINCE.store(now, Relaxed); + STATS[LOADS].fetch_add(1, Relaxed); + tracing::info!( + requests, + mb = bytes >> 20, + draws_per_frame = per_frame.min(u64::from(u32::MAX)), + "texture book: loading screen seen in the request stream; staging budgets raised" + ); + } + } + if announced && now >= LOADING_UNTIL.load(Relaxed) { + tracing::info!( + seconds = now.saturating_sub(LOADING_SINCE.swap(0, Relaxed)) / 1000, + "texture book: the loading screen is over; staging budgets back to normal" + ); + } + // Those made ready that nobody named in time stop counting against the + // limit (their host copies go the way of idle ones). + let late = with(|b| { + let old: Vec<u64> = b.ready.iter().filter(|(_, (_, at))| now.saturating_sub(*at) > UNNAMED_MS).map(|(a, _)| *a).collect(); + old.into_iter().filter_map(|a| b.ready.remove(&a)).map(|(bytes, _)| bytes).sum::<u64>() + }); + if late != 0 { + UNNAMED.fetch_sub(late.min(UNNAMED.load(Relaxed)), Relaxed); + } + if now.saturating_sub(TICKED[3].load(Relaxed)) >= 5_000 { + TICKED[3].store(now, Relaxed); + let s = |i: usize| STATS[i].load(Relaxed); + if s(DONE) != 0 { + tracing::info!( + requests_done = s(DONE), + texture_known = s(KNOWN), + made_ready = s(READY), + adopted_by_slots = s(ADOPTED), + unnamed_mb = UNNAMED.load(Relaxed) >> 20, + no_room = s(NO_ROOM), + no_host_ram = s(NO_HOST_RAM), + not_mapped = s(NOT_MAPPED), + not_taken = s(NOT_TAKEN), + overwritten = s(OVERWRITTEN), + loading_screens = s(LOADS), + loading = loading(), + "texture book: the title's requests since the start" + ); + } + } + let due = with(|b| { + let named = b.named.len(); + b.dirty && named >= MIN_NAMED_TO_SAVE && b.dir.is_some() && now.saturating_sub(b.last_save) >= SAVE_EVERY_MS + }); + if due && !SAVING.swap(true, Relaxed) { + with(|b| b.last_save = now); + let _ = std::thread::Builder::new().name("texture book save".into()).spawn(|| { + save(); + SAVING.store(false, Relaxed); + }); + } +} + +fn save() { + let Some((dir, bytes)) = with(|b| { + let dir = b.dir.clone()?; + let run = b.run; + let Book { meta, evicted, touched, .. } = b; + meta.retain(|k, m| !(evicted.contains(k) && !touched.contains(k)) && run.saturating_sub(m.last_run) < STALE_RUNS); + if meta.len() > MAX_ENTRIES { + let mut uses: Vec<u32> = meta.values().map(|m| m.uses).collect(); + uses.sort_unstable_by(|a, b| b.cmp(a)); + let least = uses[MAX_ENTRIES - 1]; + let mut room = MAX_ENTRIES; + meta.retain(|_, m| { + let keep = m.uses > least || (m.uses == least && room > 0); + if keep { + room = room.saturating_sub(1); + } + keep + }); + } + b.dirty = false; + Some((dir, encode(b.run, &b.meta))) + }) else { + return; + }; + let tmp = dir.join("book.tmp"); + let done = std::fs::create_dir_all(&dir) + .and_then(|()| std::fs::write(&tmp, &bytes)) + .and_then(|()| std::fs::rename(&tmp, dir.join("book.bin"))); + match done { + Ok(()) => tracing::debug!(bytes = bytes.len(), "texture book: saved"), + Err(e) => { + tracing::warn!(error = %e, "texture book: not saved"); + let _ = std::fs::remove_file(&tmp); + } + } +} + +fn encode(run: u32, meta: &HashMap<Key, Meta>) -> Vec<u8> { + let mut out = Vec::with_capacity(16 + meta.len() * 100); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&run.to_le_bytes()); + out.extend_from_slice(&(meta.len() as u32).to_le_bytes()); + for (k, m) in meta { + out.extend_from_slice(&k.file.to_le_bytes()); + out.extend_from_slice(&k.offset.to_le_bytes()); + out.extend_from_slice(&k.source_size.to_le_bytes()); + out.extend_from_slice(&k.dest_size.to_le_bytes()); + out.extend_from_slice(&k.options.to_le_bytes()); + for w in m.resource { + out.extend_from_slice(&w.to_le_bytes()); + } + out.extend_from_slice(&m.first.to_le_bytes()); + out.extend_from_slice(&m.uses.to_le_bytes()); + out.extend_from_slice(&m.last_run.to_le_bytes()); + } + out +} + +/// The run number to use now, and the entries. `None` for a file that is not +/// ours or cut short (the book starts over). +fn parse(bytes: &[u8]) -> Option<(u32, HashMap<Key, Meta>)> { + const ENTRY: usize = 32 + 56 + 12; + let (head, mut rest) = bytes.split_at_checked(12)?; + if &head[..4] != MAGIC { + return None; + } + let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap_or([0; 4])); + let u64_at = |b: &[u8], i: usize| u64::from_le_bytes(b[i..i + 8].try_into().unwrap_or([0; 8])); + let (run, count) = (u32_at(head, 4), u32_at(head, 8) as usize); + if rest.len() != count.checked_mul(ENTRY)? { + return None; + } + let mut meta = HashMap::with_capacity(count); + while let Some((e, tail)) = rest.split_at_checked(ENTRY) { + rest = tail; + let key = Key { + file: u64_at(e, 0), + offset: u64_at(e, 8), + source_size: u32_at(e, 16), + dest_size: u32_at(e, 20), + options: u64_at(e, 24), + }; + let mut resource = [0u32; 14]; + for (i, w) in resource.iter_mut().enumerate() { + *w = u32_at(e, 32 + 4 * i); + } + let last_run = u32_at(e, 32 + 56 + 8); + meta.insert(key, Meta { resource, first: u32_at(e, 88), uses: u32_at(e, 92), last_run }); + } + // A new session counts as the run after the newest the file knows. + Some((run.saturating_add(1), meta)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_book_round_trips() { + let key = Key { file: 7, offset: 1 << 33, source_size: 5, dest_size: 9, options: 0x1e }; + let mut meta = HashMap::new(); + meta.insert(key, Meta { resource: [3, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0], first: 2, uses: 4, last_run: 3 }); + let bytes = encode(3, &meta); + let (run, back) = parse(&bytes).unwrap(); + assert_eq!(run, 4); + let m = back[&key]; + assert_eq!((m.first, m.uses, m.last_run, m.resource[4]), (2, 4, 3, 256)); + assert!(parse(&bytes[..bytes.len() - 1]).is_none()); + assert!(parse(b"nope").is_none()); + } + + #[test] + fn a_pack_is_known_by_its_name_in_any_case() { + assert_eq!(file_opened("X:\\Pack\\A.rpf"), file_opened("x:\\pack\\a.RPF")); + assert_ne!(file_opened("a"), file_opened("b")); + } +} diff --git a/crates/victory-gpu/src/tight.rs b/crates/victory-gpu/src/tight.rs new file mode 100644 index 000000000..e6b613513 --- /dev/null +++ b/crates/victory-gpu/src/tight.rs @@ -0,0 +1,381 @@ +//! Learned, tight declarations of what a root UAV may write +//! (`VICTORY_TIGHT_WRITES=1`; off by default, see below). +//! +//! A root view has no size, so `Draw::root_uav` declared everything that is +//! left of the title's buffer as written by the shader (the 174 MB heap, from +//! dozens of offsets): that wide declaration drives "title bytes under +//! flights' writes", the hash and compare passes, and the landing of 64 KiB +//! pieces that nothing changed in. +//! +//! Here the footprint is learned per (pipeline, root parameter), relative to +//! the root address, from what landed in title memory +//! ([`landed`], called from the landing's footprint counter): +//! +//! - Learn: the full range is declared, as before, and noted ([`Decls`]); +//! what lands inside a noted range, within [`EXPIRE`], widens that key's +//! footprint. After [`OBSERVE`] landings and [`MIN_DECLS`] declarations the +//! key is tight. +//! - Tight: only the footprint, [`MARGIN`] wider on both sides and in whole +//! 64 KiB blocks, is declared. Every [`VERIFY`]th declaration is full again +//! (noted as in Learn). A landing outside the footprint inside such a +//! verification sets the key to wide for good (logged once). +//! - Wide: as before. +//! +//! What this does not do: a write outside the footprint between two +//! verifications is not declared, so it stays on the card (its bytes reach +//! title memory with the next declared write of the same 64 KiB, or with the +//! next verification that finds it, but not before the title is told). That +//! is why the switch is off by default: the fallback is complete for what a +//! verification sees, not for what happens between verifications. Setting +//! `VICTORY_TIGHT_VERIFY=1` verifies every declaration (nothing is gained +//! then but the learned data's log). Table views ([`crate::draw`]'s +//! `readable`) are sized and have no pipeline identity there: not changed. + +use std::collections::HashMap; +use std::sync::{ + Mutex, RwLock, + atomic::{AtomicU32, Ordering}, +}; +use std::time::{Duration, Instant}; + +const BLOCK: u64 = 64 << 10; +/// Landings that must have been seen before a key is tight. +const OBSERVE: u32 = 8; +/// Full declarations that must have been made before a key is tight. +const MIN_DECLS: u32 = 32; +/// Added to the learned footprint on both sides. +const MARGIN: u64 = 4 * BLOCK; +/// A noted declaration takes landings this long. +const EXPIRE: Duration = Duration::from_millis(400); +/// Noted declarations kept per copy. +const KEEP: usize = 128; + +/// Always on (experimental code: no environment switch). +pub(crate) fn on() -> bool { + true +} + +/// Every this many declarations of a tight key are full. +fn verify_every() -> u32 { + 256 +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Mode { + Learn, + Tight, + Wide, +} + +#[derive(Debug)] +struct Foot { + mode: Mode, + /// Footprint relative to the root address: `[lo, hi)`. + lo: u64, + hi: u64, + seen: u32, + decls: u32, + since_full: AtomicU32, +} + +impl Foot { + fn new() -> Foot { + Foot { + mode: Mode::Learn, + lo: u64::MAX, + hi: 0, + seen: 0, + decls: 0, + since_full: AtomicU32::new(0), + } + } + + /// A landing at `[from, to)` relative to the root address. True if it + /// made the key wide. + fn landed(&mut self, from: u64, to: u64) -> bool { + match self.mode { + Mode::Wide => false, + Mode::Learn => { + self.lo = self.lo.min(from); + self.hi = self.hi.max(to); + self.seen += 1; + false + } + Mode::Tight => { + if from < self.lo || to > self.hi { + self.mode = Mode::Wide; + true + } else { + false + } + } + } + } + + /// Lock-free read path for keys already in `Tight` or `Wide`. + fn declare_read(&self, len: u64, every: u32) -> Option<(u64, u64, bool, Option<(u64, u64)>)> { + match self.mode { + Mode::Wide => Some((0, len, false, None)), + Mode::Learn => None, + Mode::Tight => { + let tight = Some((self.lo, self.hi)); + let next = self.since_full.fetch_add(1, Ordering::Relaxed) + 1; + if next >= every { + self.since_full.store(0, Ordering::Relaxed); + return Some((0, len, true, tight)); + } + let (from, to) = (self.lo.min(len), self.hi.min(len)); + if to <= from { + return Some((0, len, true, tight)); + } + Some((from, to - from, false, tight)) + } + } + } + + /// The range, from the root address, to declare of `len` bytes; + /// whether the declaration is a full one (noted for landings); and the + /// key's learned footprint if already `Tight`. + fn declare(&mut self, len: u64, every: u32) -> (u64, u64, bool, Option<(u64, u64)>) { + self.decls = self.decls.saturating_add(1); + match self.mode { + Mode::Wide => (0, len, false, None), + Mode::Learn => { + if self.seen >= OBSERVE && self.decls >= MIN_DECLS && self.lo < self.hi { + self.lo = (self.lo & !(BLOCK - 1)).saturating_sub(MARGIN); + self.hi = self.hi.div_ceil(BLOCK) * BLOCK + MARGIN; + self.mode = Mode::Tight; + self.since_full.store(0, Ordering::Relaxed); + return (0, len, true, Some((self.lo, self.hi))); + } + (0, len, true, None) + } + Mode::Tight => { + let tight = Some((self.lo, self.hi)); + let next = self.since_full.fetch_add(1, Ordering::Relaxed) + 1; + if next >= every { + self.since_full.store(0, Ordering::Relaxed); + return (0, len, true, tight); + } + let (from, to) = (self.lo.min(len), self.hi.min(len)); + if to <= from { + // Nothing of the footprint inside the range: full. + return (0, len, true, tight); + } + (from, to - from, false, tight) + } + } + } +} + +struct Decl { + key: (usize, u32), + from: u64, + to: u64, + at: Instant, +} + +#[derive(Default)] +struct CopyDecls { + full: Vec<Decl>, + tight: Vec<Decl>, +} + +/// Footprints by key, in [`SHARDS`] parts by key, and noted declarations by +/// copy, in as many parts by copy: one lock for all was taken by every +/// draw or dispatch with a root UAV it writes, on every thread that +/// translates list calls. A declaration takes its key's part, then (when it +/// is a full one) its copy's; a landing takes its copy's part, then the +/// parts of the keys it found, never two at once. +const SHARDS: usize = 16; + +type Keys = HashMap<(usize, u32), Foot>; +type Decls = HashMap<u64, CopyDecls>; + +static KEYS: [RwLock<Option<Keys>>; SHARDS] = [const { RwLock::new(None) }; SHARDS]; +static DECLS: [Mutex<Option<Decls>>; SHARDS] = [const { Mutex::new(None) }; SHARDS]; + +fn spread(x: u64) -> usize { + (x.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 60) as usize % SHARDS +} + +fn keys_read(key: (usize, u32)) -> std::sync::RwLockReadGuard<'static, Option<Keys>> { + let at = spread(key.0 as u64 ^ u64::from(key.1).rotate_left(32)); + KEYS[at].read().unwrap_or_else(|e| e.into_inner()) +} + +fn keys_write(key: (usize, u32)) -> std::sync::RwLockWriteGuard<'static, Option<Keys>> { + let at = spread(key.0 as u64 ^ u64::from(key.1).rotate_left(32)); + KEYS[at].write().unwrap_or_else(|e| e.into_inner()) +} + +fn decls_of(id: u64) -> std::sync::MutexGuard<'static, Option<Decls>> { + DECLS[spread(id)].lock().unwrap_or_else(|e| e.into_inner()) +} + +fn push_decl(list: &mut Vec<Decl>, key: (usize, u32), from: u64, to: u64, now: Instant) { + if let Some(i) = list.iter().rev().take(8).position(|d| d.key == key && d.from == from && d.to == to) { + let at = list.len() - 1 - i; + list[at].at = now; + return; + } + if list.len() >= KEEP { + list.remove(0); + } + list.push(Decl { key, from, to, at: now }); +} + +/// What `Draw::root_uav` declares of a root UAV at `address` in copy `id` +/// (title memory from `start`), whose range is `len` bytes: the offset from +/// `address` and the length. (0, len) unless the key is learned. +pub(crate) fn declare(pipeline: usize, param: u32, id: u64, start: u64, address: u64, len: u64) -> (u64, u64) { + if !on() || len == 0 { + return (0, len); + } + let key = (pipeline, param); + let every = verify_every(); + let fast = { + let guard = keys_read(key); + guard.as_ref().and_then(|k| k.get(&key)).and_then(|foot| foot.declare_read(len, every)) + }; + let (from, n, full, tight) = match fast { + Some(res) => res, + None => keys_write(key) + .get_or_insert_with(Default::default) + .entry(key) + .or_insert_with(Foot::new) + .declare(len, every), + }; + if full || tight.is_some() { + let base = address.saturating_sub(start); + let now = Instant::now(); + let mut decls = decls_of(id); + let entry = decls.get_or_insert_with(Default::default).entry(id).or_default(); + if let Some((t_from, t_to)) = tight { + let c_from = base.saturating_add(t_from); + let c_to = base.saturating_add(t_to).min(base.saturating_add(len)); + if c_from < c_to { + push_decl(&mut entry.tight, key, c_from, c_to, now); + } + } + if full { + push_decl(&mut entry.full, key, base, base.saturating_add(len), now); + } + } + (from, n) +} + +/// Shaders wrote bytes that landed in offsets `[from, to)` of copy `id`. +pub(crate) fn landed(id: u64, from: usize, to: usize) { + if !on() { + return; + } + let (from, to) = (from as u64, to as u64); + // The noted declarations it lands in, in their order: the key and the + // range relative to the declaration. Landings already inside an active + // tight pipeline's learned footprint do not falsely widen another tight + // pipeline verifying over the same shared heap. + let (hits, explained): (Vec<((usize, u32), u64, u64)>, bool) = { + let mut decls = decls_of(id); + let Some(entry) = decls.as_mut().and_then(|d| d.get_mut(&id)) else { + return; + }; + let now = Instant::now(); + entry.full.retain(|d| now.duration_since(d.at) < EXPIRE); + entry.tight.retain(|d| now.duration_since(d.at) < EXPIRE); + let explained = entry.tight.iter().any(|t| from >= t.from && to <= t.to); + let hits = entry + .full + .iter() + .filter(|d| from < d.to && to > d.from) + .map(|d| (d.key, from.max(d.from) - d.from, to.min(d.to) - d.from)) + .collect(); + (hits, explained) + }; + for (key, a, b) in hits { + let widened = keys_write(key) + .as_mut() + .and_then(|k| k.get_mut(&key)) + .is_some_and(|foot| !(foot.mode == Mode::Tight && explained) && foot.landed(a, b)); + if widened { + tracing::warn!( + pipeline = format_args!("{:#x}", key.0), + param = key.1, + from = format_args!("{a:#x}"), + to = format_args!("{b:#x}"), + "a shader wrote outside its learned footprint: its root UAV is declared whole again (VICTORY_TIGHT_WRITES)" + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn learns_then_tightens_then_falls_back() { + let mut f = Foot::new(); + let len = 100 * BLOCK; + // Learning: whole, noted. + for i in 0..MIN_DECLS { + let res = f.declare(len, 4); + assert_eq!((res.0, res.1, res.2), (0, len, true)); + if i + 1 < MIN_DECLS { + assert_eq!(res.3, None); + } + f.landed(10 * BLOCK + 5, 11 * BLOCK); + } + // The declaration that finds it learned is still whole. + assert_eq!(f.mode, Mode::Tight); + let (from, n, full, tight) = f.declare(len, 4); + assert!(!full); + assert_eq!(tight, Some((6 * BLOCK, 15 * BLOCK))); + assert_eq!(from, 6 * BLOCK); + assert_eq!(from + n, 15 * BLOCK); + // Every fourth is whole. + assert!(!f.declare(len, 4).2); + assert!(!f.declare(len, 4).2); + assert!(f.declare(len, 4).2); + // Inside: kept. Outside: wide for good. + assert!(!f.landed(7 * BLOCK, 8 * BLOCK)); + assert!(f.landed(50 * BLOCK, 51 * BLOCK)); + assert_eq!(f.declare(len, 4), (0, len, false, None)); + } + + #[test] + fn never_tight_without_landings() { + let mut f = Foot::new(); + for _ in 0..1000 { + assert_eq!(f.declare(BLOCK, 4), (0, BLOCK, true, None)); + } + assert_eq!(f.mode, Mode::Learn); + } + + #[test] + fn tight_key_not_widened_by_other_tight_key_on_shared_copy() { + let copy_id = 0xdead_beef_u64; + let len = 100 * BLOCK; + let key_a = (0xaaaa_1000, 0); + let key_b = (0xbbbb_2000, 0); + // Train A at [2..3) * BLOCK and B at [60..61) * BLOCK on separate copies first, + // then run both against `copy_id` (shared 100 * BLOCK heap). + let id_a = copy_id + 1; + let id_b = copy_id + 2; + for _ in 0..MIN_DECLS { + let _ = declare(key_a.0, key_a.1, id_a, 0, 0, len); + landed(id_a, (2 * BLOCK) as usize, (3 * BLOCK) as usize); + let _ = declare(key_b.0, key_b.1, id_b, 0, 0, len); + landed(id_b, (60 * BLOCK) as usize, (61 * BLOCK) as usize); + } + // Now both A and B declare on shared `copy_id`; run 256+ declarations so A verifies. + for _ in 0..=verify_every() + 2 { + let _ = declare(key_a.0, key_a.1, copy_id, 0, 0, len); + let _ = declare(key_b.0, key_b.1, copy_id, 0, 0, len); + } + // B lands in its own learned footprint while A's verification is active on `copy_id`. + landed(copy_id, (60 * BLOCK) as usize, (61 * BLOCK) as usize); + let (from_a, n_a) = declare(key_a.0, key_a.1, copy_id, 0, 0, len); + assert!(n_a < len, "pipeline A must stay tight when B lands in B's footprint (got {from_a}..{})", from_a + n_a); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 151de0903..22f343891 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -38,7 +38,12 @@ pub(crate) const PAGE: usize = 64 << 10; const KERNEL_PAGE: usize = 4096; /// The parts of a page. -const PARTS: usize = PAGE / KERNEL_PAGE; +pub(crate) const PARTS: usize = PAGE / KERNEL_PAGE; + +/// Of a host copy, per 64 KiB page it holds in part (by the page's index from +/// the copy's first page): the asking after which each 4 KiB part was last +/// taken whole. A part's note is the later of this and its page's own. +pub(crate) type PartsTaken = BTreeMap<usize, [u64; PARTS]>; /// All of them. const WHOLE: u16 = u16::MAX; @@ -58,6 +63,7 @@ impl Journal { /// Page `page` was found written by asking `now`: the parts in `parts` /// (a bit each). The asking that found it written before (0: none). fn note(&mut self, page: usize, parts: u16, now: u64) -> u64 { + bump_write_blocks(page / (BLOCK / PAGE), page / (BLOCK / PAGE) + 1); let before = self.written.insert(page, now).unwrap_or(0); if parts == WHOLE || !parts_on() { self.parts.remove(&page); @@ -97,6 +103,45 @@ fn next_asking() -> u64 { ASKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 } +/// Page ranges (first, last) in order of their first page, those that +/// overlap or touch made one. Every page of the result is a page of one of +/// `ranges`: asked under the same number, a range across two of them is as +/// asked as one inside either. +fn joined_pages(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.retain(|r| r.0 < r.1); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for (a, b) in ranges { + match out.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + out +} + +/// Whether pages `[first, last)` lie in `ahead` (as [`joined_pages`] makes +/// it): in one of its ranges, which are apart. +fn covers(ahead: &[(usize, usize)], first: usize, last: usize) -> bool { + let i = ahead.partition_point(|r| r.0 <= first); + i > 0 && ahead[i - 1].1 >= last +} + +/// Since the last line: questions answered from what a submission asked +/// ahead, and the ranges it had asked, summed over them (`ahead`'s length). +pub(crate) static COVER_ASKS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`covers`], counted. +fn covered(j: &Journal, first: usize, last: usize) -> bool { + if j.kept && !KEPT.load(std::sync::atomic::Ordering::Acquire) { + return false; + } + use std::sync::atomic::Ordering::Relaxed; + COVER_ASKS[0].fetch_add(1, Relaxed); + COVER_ASKS[1].fetch_add(j.ahead.len() as u64, Relaxed); + covers(&j.ahead, first, last) +} + /// A title-memory range whose changed pages another subsystem needs to read. pub(crate) struct Tracked { start: usize, @@ -127,7 +172,12 @@ struct Journal { parts: std::collections::HashMap<usize, [u64; PARTS], std::hash::BuildHasherDefault<PageHash>>, /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) /// and the asking that did: `writes` answers for a range inside one - /// from the journal, without another kernel call. + /// from the journal, without another kernel call. In order and apart + /// ([`joined_pages`]): a range is looked for by halves ([`covers`]). + /// It was a list in the order asked, looked through whole by every + /// question, and a submission asks about thousands of ranges and then + /// asks the journal of each again (a frame of the chase in run 104020: + /// 12,800 refreshes, 10,977 of them known to copy nothing, 42.9 ms). ahead: Vec<(usize, usize)>, ahead_asked: u64, /// The ahead asking stands for a whole submission ([`ask_once`]): no @@ -150,6 +200,122 @@ static JOURNAL: RwLock<Journal> = RwLock::new(Journal { kept: false, }); +// Reuse the same generation table across the address space. Aliases can +// invalidate an unrelated memo, but every writer still advances its bucket. +const WRITE_BLOCKS: usize = 1 << 16; +static BLOCK_WRITE_GEN: [std::sync::atomic::AtomicU64; WRITE_BLOCKS] = [const { std::sync::atomic::AtomicU64::new(1) }; WRITE_BLOCKS]; +static ALL_WRITE_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static ASK_END_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +static KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(crate) fn kept() -> bool { + KEPT.load(std::sync::atomic::Ordering::Acquire) +} + +/// Whether the submission actually asked the kernel about this range. +pub(crate) fn kept_covers(from: usize, to: usize) -> bool { + if !KEPT.load(std::sync::atomic::Ordering::Acquire) { + return false; + } + let j = journal(); + j.kept && KEPT.load(std::sync::atomic::Ordering::Acquire) && covers(&j.ahead, from / PAGE, to.div_ceil(PAGE)) +} + +/// A copy of the submission's one asking's ranges ([`ask_once`]), for +/// [`kept_covers_cached`]: taken once per asking, not looked up under the +/// journal's lock for every refresh of the submission. +#[derive(Clone, Default)] +pub(crate) struct KeptView { + /// The [`ASK_END_GEN`] it was taken at (0: none). + generation: u64, + ahead: Vec<(usize, usize)>, +} + +impl KeptView { + fn refresh(&mut self) -> bool { + use std::sync::atomic::Ordering::Acquire; + if !KEPT.load(Acquire) { + return false; + } + let generation = ASK_END_GEN.load(Acquire); + if self.generation != generation { + { + let j = journal(); + if !j.kept || !KEPT.load(Acquire) { + return false; + } + self.ahead.clear(); + self.ahead.extend_from_slice(&j.ahead); + } + // Another asking began while this copy was taken. + if ASK_END_GEN.load(Acquire) != generation || !KEPT.load(Acquire) { + self.generation = 0; + return false; + } + self.generation = generation; + } + KEPT.load(Acquire) + } + + /// A read-only copy for workers that can run another refresh while + /// helping with nested work on the same thread. + pub(crate) fn snapshot(&mut self) -> Option<Self> { + self.refresh().then(|| self.clone()) + } + + /// Treat an answer that ended or was replaced as unknown. Every change + /// to a standing answer advances `ASK_END_GEN`. + pub(crate) fn covers_current(&self, from: usize, to: usize) -> bool { + use std::sync::atomic::Ordering::Acquire; + let current = || KEPT.load(Acquire) && ASK_END_GEN.load(Acquire) == self.generation; + current() && covers(&self.ahead, from / PAGE, to.div_ceil(PAGE)) && current() + } +} + +/// [`kept_covers`], from a cache of the standing answer. +pub(crate) fn kept_covers_cached(view: &mut KeptView, from: usize, to: usize) -> bool { + if view.refresh() { + covers(&view.ahead, from / PAGE, to.div_ceil(PAGE)) + } else { + kept_covers(from, to) + } +} + +fn write_generations(first: usize, count: usize) -> impl Iterator<Item = &'static std::sync::atomic::AtomicU64> { + let first = first % WRITE_BLOCKS; + let end = first + count; + BLOCK_WRITE_GEN[first..end.min(WRITE_BLOCKS)].iter().chain(&BLOCK_WRITE_GEN[..end.saturating_sub(WRITE_BLOCKS)]) +} + +#[inline] +fn bump_write_blocks(first: usize, last: usize) { + let count = last.saturating_sub(first); + if count >= WRITE_BLOCKS { + ALL_WRITE_GEN.fetch_add(1, std::sync::atomic::Ordering::Release); + } else { + for generation in write_generations(first, count) { + generation.fetch_add(1, std::sync::atomic::Ordering::Release); + } + } +} + +/// Monotonic write-generation signature for `[from, to)` across 64 KiB blocks, +/// plus the current `ask_once_end` generation (`None` if wider than `4 MiB`). +pub(crate) fn block_write_sig(from: usize, to: usize) -> Option<(u64, u64)> { + if from >= to { + return Some((0, ASK_END_GEN.load(std::sync::atomic::Ordering::Acquire))); + } + if to.saturating_sub(from) > (4 << 20) { + return None; + } + let first = from / BLOCK; + let mut sum = ALL_WRITE_GEN.load(std::sync::atomic::Ordering::Acquire); + for generation in write_generations(first, to.div_ceil(BLOCK) - first) { + sum = sum.wrapping_add(generation.load(std::sync::atomic::Ordering::Acquire)); + } + Some((sum, ASK_END_GEN.load(std::sync::atomic::Ordering::Acquire))) +} + fn journal() -> std::sync::RwLockReadGuard<'static, Journal> { if let Ok(j) = JOURNAL.try_read() { return j; @@ -255,10 +421,19 @@ thread_local! { static FOUND: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; } -/// The pages of `[first, last)` the kernel says were written since it was -/// last asked, in order, each once, with their written parts; `None` if the range is not write-watched -/// memory of one reservation. The caller holds the range ([`Asking`]). -fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { +/// Serializes Windows write-watch calls, including calls on disjoint ranges +/// of a reservation. Take this after the journal lock if both are needed. +pub(crate) fn with_kernel_write_watch<T>(call: impl FnOnce() -> T) -> T { + static LOCK: Mutex<()> = Mutex::new(()); + let _kernel = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + call() +} + +/// Appends the pages of `[first, last)` the kernel says were written since it +/// was last asked, in order, each once, with their written parts, into `out`. +/// Returns `false` if the range is not write-watched memory of one reservation. +/// The caller holds the range ([`Asking`]). +fn kernel_written_into(first: usize, last: usize, out: &mut Vec<(usize, u16)>) -> bool { use windows_sys::Win32::System::Memory::GetWriteWatch; const WRITE_WATCH_FLAG_RESET: u32 = 1; FOUND.with(|found| { @@ -271,7 +446,7 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // SAFETY: the answer buffer holds `count` entries. - let failed = unsafe { + let failed = with_kernel_write_watch(|| unsafe { GetWriteWatch( WRITE_WATCH_FLAG_RESET, (first * PAGE) as *const _, @@ -280,14 +455,14 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { &mut count, &mut granularity, ) - } != 0; + }) != 0; #[cfg(feature = "diagnostics")] { tally(10, u64::from(failed)); tally(11, started.elapsed().as_nanos() as u64); } if failed { - return None; + return false; } #[cfg(feature = "diagnostics")] { @@ -299,23 +474,33 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { tally(0, 1); tally(1, ((last - first) * (PAGE >> 10)) as u64); } - let mut pages: Vec<(usize, u16)> = Vec::new(); + let start = out.len(); for &at in &found[..count] { let (page, part) = (at / PAGE, 1u16 << (at % PAGE / KERNEL_PAGE)); - match pages.last_mut() { - Some((last, parts)) if *last == page => *parts |= part, - _ => pages.push((page, part)), + if out.len() > start + && let Some((last, parts)) = out.last_mut() + && *last == page + { + *parts |= part; + } else { + out.push((page, part)); } } - Some(pages) + true }) } +/// [`kernel_written_into`] allocating a `Vec` for standalone callers. +fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { + let mut pages = Vec::new(); + kernel_written_into(first, last, &mut pages).then_some(pages) +} + /// Ranges of one submission closer than this are asked about together: /// walking the pages between them costs less than another kernel call (a /// call that resets written pages costs 30-70 microseconds whatever the /// range). -const AHEAD_GAP: usize = (8 << 20) / PAGE; +const AHEAD_GAP: usize = (512 << 10) / PAGE; /// The most one asking covers (its answer needs 8 bytes per 4 KiB page). const AHEAD_MAX: usize = (1 << 30) / PAGE; @@ -325,25 +510,29 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; /// submissions refresh thousands of host copies (6,664 askings a frame, /// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are /// left to `writes`. -pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { +/// Collects, sorts, and merges overlapping non-published page intervals for `ranges`. +fn merged_page_pieces(ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { let mut pieces: Vec<(usize, usize)> = ranges .iter() - // Not view memory known by its bits: the kernel would refuse the - // asking (and, asked together with others, theirs). .filter(|r| r.0 < r.1 && !published(r.0, r.1)) .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) .collect(); - if pieces.len() < 2 { - return; - } - pieces.sort_unstable(); - // The submission's one asking stands ([`ask_once`]): what it does not - // hold is left to `writes`. - if journal().kept { - return; + if pieces.len() > 1 { + pieces.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(pieces.len()); + for (a, b) in pieces { + match out.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + return out; } - let _all = Asking::hold_all(); - let (mut asked, mut written) = (Vec::new(), Vec::new()); + pieces +} + +/// Coalesces sorted `pieces` within `AHEAD_GAP` / `AHEAD_MAX` and asks the kernel. +fn ask_pieces(pieces: &[(usize, usize)], min_run: usize, asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>) { let mut i = 0; while i < pieces.len() { let first = pieces[i].0; @@ -356,13 +545,32 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { last = last.max(pieces[k].1); k += 1; } - ask_run(&pieces[i..k], &mut asked, &mut written); + ask_run(&pieces[i..k], min_run, asked, written); i = k; } +} + +pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + if kept() || ranges.len() < 2 { + return; + } + let pieces = merged_page_pieces(ranges); + if pieces.len() < 2 { + return; + } + let _all = Asking::hold_all(); + // A submission can publish its asking while we wait. Check before + // consuming any dirty bits so every answer we take reaches the journal. + if kept() { + return; + } + let (mut asked, mut written) = (Vec::new(), Vec::new()); + ask_pieces(&pieces, 2, &mut asked, &mut written); note_hot(&written); let mut j = journal_mut(); + j.kept = false; j.ahead_asked = next_asking(); - j.ahead = asked; + j.ahead = joined_pages(asked); let now = j.ahead_asked; for (page, parts) in written { j.note(page, parts, now); @@ -508,7 +716,8 @@ fn ask_early(every: std::time::Duration) { /// The submission's refreshes are done: `writes` asks the kernel again. pub(crate) fn ask_ahead_done() { let mut j = journal_mut(); - if !j.kept { + if !j.kept || !kept() { + j.kept = false; j.ahead.clear(); } } @@ -538,74 +747,60 @@ pub(crate) fn once() -> bool { } /// With [`once`]: asks about `ranges` (everything a submission's lists -/// refresh) as [`ask_ahead`] does, and lets that asking stand until +/// refresh) in a single coalesced pass, and lets that asking stand until /// [`ask_once_end`]. pub(crate) fn ask_once(ranges: &[(usize, usize)]) { if !once() { return; } - ask_once_end(); - ask_ahead(ranges); - ask_rest(ranges); -} - -/// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the -/// asking stands. -fn ask_rest(ranges: &[(usize, usize)]) { + let pieces = merged_page_pieces(ranges); + // A range asking can have reset dirty bits whose answer is still being + // published. Wait for it before replacing the standing answer. let _all = Asking::hold_all(); - let mut ahead = { + { let mut j = journal_mut(); - std::mem::take(&mut j.ahead) - }; - // `ask_ahead` leaves a range that lies alone to `writes`, which asks - // once per flush: with one asking for the submission that was every - // such range asked again at each of its 70 flushes (run 76: 2,300 - // askings a frame with the switch on, as without it). They are asked - // here, once; what is not write-watched stays with `writes`. - let mut written = Vec::new(); - for &(start, end) in ranges { - if start >= end || published(start, end) { - continue; - } - let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - if !ahead.iter().any(|&(a, b)| a <= first && last <= b) - && let Some(pages) = kernel_written(first, last) - { - written.extend(pages); - ahead.push((first, last)); + ask_once_end(); + if j.kept || !pieces.is_empty() { + j.ahead.clear(); + j.kept = false; } } + if pieces.is_empty() { + return; + } + let (mut asked, mut written) = (Vec::with_capacity(pieces.len()), Vec::new()); + ask_pieces(&pieces, 1, &mut asked, &mut written); note_hot(&written); let mut j = journal_mut(); - // A number of its own, and the one this asking stands under: between - // the two parts another thread may have asked about a range of the - // second, copied it, and the title written it since. Under the first - // part's number that write was older than the copy, and never copied. let now = next_asking(); j.ahead_asked = now; for (page, parts) in written { j.note(page, parts, now); } - j.kept = !ahead.is_empty(); - j.ahead = ahead; + j.ahead = joined_pages(asked); + j.kept = !j.ahead.is_empty(); + KEPT.store(j.kept, std::sync::atomic::Ordering::Release); } /// The submission's one asking stands no longer: its refreshes are done, /// or title memory was written in a way the journal was not told. pub(crate) fn ask_once_end() { - let mut j = journal_mut(); - if j.kept { - j.kept = false; - j.ahead.clear(); - } + KEPT.store(false, std::sync::atomic::Ordering::Release); + ASK_END_GEN.fetch_add(1, std::sync::atomic::Ordering::Release); } /// We wrote title memory `[at, at + len)` while a submission's one asking /// stands (the title's buffer copies, done at submission): its pages count /// as written after that asking, so the refreshes that follow copy them. pub(crate) fn wrote(at: usize, len: usize) { + if len != 0 { + bump_write_blocks(at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + } + if len == 0 || !KEPT.load(std::sync::atomic::Ordering::Acquire) { + return; + } let mut j = journal_mut(); - if !j.kept || len == 0 { + if !j.kept || !KEPT.load(std::sync::atomic::Ordering::Acquire) { return; } let now = next_asking(); @@ -634,22 +829,23 @@ fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec<usize>)> { /// One kernel asking for `pieces` (page ranges in order); by halves if it /// fails, as a run across two reservations or into memory that is not -/// write-watched does. A piece alone is left to [`writes`]. Adds what was -/// asked to `asked` and the pages found written to `written`. -fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>) { - if pieces.len() < 2 { +/// write-watched does. Runs with fewer than `min_run` pieces are skipped. +fn ask_run(pieces: &[(usize, usize)], min_run: usize, asked: &mut Vec<(usize, usize)>, written: &mut Vec<(usize, u16)>) { + if pieces.len() < min_run || pieces.is_empty() { return; } let first = pieces[0].0; let last = pieces.iter().map(|p| p.1).max().unwrap_or(first); - if let Some(pages) = kernel_written(first, last) { - written.extend(pages); + if kernel_written_into(first, last, written) { asked.push((first, last)); return; } + if pieces.len() < 2 { + return; + } let (a, b) = pieces.split_at(pieces.len() / 2); - ask_run(a, asked, written); - ask_run(b, asked, written); + ask_run(a, min_run, asked, written); + ask_run(b, min_run, asked, written); } /// What [`writes`] would say of `[start, end)` from the journal alone, if @@ -660,10 +856,7 @@ fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let j = journal(); - j.ahead - .iter() - .any(|&(a, b)| a <= first && last <= b) - .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) + covered(&j, first, last).then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) } /// The pages of `[start, end)` (whole pages) as last written, for pages @@ -681,7 +874,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() }; // Asked ahead with the submission's other ranges: the journal has it. - let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j))); + let ahead = |j: &Journal| covered(j, first, last).then(|| (j.ahead_asked, of(j))); if let Some(known) = ahead(&journal()) { return Some(known); } @@ -750,13 +943,92 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve Some(answer) } +/// Whether [`writes_apart`] cuts a wide range where its blocks are published +/// (`VICTORY_TAKE_APART=0`: asked whole, as before). +fn take_apart() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TAKE_APART").is_none_or(|v| v != "0")) +} + +/// Runs of blocks [`writes_apart`] asks about at most; past that the range is +/// asked whole. +const APART_RUNS: usize = 256; + +/// Blocks published between two runs of unpublished ones that are asked with +/// them, as one asking. +const APART_GAP: usize = 8; + +/// The blocks of `[first, last)` an asking must look at: not published +/// ([`PUBLISHED`]), or with the title's bytes put in beside their guards +/// ([`BESIDE`]); as runs `[from, to)`, runs fewer than [`APART_GAP`] apart +/// joined. `None` past [`APART_RUNS`] runs. +fn unpublished_runs(first: usize, last: usize) -> Option<Vec<(usize, usize)>> { + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + let mut open = (!PUBLISHED.word(word) | BESIDE.word(word)) & mask; + while open != 0 { + let bit = open.trailing_zeros() as usize; + // (the run of set bits from `bit` on, inside this word) + let past = bit + (!(open >> bit)).trailing_zeros() as usize; + let (from, to) = (word * 64 + bit, (word * 64 + past).min(until)); + match runs.last_mut() { + Some(run) if from <= run.1 + APART_GAP => run.1 = run.1.max(to), + _ => { + if runs.len() == APART_RUNS { + return None; + } + runs.push((from, to)); + } + } + open = if past >= 64 { 0 } else { open & (u64::MAX << past) }; + } + block = until; + } + Some(runs) +} + +/// [`writes`] (guarded) of `[start, end)` as page and asking, cut where its +/// blocks are published: the runs of blocks that are not are asked as +/// [`writes`] asks, one by one, and the answer for all of the range is then +/// the journal's, which holds every write of the published ones (as +/// [`writes`] answers when the whole range is published). `None` where +/// [`writes`] of a run is. +/// +/// A placed heap of descriptors (185 MB) was asked whole at every round of +/// its records, 27.5 a frame and 5.6 ms of the round's thread, for a few +/// dozen written blocks: one block that was not published made all of it a +/// kernel asking and a walk of its guards under their lock, which the +/// submitting thread's own askings wait for. +pub(crate) fn writes_apart(start: usize, end: usize) -> Option<Vec<(usize, u64)>> { + if start >= end || !take_apart() || !light() { + return writes(start, end, true).map(|w| w.1); + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let Some(runs) = unpublished_runs(first, last) else { + return writes(start, end, true).map(|w| w.1); + }; + if runs.len() == 1 && runs[0] == (first, last) { + return writes(start, end, true).map(|w| w.1); + } + for (from, to) in runs { + writes((from * PAGE).max(start), (to * PAGE).min(end), true)?; + } + let j = journal(); + Some(j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()) +} + /// Whether nothing of `[start, end)` was written that a copy with the notes -/// `copied` (the asking after which each page from page `base` on was taken) -/// and `ranged` (the asking after which a range that holds this one was -/// taken whole, or 0) does not hold, as [`writes`] would answer with nothing +/// `copied` (the asking after which each page from page `base` on was taken), +/// `parts` (the same for the 4 KiB parts of pages it took in part) and +/// `ranged` (the asking after which a range that holds this one was taken +/// whole, or 0) does not hold, as [`writes`] would answer with nothing /// asked: the submission's asking covers the range, or its blocks are known /// by their bits. `false` if something would have to be asked. -pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool { +pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], parts: &PartsTaken, ranged: u64) -> bool { let (first, last) = (start / PAGE, end.div_ceil(PAGE)); // The bits first, then the journal, as in `writes`. let known = published(start, end); @@ -765,14 +1037,59 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], crate::faultbook::note(crate::faultbook::What::Known, first, last, 1); } let j = journal(); - if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + if !known && !covered(&j, first, last) { return false; } let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { return false; }; - (ranged != 0 || taken.iter().all(|&at| at != 0)) - && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) + // The parts of `page` that hold bytes of the range. + let within = |page: usize| { + let (a, b) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end)); + (a - page * PAGE) / KERNEL_PAGE..(b - page * PAGE).div_ceil(KERNEL_PAGE) + }; + // Every byte was taken once: its page whole, or its part. + if ranged == 0 { + for (n, _) in taken.iter().enumerate().filter(|(_, at)| **at == 0) { + let page = first + n; + let Some(stamps) = parts.get(&(page - base)) else { + return false; + }; + if within(page).any(|k| stamps[k] == 0) { + return false; + } + } + } + j.written.range(first..last).all(|(&page, &write)| { + let at = taken[page - first].max(ranged); + if at != 0 && write <= at { + return true; + } + // Taken in part since: each part as it was taken and written. + let Some(stamps) = parts.get(&(page - base)) else { + return false; + }; + let each = j.parts.get(&page); + within(page).all(|k| { + let at = at.max(stamps[k]); + at != 0 && each.map_or(write, |w| w[k]) <= at + }) + }) +} + +/// Per page of `pages`: the asking that last found each of its 4 KiB parts +/// written, where the journal tells them apart; `None` where it holds the +/// page as written whole (each part at the page's last write). +pub(crate) fn part_writes(pages: &[usize]) -> Vec<Option<[u64; PARTS]>> { + if pages.is_empty() { + return Vec::new(); + } + let j = journal(); + pages.iter().map(|page| j.parts.get(page).copied()).collect() +} + +pub(crate) fn part_write(page: usize) -> Option<[u64; PARTS]> { + journal().parts.get(&page).copied() } impl Tracked { @@ -783,7 +1100,7 @@ impl Tracked { if from >= to { return Vec::new(); } - let Some((_, pages)) = writes(from, to, true) else { + let Some(pages) = writes_apart(from, to) else { return Vec::new(); }; let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); @@ -943,7 +1260,7 @@ impl Bits { let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); match self.piece(word) { Some(piece) => { - if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 { + if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != 0 { return true; } block = until; @@ -1133,8 +1450,10 @@ fn open_unlocked(block: usize) -> bool { for &other in &others { TOLD.set(other); BESIDE.set(other); + bump_write_blocks(other, other + 1); } BESIDE.set(block); + bump_write_blocks(block, block + 1); for &other in &others { PUBLISHED.clear(other); } @@ -1277,6 +1596,7 @@ pub(crate) fn put_beside(block: usize, weight: u32, put: impl FnOnce(usize)) -> count.fetch_add(weight, Relaxed); for view in shown.iter().filter(|&&view| view != 0) { BESIDE.set(view / BLOCK); + bump_write_blocks(view / BLOCK, view / BLOCK + 1); } for view in shown.iter().filter(|&&view| view != 0) { PUBLISHED.clear(view / BLOCK); @@ -1436,7 +1756,7 @@ pub(crate) fn guarded(start: usize, end: usize) -> bool { /// Whether nothing of `[start, end)` can have been written since an asking /// noted it in the journal ([`PUBLISHED`]). -fn published(start: usize, end: usize) -> bool { +pub(crate) fn published(start: usize, end: usize) -> bool { let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); // (In this order: who puts something in beside a guard sets the one bit, // then clears the other, which an asking that is publishing the block may @@ -2402,6 +2722,7 @@ fn unguard(g: &mut Guards, blocks: &[usize]) { } } PROTECTED.clear(block); + bump_write_blocks(block, block + 1); } #[cfg(feature = "diagnostics")] if !blocks.is_empty() { @@ -2414,6 +2735,7 @@ fn unguard(g: &mut Guards, blocks: &[usize]) { /// The runtime calls it (as `kernel_will_write`) before the title's kernel /// reads into its own memory. pub fn writing(at: usize, len: usize) { + crate::demand::fulfill_range(at, len, false); // The length is the title's (`fread`'s size times count, saturated). let last = at.saturating_add(len).div_ceil(BLOCK); if !light() || PROTECTED.any(at / BLOCK, last) { @@ -2441,6 +2763,7 @@ pub struct KernelWrite(usize, usize); /// write fail (the kernel does not fault into our handler): a read cut /// short, which the title takes for what the file holds. pub fn kernel_writing(at: usize, len: usize) -> KernelWrite { + crate::demand::fulfill_range(at, len, true); // The kernel's write does not fault into the handler. materialize(at, len); let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); @@ -2528,6 +2851,7 @@ pub fn title_memory_written(at: usize, len: usize, pages: bool) { } let mode = page_writes(); let end = at.saturating_add(len); + bump_write_blocks(at / BLOCK, end.div_ceil(BLOCK)); if pages { WRITTEN[0].fetch_add(1, Relaxed); WRITTEN[1].fetch_add(len as u64, Relaxed); @@ -2818,6 +3142,7 @@ pub fn title_memory_reading_now() -> Option<Reading> { /// neither guarded nor writable) and a kernel read into it fail, so the /// write access is given back. pub fn title_memory_remapped(at: usize, len: usize) { + crate::demand::forget(at, len); crate::texback::remapped(at, len); open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); } @@ -2828,6 +3153,7 @@ pub fn title_memory_remapped(at: usize, len: usize) { /// before the unmapping would leave the address guarded, clean and known by /// its bits ([`PUBLISHED`]) with no view behind it. pub fn title_memory_unmapping(at: usize, len: usize) { + crate::demand::forget(at, len); crate::texback::remapped(at, len); let mut g = title_memory_changed(at, len); if CHANGING.get().0 && len != 0 { @@ -2844,6 +3170,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) { g.clean.remove(block); PUBLISHED.clear(block); PROTECTED.clear(block); + bump_write_blocks(block, block + 1); } } @@ -2852,6 +3179,8 @@ pub fn title_memory_unmapping(at: usize, len: usize) { /// was noted of its blocks (guarded, clean, absent) would be taken for true /// of the next memory at the address. pub fn title_memory_freed(at: usize, len: usize) { + crate::demand::forget(at, len); + bump_write_blocks(at / BLOCK, if len != 0 { at.saturating_add(len).div_ceil(BLOCK) } else { at / BLOCK + 1 }); crate::shadow::write_combined_freed(at, len); let mut g = guards(); let first = at / BLOCK; @@ -3084,6 +3413,15 @@ pub(crate) fn install() { { return EXCEPTION_CONTINUE_EXECUTION; } + // C2 demand landing: a block parked on the card (`PAGE_NOACCESS`) is + // fetched and landed before the title's (or `safecopy`'s) access + // proceeds. + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS + && r.NumberParameters >= 2 + && crate::demand::on_fault(r.ExceptionInformation[1], ours.is_none()) + { + return EXCEPTION_CONTINUE_EXECUTION; + } if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != WRITE @@ -3269,6 +3607,25 @@ mod parts_tests { assert_eq!(j.note(9, 0b100, 9), 0); assert_eq!(j.parts_since(9, 5), 0b100); } + + /// The ranges asked ahead, joined, answer as the list did, and for a + /// range across two that touch. + #[test] + fn ranges_asked_ahead_are_found_by_halves() { + let asked = vec![(40, 50), (10, 20), (15, 30), (30, 32), (60, 61), (5, 5)]; + let ahead = joined_pages(asked.clone()); + assert_eq!(ahead, [(10, 32), (40, 50), (60, 61)]); + for first in 0..70 { + for last in first + 1..71 { + let one = asked.iter().any(|&(a, b)| a <= first && last <= b); + let joined = (10..=31).contains(&first) && last <= 32 + || (40..=49).contains(&first) && last <= 50 + || first == 60 && last == 61; + assert!(!one || covers(&ahead, first, last), "{first}..{last}"); + assert_eq!(covers(&ahead, first, last), joined, "{first}..{last}"); + } + } + } } #[cfg(test)] @@ -3654,20 +4011,80 @@ mod tests { VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as usize; assert_ne!(p, 0); - // One range: `ask_ahead` leaves it. let ranges = [(p, p + 4 * PAGE)]; - ask_ahead(&ranges); let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched"); // SAFETY: committed pages of ours. unsafe { ((p + PAGE) as *mut u8).write_volatile(1) }; - ask_rest(&ranges); + ask_once(&ranges); + let snapshot = KeptView::default().snapshot(); let last = journal().written.get(&(p / PAGE + 1)).copied(); ask_once_end(); + if let Some(snapshot) = snapshot { + assert!(!snapshot.covers_current(p, p + 4 * PAGE)); + } assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}"); + assert!(!kept()); + assert!(!kept_covers(p, p + 4 * PAGE)); + assert!(asked(p, p + 4 * PAGE).is_none()); + // Subsequent writes must be visible through `writes` (stale `ahead` is ignored), + // and `wrote` must not revive or mutate the ended asking. + wrote(p, PAGE); + // SAFETY: committed pages of ours. + unsafe { ((p + 2 * PAGE) as *mut u8).write_volatile(3) }; + let (_, after_end) = writes(p, p + 4 * PAGE, false).expect("watched"); + assert!(after_end.iter().any(|&(page, _)| page == p / PAGE + 2)); // SAFETY: our allocation. unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } + #[test] + fn the_one_asking_waits_for_a_reset_to_be_journaled() { + use std::sync::mpsc; + use std::time::Duration; + + if !once() { + return; + } + // SAFETY: a committed write-watched page, freed after both askers finish. + let p = unsafe { + VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + } as usize; + assert_ne!(p, 0); + let first = p / PAGE; + let (waited, noted) = std::thread::scope(|scope| { + let range = Asking::hold(first, first + 1); + // SAFETY: this is the test's committed page. + unsafe { (p as *mut u8).write_volatile(1) }; + let pages = kernel_written(first, first + 1).expect("write-watched"); + assert_eq!(pages, [(first, 1)]); + let (started, wait_started) = mpsc::channel(); + let (done, wait_done) = mpsc::channel(); + let submission = scope.spawn(move || { + started.send(()).unwrap(); + ask_once(&[(p, p + PAGE)]); + done.send(()).unwrap(); + }); + + wait_started.recv().unwrap(); + let waited = matches!(wait_done.recv_timeout(Duration::from_millis(50)), Err(mpsc::RecvTimeoutError::Timeout)); + let noted = { + let mut j = journal_mut(); + let now = next_asking(); + j.note(first, pages[0].1, now); + now + }; + drop(range); + submission.join().unwrap(); + (waited, noted) + }); + ask_once_end(); + let reported = journal().written.get(&first).copied(); + // SAFETY: no asker is using this reservation anymore. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + assert!(waited, "the submission finished before the earlier answer was journaled"); + assert_eq!(reported, Some(noted)); + } + /// The runtime maps a view and then tells us; a copy's refresh on another /// thread can guard it in between. Told, it is the title's to write: a /// block left read-only and forgotten would be an access violation in @@ -4798,8 +5215,9 @@ mod many_askers_tests { use windows_sys::Win32::System::Memory::*; /// Threads that write pages and ask about overlapping ranges at the same - /// time: whoever wrote a page before asking is told of that write (by - /// its own asking or by one that took the kernel's answer before it). + /// time, with one more asker on a disjoint span of the same reservation. + /// Whoever wrote a page before asking is told of that write (by its own + /// asking or by one that took the kernel's answer before it). #[test] fn no_write_is_lost_between_askers() { const MEM_WRITE_WATCH: u32 = 0x20_0000; @@ -4807,11 +5225,14 @@ mod many_askers_tests { const THREADS: usize = 8; // SAFETY: a reservation of our own, freed at the end. let at = unsafe { - VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + VirtualAlloc(std::ptr::null(), 2 * PAGES * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as usize; assert!(at != 0 && at.is_multiple_of(PAGE)); + let start = std::sync::Barrier::new(THREADS + 1); std::thread::scope(|s| { - for t in 0..THREADS { + for t in 0..=THREADS { + let at = if t == THREADS { at + PAGES * PAGE } else { at }; + let start = &start; s.spawn(move || { let mut last = [0u64; PAGES]; let mut seed = t as u64 * 7919 + 1; @@ -4819,6 +5240,7 @@ mod many_askers_tests { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as usize % n }; + start.wait(); for _ in 0..4000 { let page = next(PAGES); let from = page - next(page.min(12) + 1); diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 9262b6c27..52a3452d4 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -54,6 +54,7 @@ tempfile.workspace = true [features] # Debugging switches (scripted keys and the like). +mimalloc = ["victory-gpu/mimalloc"] diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"] [lints] diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index f3d70bfe1..a8c619d30 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -29,6 +29,9 @@ pub use victory_gpu::console; pub use victory_gpu::streamline; #[cfg(all(windows, feature = "diagnostics"))] pub use victory_gpu::replay; +/// A frame-rate estimate from a run's log without the title (`victory bench`). +#[cfg(windows)] +pub use victory_gpu::bench; #[cfg(windows)] pub use victory_gpu::pipeline::known as known_pipelines; diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index a5de7c41d..f948b1077 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -66,12 +66,16 @@ pub fn warm_shader(container: &[u8]) -> Result<bool, String> { } /// Keeps the host's translations of the title's shaders in `dir` (a -/// folder of the cache) across runs, and its compiled pipelines beside it -/// (`pipelines`). +/// folder of the cache) across runs, its compiled pipelines beside it +/// (`pipelines`), and the texture book and converted DirectStorage outputs +/// (`textures`). pub fn use_shader_cache(dir: std::path::PathBuf) { #[cfg(windows)] { victory_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines")); + // The texture book and the converted cache beside them (`textures`): + // a folder of the same checked cache root, never the repository's. + victory_gpu::texture_book::use_dir(dir.with_file_name("textures")); victory_gpu::shader_cache::use_shader_cache(dir); } #[cfg(not(windows))] diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 14911cd50..735e0b7eb 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -150,7 +150,10 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; let files = Files::new(file, Io::chosen()); - let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files }); + // What the texture book and the converted cache know the file's requests + // by (a `.rpf` opening is also a sign of a loading screen). + let key = victory_gpu::texture_book::file_opened(&kept); + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files, key }); if stream_log::on() { stream_log::line(format_args!("F\t{:x}\t{kept}", file as usize)); } @@ -278,6 +281,8 @@ static FACTORY_VTABLE: Methods<16> = Methods([ struct File { files: Files, + /// [`victory_gpu::texture_book::file_opened`]'s number for its path. + key: u64, } /// How files are read (`VICTORY_DSTORAGE_IO`). @@ -321,9 +326,13 @@ struct Files { io: Io, } +fn worker_count() -> usize { + std::thread::available_parallelism().map_or(4, |n| (n.get() / 2).clamp(2, 6)) +} + impl Files { fn new(first: std::fs::File, io: Io) -> Files { - let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let workers = worker_count(); let others = match io { Io::One => 0, Io::Overlapped => 1, @@ -629,12 +638,22 @@ fn scheduler() -> Option<&'static Scheduler> { }) .as_ref()?; STARTED.call_once(|| { - let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let workers = worker_count(); let started = (0..workers) .filter(|i| { std::thread::Builder::new() .name(format!("dstorage {i}")) - .spawn(|| work(scheduler)) + .spawn(|| { + // Keep background streaming/decompression below translation and submit threads. + #[cfg(windows)] + unsafe { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL, + }; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + } + work(scheduler); + }) .is_ok() }) .count(); @@ -786,6 +805,9 @@ fn work(scheduler: &'static Scheduler) { let reading = victory_gpu::timeline::span("streaming: a request"); let result = execute(&job.request); reading.end(); + if result.is_ok() { + landed(&job.request); + } walls_request(&job.request, &result, started); stream_log::request(&job, started, &result); if let Some(traced) = traced { @@ -1408,6 +1430,24 @@ fn execute(request: &Request) -> Result<(), HRESULT> { } let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; + // Decoded before (in this run or an earlier one): read, not decoded. + let cached = converted_key(request, size).map(|key| (key, victory_gpu::converted_cache::source_hash(&source))); + if let Some((key, hash)) = cached + && let Some(hit) = victory_gpu::converted_cache::open(&key, hash) + { + let n = hit.bytes(); + let mut hit = Some(hit); + let served = into_destination(request, size, |out| match hit.take() { + Some(hit) if n <= out.len() => { + if hit.read_into(&mut out[..n]) { Ok(n) } else { Err(INVALID_DATA) } + } + _ => Err(INVALID_DATA), + }); + if served.is_ok() { + return Ok(()); + } + tracing::debug!("dstorage: a converted cache entry could not be read; decoded"); + } // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { let mut packed = vec![0; request.intermediate_size as usize]; @@ -1417,11 +1457,18 @@ fn execute(request: &Request) -> Result<(), HRESULT> { } else { source }; - into_destination(request, size, |out| match tables { - Some(tables) => bcpack::decode(bc, &source, out, tables) - .map(|()| out.len()) - .map_err(|e| fail(INVALID_DATA, &e.to_string())), - None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), + into_destination(request, size, |out| { + let n = match tables { + Some(tables) => bcpack::decode(bc, &source, out, tables) + .map(|()| out.len()) + .map_err(|e| fail(INVALID_DATA, &e.to_string()))?, + None => inflate(&source, out).map_err(|hr| fail(hr, "zlib"))?, + }; + // Write-through: kept for the next time this request comes. + if let Some((key, hash)) = cached { + victory_gpu::converted_cache::store(key, hash, out[..n].to_vec()); + } + Ok(n) })?; tracing::trace!( options = format_args!("{options:#x}"), @@ -1432,6 +1479,49 @@ fn execute(request: &Request) -> Result<(), HRESULT> { Ok(()) } +/// The converted cache's key for a decoding request from a file whose +/// output (`size` bytes) is worth keeping: BCPack requests (the costly +/// decode), zlib ones only from 1 MiB up. `None` for memory sources. +fn converted_key(request: &Request, size: usize) -> Option<victory_gpu::texture_book::Key> { + let worth = request.options & BCPACK != 0 || size >= 1 << 20; + (worth && victory_gpu::converted_cache::wanted(size)).then(|| request_key(request)).flatten() +} + +/// What a request is known by across runs; `None` for a memory source. +fn request_key(request: &Request) -> Option<victory_gpu::texture_book::Key> { + if request.options & MEMORY_SOURCE != 0 || request.source.is_null() { + return None; + } + // SAFETY: a file object we created; the title keeps it open. + let file = unsafe { &*request.source.cast::<Instance<File>>() }.state.key; + Some(victory_gpu::texture_book::Key { + file, + offset: request.offset, + source_size: request.source_size, + dest_size: request.destination_size, + options: request.options, + }) +} + +/// A request finished well: the texture book is told where its bytes are +/// in title memory, so that a texture it filled is made ready for the card +/// at once (`victory_gpu::texture_book`). +fn landed(request: &Request) { + let len = if request.options & (ZLIB | BCPACK) != 0 { request.destination_size } else { request.source_size } as usize; + let key = request_key(request); + let at = if request.options & PAGE_DESTINATION == 0 { + request.destination as usize + } else if len >= 4096 { + // Where the title sees the pages written: one run covering them all. + let offset = (request.page_offset & 0xffff) as usize; + let pages = read_list(request.destination.cast(), offset, len); + super::xmem::shown_at(&pages, offset, len).into_iter().find(|&(_, n)| n >= len).map_or(0, |(at, _)| at) + } else { + 0 + }; + victory_gpu::texture_book::request_done(key, at, len); +} + /// Inflates a zlib stream into `out`, returning the bytes written. A stream /// that ends short of `out` passes: the title's chunks fill it exactly, and /// nothing says that is required. diff --git a/crates/victory-hle/src/modules/fidelityfx.rs b/crates/victory-hle/src/modules/fidelityfx.rs index fd89a79ce..2925933d1 100644 --- a/crates/victory-hle/src/modules/fidelityfx.rs +++ b/crates/victory-hle/src/modules/fidelityfx.rs @@ -187,11 +187,17 @@ fn contexts<T>(f: impl FnOnce(&mut HashMap<usize, Created>) -> T) -> T { /// divides by zero at its first upscaling (2026-11-26, 4070 SUPER). const SHIPPING_MAX_OUTPUT: [u32; 2] = [1920, 1080]; const SHIPPING_MAX_RENDER: [u32; 2] = [1280, 720]; +/// The legacy allocation's render size, which the shipping FSR4 accepts too +/// (DLAA: rendered at the output size). Made smaller than this, the title's +/// queries on the context disagree with the sizes it asked for and it breaks +/// into its crash handler at start (2026-11-27, VICTORY_DLSS_MODE=dlaa). +const SHIPPING_LEGACY_RENDER: [u32; 2] = [1920, 1080]; /// The sizes the title's shipping FSR4 accepts for a context, if `render` and -/// `output` are not those: (render, output). +/// `output` are not ones it accepts: (render, output). fn shipping_sizes(render: [u32; 2], output: [u32; 2]) -> Option<([u32; 2], [u32; 2])> { - ((render, output) != (SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT)).then_some((SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT)) + let accepted = output == SHIPPING_MAX_OUTPUT && (render == SHIPPING_MAX_RENDER || render == SHIPPING_LEGACY_RENDER); + (!accepted).then_some((SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT)) } extern "C" fn ffxCreateContext(context: *mut *mut c_void, desc: *mut Header, memory: *const c_void) -> u32 { @@ -476,6 +482,7 @@ mod tests { assert_eq!(shipping_sizes([2560, 1440], [2560, 1440]), shipping); assert_eq!(shipping_sizes([1280, 720], [2560, 1440]), shipping); assert_eq!(shipping_sizes([1280, 720], [1920, 1080]), None); + assert_eq!(shipping_sizes([1920, 1080], [1920, 1080]), None); } struct Fixed; diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 7a2c4a82c..8bea8992b 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -400,6 +400,10 @@ pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { const PAGE: usize = 64 << 10; +// Physical pages from sections of at most +// `VICTORY_SECTION_MB` MiB (off unless set). +mod section_mb; + struct Section { handle: HANDLE, pages: usize, @@ -688,61 +692,25 @@ pub extern "system" fn XMemAllocatePhysicalPages( } // SAFETY: checked non-null. let n = unsafe { *count }; - let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else { - return 0; - }; - // A pagefile-backed section of `size` bytes, its pages committed when - // first mapped or written (`commit`): the title asks for 6.1 - // GiB at once, which a busy host often cannot commit (error 1450). - // SAFETY: plain section creation. - let handle = unsafe { - CreateFileMappingW( - INVALID_HANDLE_VALUE, - std::ptr::null(), - // Under Wine a committed section is a sparse file, free until - // touched, and committing a reserved one page by page costs a - // wineserver request each that scans every range committed so - // far: commit it whole there. - PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, - (size as u64 >> 32) as u32, - size as u32, - std::ptr::null(), - ) - }; - if handle.is_null() { - let error = std::io::Error::last_os_error(); - tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); - // SAFETY: checked non-null. - unsafe { count.write(0) }; + if n.checked_mul(PAGE).filter(|&s| s > 0).is_none() { return 0; } + // One section for the whole request unless `VICTORY_SECTION_MB` asks + // for smaller ones ([`section_mb`]). + let first = match section_mb::allocate_physical(n, section_mb::section_pages()) { + Ok(first) => first, + Err(error) => { + tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); + // SAFETY: checked non-null. + unsafe { count.write(0) }; + return 0; + } + }; tracing::debug!( n, flags = format_args!("{flags:#x}"), "XMemAllocatePhysicalPages" ); - // For the GPU side's in-place census: only a committed section can be - // opened as a host heap. - victory_gpu::title_memory_section(handle as usize, size as u64, on_wine()); - let section = Arc::new(Section { - handle, - pages: n, - window: std::sync::OnceLock::new(), - committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), - }); - let mut table = page_table_mut(); - let first = table.next_page; - table.next_page += n * FRAMES; - for index in 0..n { - let slice = Slice { - section: section.clone(), - index, - }; - table.pages.insert(first + index * FRAMES, slice); - } - // Title memory is touched without our locks: a fault there may wait for - // a mapping call, which takes them. - drop(table); for index in 0..n { // SAFETY: the title passes room for `n` page numbers. unsafe { pages.add(index).write(first + index * FRAMES) }; @@ -1143,13 +1111,6 @@ pub(crate) fn lift_thread() { } } -/// Renderer port 1 (`VICTORY_PORT_CONSTANTS=1`; the GPU side's half is -/// `victory_gpu`'s `port`): read here for xmem's part, [`arrange`]. -fn port_on() -> bool { - static ON: LazyLock<bool> = LazyLock::new(|| std::env::var("VICTORY_PORT_CONSTANTS").is_ok_and(|v| v.trim() == "1")); - *ON -} - /// The title's reservations of 64 KiB pages for 32-bit graphics memory: /// base and bytes (one, of 185 MB, in Grand Theft Auto VI). static LOW_RESERVATIONS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); @@ -1263,9 +1224,9 @@ fn map_pages(address: *mut c_void, n: usize, pages: *const usize, lazy: bool) -> // the mapping call that holds them. // SAFETY: the title passes `n` page numbers, or null. let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); - if port_on() - && let Some(pages) = &pages - { + // Renderer port 1 (always on; the GPU side's half is `victory_gpu`'s + // `port`): the 32-bit heap's pages one stretch of their section. + if let Some(pages) = &pages { arrange(base, pages); } let mut costed = Costed::begin(Some(n)); diff --git a/crates/victory-hle/src/modules/xmem/section_mb.rs b/crates/victory-hle/src/modules/xmem/section_mb.rs new file mode 100644 index 000000000..ec72617f9 --- /dev/null +++ b/crates/victory-hle/src/modules/xmem/section_mb.rs @@ -0,0 +1,432 @@ +//! Physical pages from sections of at most `VICTORY_SECTION_MB` MiB (unset, +//! 0 or not a number: one section for each request, as before). +//! +//! Port of vilocity 0f44a1706 (voidopcode), whose `xmem.rs` this tree's +//! matches; tests after KainanP ee8b92e14 and Xeltax a8c223149. The finding +//! and the cure are RyanCase94's and CuteBooty's (fxceless/victory-fork#1089, +//! #1274). +//! +//! The title asks for its 6.1 GiB of pages in one call and maps them a 64 KiB +//! page at a time: one section with views by the hundred thousand. Windows' +//! worker that rebuilds large pages trades a section's pages one at a time, +//! walks the section's views for each and holds the section's lock meanwhile, +//! which every map and unmap of the title's pages waits for (vilocity, +//! moving through the world: maps of 114 us and unmaps of 182 us each, 848 ms +//! of mapping calls a second; in sections of 2 MiB 11 and 3 us, 117 ms). +//! +//! What goes by sections sees more of them, and nothing else changes: a run +//! of pages for a mapping or a write ends at a section's end as it did at a +//! request's (`runs`), so a title mapping over a bound is two views and a +//! DirectStorage destination over one is not given a window in place +//! (`page_window`) and is written run by run through `write_physical`. Each +//! section keeps its own whole view (`Section::window`) and is closed, and the +//! GPU side told (`title_memory_section_gone`), when its last page goes. +//! +//! Renderer port 1 (`VICTORY_PORT_CONSTANTS=1`) needs the 32-bit heap's +//! pages to be one stretch of one section. With this switch set they are +//! not: `arrange` warns and leaves them where they are, and the heap +//! stays on the copy path. Measured with the port off. + +use super::*; + +/// The most pages one section holds; `usize::MAX` for no limit (one section +/// for each request, as before). +pub(super) fn section_pages() -> usize { + static PAGES: LazyLock<usize> = LazyLock::new(|| { + let pages = pages_per_section(std::env::var("VICTORY_SECTION_MB").ok().as_deref()); + if pages != usize::MAX { + tracing::info!( + mb = pages * PAGE / MIB, + pages, + "physical pages: a request is made of sections of at most this many MiB (VICTORY_SECTION_MB)" + ); + } + pages + }); + *PAGES +} + +/// [`section_pages`] for a value of `VICTORY_SECTION_MB`: whole MiB. +pub(super) fn pages_per_section(mb: Option<&str>) -> usize { + match mb + .and_then(|mb| mb.trim().parse::<usize>().ok()) + .map_or(0, |mb| mb.saturating_mul(MIB / PAGE)) + { + 0 => usize::MAX, + pages => pages, + } +} + +/// Makes `n` physical pages (`n > 0`) in pagefile-backed sections of at most +/// `per` pages each, enters them in the page table and numbers them +/// consecutively, as one request's; the first page's number. The host's +/// error, with nothing made (the sections made so far close), if it refuses +/// a section. +pub(super) fn allocate_physical(n: usize, per: usize) -> std::io::Result<usize> { + if n.checked_mul(PAGE).is_none_or(|size| size == 0) { + return Err(std::io::ErrorKind::InvalidInput.into()); + } + let per = per.max(1); + let mut sections: Vec<Arc<Section>> = Vec::with_capacity(n.div_ceil(per)); + let mut made = 0; + while made < n { + let pages = per.min(n - made); + let size = pages * PAGE; + // A pagefile-backed section of `size` bytes, its pages committed when + // first mapped or written (`commit`): the title asks for 6.1 GiB at + // once, which a busy host often cannot commit (error 1450). + // SAFETY: plain section creation. + let handle = unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + // Under Wine a committed section is a sparse file, free until + // touched, and committing a reserved one page by page costs a + // wineserver request each that scans every range committed so + // far: commit it whole there. + PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, + (size as u64 >> 32) as u32, + size as u32, + std::ptr::null(), + ) + }; + if handle.is_null() { + // Read before the sections made so far close (`sections` drops). + return Err(std::io::Error::last_os_error()); + } + sections.push(Arc::new(Section { + handle, + pages, + window: std::sync::OnceLock::new(), + committed: (0..pages.div_ceil(64)).map(|_| AtomicU64::new(0)).collect(), + })); + made += pages; + } + for section in §ions { + // For the GPU side's in-place census: only a committed section can be + // opened as a host heap. + let bytes = (section.pages * PAGE) as u64; + victory_gpu::title_memory_section(section.handle as usize, bytes, on_wine()); + } + let mut table = page_table_mut(); + let first = table.next_page; + table.next_page += n * FRAMES; + let mut number = first; + for section in §ions { + for index in 0..section.pages { + let slice = Slice { + section: section.clone(), + index, + }; + table.pages.insert(number, slice); + number += FRAMES; + } + } + // Title memory is touched without our locks: a fault there may wait for + // a mapping call, which takes them. + drop(table); + Ok(first) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `n` pages of one new request, in sections of at most `per` pages. + fn allocate_in(n: usize, per: usize) -> Vec<usize> { + let first = allocate_physical(n, per).expect("allocated"); + (0..n).map(|k| first + k * FRAMES).collect() + } + + fn slices(pages: &[usize]) -> Vec<Slice> { + let table = page_table(); + pages.iter().map(|p| table.pages[p].clone()).collect() + } + + /// The bytes of one page, through a view of our own. + fn page_bytes(page: usize) -> Vec<u8> { + let slice = page_table().pages.get(&page).cloned().expect("known page"); + View::map(&slice, 1).expect("mapped").bytes().to_vec() + } + + fn state(address: *const c_void) -> u32 { + // SAFETY: plain data; zero is a valid value. + let mut info: BasicInformation = unsafe { std::mem::zeroed() }; + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + assert_eq!(XMemVirtualQuery(process, address, &mut info), 1); + info.host.State + } + + fn reserve(n: usize) -> *mut c_void { + let kind = MEM_RESERVE | PAGES_64K; + let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, kind, 0, PAGE_READWRITE); + assert!(!at.is_null()); + at + } + + /// The title's views in `[p, p + n pages)`, in pages each. + fn views_in(p: *mut c_void, n: usize) -> Vec<usize> { + let start = p as usize; + physical().views.range(start..start + n * PAGE).map(|(_, (len, _))| len / PAGE).collect() + } + + #[test] + fn section_sizes_come_from_the_switch() { + for off in [None, Some(""), Some("0"), Some("two"), Some("-2")] { + assert_eq!(pages_per_section(off), usize::MAX, "{off:?}"); + } + assert_eq!(pages_per_section(Some("1")), 16); + assert_eq!(pages_per_section(Some(" 2 ")), 32); + assert!(allocate_physical(0, 32).is_err()); + } + + /// (KainanP ee8b92e14) 33 pages: one section, or 2 MiB and one page; + /// numbered as one request either way; written and mapped over the bound. + #[test] + fn sections_hold_at_most_the_pages_asked() { + let runs_of = |pages: &[usize]| { + runs(pages, 0, pages.len() * PAGE).map(|r| r.iter().map(|&(_, n)| n).collect::<Vec<_>>()) + }; + let whole = allocate_in(33, pages_per_section(None)); + let split = allocate_in(33, pages_per_section(Some("2"))); + assert_eq!(runs_of(&whole), Some(vec![33])); + assert_eq!(runs_of(&split), Some(vec![32, 1])); + for pages in [&whole, &split] { + assert!(pages.windows(2).all(|p| p[1] == p[0] + FRAMES)); + } + assert_eq!(XMemFreePhysicalPages(33, whole.as_ptr()), 1); + + // The last byte of the first section and the first of the second: no + // window in place, but written all the same. + let offset = 32 * PAGE - 1; + assert!(page_window(&split, offset, 2).is_none()); + assert!(page_window(&split, offset, 1).is_some()); + assert!(write_physical(&split, offset, &[17, 29])); + assert_eq!(page_bytes(split[31])[PAGE - 1], 17); + assert_eq!(page_bytes(split[32])[0], 29); + + // Mapped in one call, the pages show as one range (two views). + let at = reserve(33); + assert_eq!(XMemMapPhysicalPages(at, 33, split.as_ptr()), at); + assert_eq!(views_in(at, 33), [32, 1]); + // SAFETY: the 33 pages are mapped read-write. + unsafe { + assert_eq!(at.cast::<u8>().byte_add(offset).read(), 17); + assert_eq!(at.cast::<u8>().byte_add(offset + 1).read(), 29); + at.cast::<u8>().byte_add(33 * PAGE - 1).write(41); + } + assert_eq!(page_bytes(split[32])[PAGE - 1], 41); + assert_eq!(XMemMapPhysicalPages(at, 33, std::ptr::null()), at); + assert_eq!(state(at), MEM_RESERVE); + assert_eq!(XMemFreePhysicalPages(33, split.as_ptr()), 1); + } + + /// (vilocity 0f44a1706) 70 pages in 2 MiB: sections of 32, 32 and 6, each + /// page its section's own slice; a DirectStorage-sized write over a + /// section's end lands whole. When the pages go, every section closes. + #[test] + fn a_request_is_made_of_sections_of_two_mebibytes() { + let pages = allocate_in(70, pages_per_section(Some("2"))); + let held = slices(&pages); + let sized = |i: usize| if i < 64 { 32 } else { 6 }; + assert!(held.iter().enumerate().all(|(i, s)| s.index == i % 32 && s.section.pages == sized(i))); + assert!(Arc::ptr_eq(&held[0].section, &held[31].section)); + assert!(!Arc::ptr_eq(&held[31].section, &held[32].section)); + let data: Vec<u8> = (0..3 * PAGE).map(|i| (i % 251) as u8).collect(); + assert!(page_window(&pages, 30 * PAGE + 7, 3 * PAGE).is_none()); + assert!(write_physical(&pages, 30 * PAGE + 7, &data)); + let read: Vec<u8> = pages[30..34].iter().flat_map(|&p| page_bytes(p)).collect(); + assert_eq!(&read[7..7 + 3 * PAGE], &data[..]); + let gone: Vec<std::sync::Weak<Section>> = + [0, 32, 64].iter().map(|&i| Arc::downgrade(&held[i].section)).collect(); + drop(held); + assert_eq!(XMemFreePhysicalPages(70, pages.as_ptr()), 1); + assert!(gone.iter().all(|s| s.upgrade().is_none()), "every section closed"); + } + + /// (Xeltax a8c223149) Five pages in sections of two: views end at a + /// section's end; bytes written over the bounds through the title's views + /// land in the right pages; an unmapping inside the second section and + /// the GPU's page-mapping copies show their own section's pages. + #[test] + fn an_allocation_in_several_sections_is_mapped_and_written_across_their_bounds() { + let pages = allocate_in(5, 2); + let groups = runs(&pages, 0, 5 * PAGE).expect("known pages"); + assert_eq!(groups.iter().map(|&(_, n)| n).collect::<Vec<_>>(), [2, 2, 1]); + let from_start = groups.iter().all(|(slice, _)| slice.index == 0); + assert!(from_start, "each run from its section's start"); + assert!(page_window(&pages, 2 * PAGE + 7, PAGE).is_some()); + assert!(page_window(&pages, PAGE, 2 * PAGE).is_none()); + let data: Vec<u8> = (0..3 * PAGE + 100).map(|i| (i % 251) as u8 ^ 0x5a).collect(); + let offset = PAGE / 2; + assert!(write_physical(&pages, offset, &data)); + let seen: Vec<u8> = pages.iter().flat_map(|&p| page_bytes(p)).collect(); + assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset"); + assert_eq!(seen[offset..offset + data.len()], data[..]); + assert!(seen[offset + data.len()..].iter().all(|&b| b == 0), "after"); + + let (a, b) = (reserve(5), reserve(2)); + let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(a, 5, pages.as_ptr()), a); + assert_eq!(views_in(a, 5), [2, 2, 1]); + // SAFETY: all five pages are mapped read-write at `a`. + unsafe { + assert_eq!(std::slice::from_raw_parts(a.cast::<u8>(), 5 * PAGE), &seen[..]); + at(a, 2).cast::<u8>().sub(1).write_bytes(0xee, 2); + at(a, 4).cast::<u8>().sub(1).write_bytes(0xdd, 2); + } + assert_eq!(page_bytes(pages[1])[PAGE - 1], 0xee); + assert_eq!(page_bytes(pages[2])[0], 0xee); + assert_eq!(page_bytes(pages[3])[PAGE - 1], 0xdd); + assert_eq!(page_bytes(pages[4])[0], 0xdd); + // Where the pages show, over a bound: one run of addresses. + assert_eq!(shown_at(&pages, PAGE, 3 * PAGE), vec![(at(a, 1) as usize, 3 * PAGE)]); + // The second section's second page unmapped: its first stays. + assert_eq!(XMemMapPhysicalPages(at(a, 3), 1, std::ptr::null()), at(a, 3)); + assert_eq!(views_in(a, 5), [2, 1, 1]); + assert_eq!(state(at(a, 3)), MEM_RESERVE); + // SAFETY: still mapped. + assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 0xee); + assert!(map_alias(b as u64, at(a, 4) as u64, PAGE as u64)); + assert!(map_alias(at(b, 1) as u64, at(a, 2) as u64, PAGE as u64)); + // SAFETY: both mapped read-write. + unsafe { + assert_eq!(b.cast::<u8>().read(), 0xdd); + assert_eq!(at(b, 1).cast::<u8>().read(), 0xee); + } + for (p, n) in [(a, 5), (b, 2)] { + assert_eq!(XMemMapPhysicalPages(p, n, std::ptr::null()), p); + } + assert!(shown_at(&pages, 0, 5 * PAGE).is_empty()); + assert_eq!(XMemFreePhysicalPages(5, pages.as_ptr()), 1); + } + + /// The title's own call cuts a request as the switch says: unset (the + /// default), one section of 33 pages, as before the switch. + #[test] + fn the_title_call_cuts_by_the_switch() { + let (mut pages, mut given) = (vec![0; 33], 33); + assert_eq!(XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), 1); + assert_eq!(given, 33); + let per = section_pages().min(33); + let expected: Vec<usize> = (0..33).step_by(per).map(|first| per.min(33 - first)).collect(); + let groups = runs(&pages, 0, 33 * PAGE).expect("known pages"); + assert_eq!(groups.iter().map(|&(_, n)| n).collect::<Vec<_>>(), expected); + if std::env::var_os("VICTORY_SECTION_MB").is_none() { + assert_eq!(expected, [33], "off by default"); + } + assert_eq!(XMemFreePhysicalPages(33, pages.as_ptr()), 1); + } + + /// (KainanP ee8b92e14) Remapping single pages of a large request while + /// other memory is made and freed: one section per request against 2 MiB + /// sections, no title needed. Ignored: it maps 4 GiB and runs for a + /// minute. `cargo test --release -p victory-hle --lib physical_remap_bench + /// -- --ignored --nocapture --test-threads=1`; `VICTORY_SECTION_BENCH=<MiB>, + /// <seconds>,<rounds>,<pressure MiB>` changes the defaults `4096,10,3,2048`. + #[test] + #[ignore = "benchmark"] + fn physical_remap_bench() { + use std::sync::atomic::AtomicBool; + use std::time::{Duration, Instant}; + + let knobs: Vec<usize> = std::env::var("VICTORY_SECTION_BENCH") + .unwrap_or_default() + .split(',') + .filter_map(|v| v.trim().parse().ok()) + .collect(); + let knob = |i: usize, default: usize| knobs.get(i).copied().unwrap_or(default); + let (mib, seconds, rounds, pressure) = (knob(0, 4096), knob(1, 10), knob(2, 3), knob(3, 2048)); + let n = mib * MIB / PAGE; + let percentile = |v: &mut Vec<f64>, p: usize| { + v.sort_by(f64::total_cmp); + v[(v.len() * p / 100).min(v.len() - 1)] + }; + let name = |mb: &str| if mb.is_empty() { "one".to_string() } else { format!("{mb} MiB") }; + let mut results: Vec<(&str, Vec<[f64; 5]>)> = vec![("", vec![]), ("2", vec![])]; + for round in 0..rounds { + for (mb, rows) in &mut results { + let pages = allocate_in(n, pages_per_section(Some(mb))); + let at = reserve(n); + let base = at as usize; + // A view a page, each page touched, as the title maps its pool. + for (k, page) in pages.iter().enumerate() { + let page_at = (base + k * PAGE) as *mut c_void; + assert_eq!(XMemMapPhysicalPages(page_at, 1, page), page_at); + for b in (0..PAGE).step_by(4096) { + // SAFETY: mapped read-write just now. + unsafe { page_at.cast::<u8>().byte_add(b).write(1) }; + } + } + let stop = AtomicBool::new(false); + let mut calls = Vec::new(); + std::thread::scope(|scope| { + // Another user of memory: made, touched and freed again. + scope.spawn(|| { + while pressure > 0 && !stop.load(Ordering::Relaxed) { + let mut block = vec![0u8; pressure * MIB]; + for b in block.iter_mut().step_by(4096) { + *b = 1; + } + std::hint::black_box(&block); + } + }); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as usize % n + }; + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(seconds as u64) { + let (k, page) = (next(), pages[next()]); + let page_at = (base + k * PAGE) as *mut c_void; + let t = Instant::now(); + assert_eq!(XMemMapPhysicalPages(page_at, 1, &page), page_at); + calls.push(t.elapsed().as_secs_f64() * 1e6); + // SAFETY: mapped read-write just now. + unsafe { page_at.cast::<u8>().write(2) }; + } + stop.store(true, Ordering::Relaxed); + }); + let slow: Vec<f64> = calls.iter().copied().filter(|&us| us >= 1000.0).collect(); + let row = [ + calls.len() as f64 / seconds as f64, + percentile(&mut calls, 50), + percentile(&mut calls, 99), + slow.len() as f64, + slow.iter().sum::<f64>() / 1000.0, + ]; + println!( + "round {round}, sections {}: {:.0} remaps/s, median {:.1} us, p99 {:.1} us, {} of 1 ms or more ({:.0} ms)", + name(mb), + row[0], + row[1], + row[2], + row[3], + row[4] + ); + rows.push(row); + assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at); + assert_eq!(XMemFreePhysicalPages(n, pages.as_ptr()), 1); + } + } + for (mb, rows) in &results { + let median = |i: usize| { + let mut v: Vec<f64> = rows.iter().map(|r| r[i]).collect(); + percentile(&mut v, 50) + }; + println!( + "median of {rounds} rounds, sections {}: {:.0} remaps/s, median {:.1} us, p99 {:.1} us, {} of 1 ms or more ({:.0} ms)", + name(mb), + median(0), + median(1), + median(2), + median(3), + median(4) + ); + } + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index c24e3484c..9007c1bea 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -157,7 +157,8 @@ impl Host { ShaderVisibility: vis, }) .collect(); - // By slot, then kind: 0 CBV, 1 SRV, 2 UAV. + // By slot, then kind: 0 constant buffer (read as raw bytes, an SRV + // too), 1 SRV, 2 UAV. let mut views: Vec<(u8, u8)> = stages .iter() .flat_map(|(s, _)| { @@ -171,9 +172,8 @@ impl Host { for (slot, kind) in views { params.push(D3D12_ROOT_PARAMETER1 { ParameterType: match kind { - 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, 2 => D3D12_ROOT_PARAMETER_TYPE_UAV, - _ => D3D12_ROOT_PARAMETER_TYPE_CBV, + _ => D3D12_ROOT_PARAMETER_TYPE_SRV, }, Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { @@ -624,8 +624,9 @@ pub enum Root { sampler: bool, index: usize, }, - /// A root CBV (or with `srv`, a root SRV) over a buffer of these - /// dwords ([`Host::dispatch`] only). + /// A root constant buffer (or with `srv`, a root SRV) over a buffer of + /// these dwords ([`Host::dispatch`] only); both are bound as raw root + /// SRVs (translated shaders read constant buffers as raw bytes). View { srv: bool, data: Vec<u32>, @@ -1405,11 +1406,23 @@ impl Host { uavs.push((t, Some((w, h)), 1, rb)); } View::Cbv(data) => { + // Translated shaders read a heap constant buffer as a + // structured buffer of dwords, as the host makes it. let b = upload(data)?; - dev.CreateConstantBufferView( - Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { - BufferLocation: b.GetGPUVirtualAddress(), - SizeInBytes: (data.len() * 4).next_multiple_of(256) as u32, + dev.CreateShaderResourceView( + &b, + Some(&D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: data.len().max(1) as u32, + StructureByteStride: 4, + Flags: D3D12_BUFFER_SRV_FLAG_NONE, + }, + }, }), at, ); @@ -1486,14 +1499,11 @@ impl Host { at.ptr += (index * size) as u64; list.SetComputeRootDescriptorTable(*param, at); } - Root::View { srv, data } => { + Root::View { data, .. } => { + // Root constant buffers are raw views too. let b = upload(data)?; let va = b.GetGPUVirtualAddress(); - if *srv { - list.SetComputeRootShaderResourceView(*param, va); - } else { - list.SetComputeRootConstantBufferView(*param, va); - } + list.SetComputeRootShaderResourceView(*param, va); keep.push(b); } } diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index b32afa897..51cabe4b6 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -251,26 +251,64 @@ impl<'a> Lower<'a> { (handle, byte, mapped) } - /// The second 64 bytes of a 128-byte node: in a page, and in a copy, of - /// their own maybe. Goes on in another block. - fn bvh_second_half(&mut self, at: NodeAt) -> NodeAt { + /// Reads the 12 dwords at offset +64 of a 128-byte node and returns + /// `(words, mapped)`. On `NodeAt::Memory`, skips the second directory + /// lookup when the 64-byte-aligned second half lies in the same 64 KiB page. + fn bvh_second_half_words(&mut self, at: NodeAt) -> (Vec<V>, V) { match at { NodeAt::Buffer { handle, byte } => { let size = self.s.m.i32(64); let byte = self.s.m.bin(self.cur, Bin::Add, byte, size); - NodeAt::Buffer { handle, byte } + let second = NodeAt::Buffer { handle, byte }; + let i1t = self.s.m.int(1); + let one = self.s.m.int_const(i1t, 1); + (self.bvh_node_words(second, None, 0, 12), one) } - NodeAt::Memory { low, high, .. } => { - let (low, high) = self.address_plus(low, high, 64); - // Every lane in this block runs the instruction. - let (handle, byte, mapped) = self.bvh_memory(low, high, None); - NodeAt::Memory { - handle, - byte, - low, - high, - mapped, + NodeAt::Memory { handle, byte, low, high, mapped } => { + let head = self.cur; + let page_mask = self.s.m.i32(0xFFFF); + let limit = self.s.m.i32(0xFFC0); + let within = self.s.m.bin(head, Bin::And, low, page_mask); + let cross = self.s.m.cmp(head, pred::IUGE, within, limit); + let (same_block, cross_block, join) = + (self.s.m.new_block(), self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(head, Term::CondBr(cross, cross_block, same_block)); + + self.cur = same_block; + let k64 = self.s.m.i32(64); + let same_byte = self.s.m.bin(same_block, Bin::Add, byte, k64); + let same_words = self.bvh_node_words( + NodeAt::Memory { handle, byte: same_byte, low, high, mapped }, + None, + 0, + 12, + ); + let same_end = self.cur; + self.s.m.terminate(same_end, Term::Br(join)); + + self.cur = cross_block; + let (low2, high2) = self.address_plus(low, high, 64); + let (h2, b2, m2) = self.bvh_memory(low2, high2, None); + let cross_words = self.bvh_node_words( + NodeAt::Memory { handle: h2, byte: b2, low: low2, high: high2, mapped: m2 }, + None, + 0, + 12, + ); + let cross_end = self.cur; + self.s.m.terminate(cross_end, Term::Br(join)); + + self.cur = join; + let (i32t, i1t) = (self.s.t.i32, self.s.m.int(1)); + let mut merged = Vec::with_capacity(12); + for (sw, cw) in same_words.into_iter().zip(cross_words) { + let phi = self.s.m.phi(join, i32t); + self.s.m.set_phi(phi, vec![(sw, same_end), (cw, cross_end)]); + merged.push(phi); } + let mapped_phi = self.s.m.phi(join, i1t); + self.s.m.set_phi(mapped_phi, vec![(mapped, same_end), (m2, cross_end)]); + (merged, mapped_phi) } } } @@ -346,8 +384,18 @@ impl<'a> Lower<'a> { self.cur = wide_block; let k16 = self.s.m.i32(16); let mut words = self.bvh_node_words(at, None, 16, 12); - let second = self.bvh_second_half(at); - words.extend(self.bvh_node_words(second, None, 0, 12)); + let (second_words, second_mapped) = self.bvh_second_half_words(at); + words.extend(second_words); + let second = match at { + NodeAt::Buffer { handle, byte } => NodeAt::Buffer { handle, byte }, + NodeAt::Memory { handle, byte, low, high, .. } => NodeAt::Memory { + handle, + byte, + low, + high, + mapped: second_mapped, + }, + }; let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect(); // (The look for the second half goes on in another block.) let wide_block = self.cur; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3aa6a72c5..5a4aba0a3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -48,6 +48,23 @@ enum Val { Missing(Why), } +/// How a constant buffer is read ([`Lower::constant_view`]). +#[derive(Debug, Clone, Copy)] +enum ConstantView { + /// As raw bytes through this handle (a raw view of the host): byte 0 is + /// the title's address. With a size, bytes at or past it read zeros by + /// the code's own test (a root view has no size); without one, the + /// view's own size bounds the reads (zeros past it). + Raw(V, Option<u32>), + /// As a structured buffer of dwords (stride 4) through this handle: the + /// view slot holds a structured view whose first element is the title's + /// address (any 4 bytes) and whose size is the CBV's (zeros past it). + Structured(V), + /// Through a constant buffer view (a descriptor neither a root view nor + /// in the view heap: none the host binds). + Cbuffer(V), +} + pub(crate) struct Lowered { pub dxil: Vec<u8>, /// Bit n: immediate sampler n is a comparison sampler. @@ -114,9 +131,17 @@ fn counted_in_threads(parts: &Parts) -> bool { /// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory /// bc3cd4b0, which does so for two of the programs by their digests). pub(super) fn lower_counted(parts: &Parts, counted: bool) -> Result<Lowered, ShaderError> { + lower_with_options(parts, counted, &[]) +} + +pub(super) fn lower_with_lds_seed(parts: &Parts, seed: &[u32]) -> Result<Lowered, ShaderError> { + lower_with_options(parts, false, seed) +} + +fn lower_with_options(parts: &Parts, counted: bool, lds_seed: &[u32]) -> Result<Lowered, ShaderError> { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad).run(counted) { + match Lower::new(parts, &bad).run(counted, lds_seed) { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -2599,13 +2624,37 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::Or, first, total)) } - fn run(mut self, counted: bool) -> Result<Lowered, Stop> { + fn run(mut self, counted: bool, lds_seed: &[u32]) -> Result<Lowered, Stop> { let p = self.x.p; // A host group has 32 KiB of LDS (D3D12): the program's LDS with the meetings' and // exchanges' dwords past it must fit (`CS_CollectTriangles_Meshlets` uses all 32 KiB). if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS { return Err(unsupported(0, "LDS for the console waves' meetings past the host's 32 KiB")); } + if !lds_seed.is_empty() { + let StageIo::Cs(cs) = self.x.native.io else { + return Err(unsupported(0, "LDS initialization outside compute")); + }; + if lds_seed.len() > (cs.lds_bytes() / 4) as usize { + return Err(unsupported(0, "LDS initialization past the guest allocation")); + } + let entry = self.s.entry; + self.cur = entry; + let thread = self.s.op(entry, "flattenedThreadIdInGroup.i32", Attr::ReadNone, self.s.t.i32, 96, &[]); + let zero = self.s.m.i32(0); + let first = self.s.m.cmp(entry, pred::EQ, thread, zero); + let branch = self.begin_guarded(Some(first)); + let lds = self.s.lds(); + for (index, &word) in lds_seed.iter().enumerate() { + let index = self.s.m.i32(index as u32); + let ptr = self.s.m.element(self.cur, lds, index); + let value = self.s.m.i32(word); + self.s.m.store(self.cur, ptr, value); + } + self.end_guarded(branch, &[]); + self.group_sync(self.cur); + self.s.entry = self.cur; + } if counted { // Before anything else, so that wave counts, reads of the first // lane and stores know only the lanes that run. @@ -3429,13 +3478,14 @@ impl<'a> Lower<'a> { if let Some(g) = guard { missing = self.s.m.bin(c, Bin::And, missing, g); } - let places = k(self, MEMORY_FAULTS - 1); + let mask = k(self, MEMORY_FAULTS - 1); let faults = self.s.root_uav_handle(SLOT_FAULTS); let noting = self.begin_guarded(Some(missing)); let c = self.cur; - let place = self.s.m.bin(c, Bin::URem, page, places); + let masked = self.s.m.bin(c, Bin::And, page, mask); let one = k(self, 1); - let place = self.s.m.bin(c, Bin::Add, place, one); + let zero_slot = self.s.m.cmp(c, pred::EQ, masked, zero); + let place = self.s.m.select(c, zero_slot, one, masked); let k2 = k(self, 2); let place = self.s.m.bin(c, Bin::Shl, place, k2); let void = self.s.t.void; @@ -3459,9 +3509,9 @@ impl<'a> Lower<'a> { }; let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); - // The builder's threads read what others of the dispatch wrote (a - // refit climbs from children to parents): globally coherent. - let coherent = if crate::spill::is_spilled(self.x.native) { 0x4000 } else { 0 }; + // The builder's stores write through to L2; its loads hit L1 and + // reload at the fences around its atomics. + let coherent = if store && crate::spill::is_spilled(self.x.native) { 0x4000 } else { 0 }; let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000 | coherent, 0)); let k64k = k(self, 0xFFFF); let within = self.s.m.bin(c, Bin::And, lo, k64k); @@ -5826,6 +5876,19 @@ impl<'a> Lower<'a> { && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")); + if std::env::var_os("VICTORY_LDS_WHY").is_some() + && matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_swizzle") || name.contains("permute")) + { + eprintln!( + "LDS-WHY {:#x} {name} block={b} split={} all={:?} meet_at={:?} unordered={}", + offset, + self.split_lds, + self.lds_meet.as_ref().map(|(all, _)| all[b]), + self.lds_meet.as_ref().map(|(_, m)| m[b]), + self.lds_unordered.contains(&(b, i)), + ); + } if self.split_lds && matches!(inst.fields, Fields::Ds { .. }) && !(name.starts_with("ds_swizzle") || name.contains("permute")) @@ -6727,13 +6790,13 @@ impl<'a> Lower<'a> { let raw = self.end_guarded(at, &raw); let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero); let at = self.begin_guarded(Some(other)); - let h = self.handle(site, src, false, (13, 0x1_0000))?; + let view = self.constant_view(site, src)?; let mut both = Vec::new(); for (k, &r) in raw.iter().enumerate() { let b = self.cur; let off = self.s.m.i32(4 * k as u32); let a = self.s.m.bin(b, Bin::Add, addr, off); - let x = self.cbuffer_dword(h, a); + let x = self.constant_dword(view, a); both.push((x, r)); } let both = self.end_guarded(at, &both); @@ -6790,7 +6853,18 @@ impl<'a> Lower<'a> { } return Ok(()); } - let h = self.handle(site, src, false, (13, 0x1_0000))?; + let h = match self.constant_view(site, src)? { + ConstantView::Cbuffer(h) => h, + raw => { + for k in 0..count { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.constant_dword(raw, a); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + }; let constant = match addr { V::Const(_) if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() => @@ -7286,6 +7360,125 @@ impl<'a> Lower<'a> { x } + /// How the constant buffer `src` read at `site` is read. Never through a + /// constant buffer view: its address must lie on 256 bytes on the host, + /// the console's constants lie on 16, and the host reads them where the + /// title wrote them (`victory-gpu` `port`) only through views that begin + /// on any 4 bytes: + /// + /// - A root constant buffer: raw bytes through the root SRV `t<slot>` + /// ([`super::shader::Shader::root_constants_handle`]) at the title's + /// address; zeros past [`super::shader::ROOT_CONSTANT_BYTES`]. + /// - One in a table: a structured buffer of dwords through its own slot, + /// which the host makes a structured view (stride 4) of the CBV's bytes + /// (`HostHeap::constant_at`, the mirror's `make_twinned`); zeros past + /// it. No raw twin is needed (NVIDIA's heaps have no room for them). + /// - One picked from the heap by a computed index: where the host keeps + /// raw twins ([`super::shader::raw_views`]), raw bytes through the twin + /// of its slot ([`Lower::raw_twin`]: an index from wrong data meets a + /// null raw view there, not a texture); else as in a table. + fn constant_view(&mut self, site: Site, src: &Source) -> Result<ConstantView, Why> { + if self.root_copy.is_none() + && let Source::Built { address, .. } = src + && let Some(rp) = self.x.native.layout.get(address.param).copied() + && rp.root == RootType::Descriptor + { + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + if matches!(kind, Some(ResourceType::Cbv) | None) { + let h = self.s.root_constants_handle(rp.slot); + return Ok(ConstantView::Raw(h, Some(super::shader::ROOT_CONSTANT_BYTES))); + } + } + // The root parameter kind each leaf's descriptor is loaded through. + let roots: Vec<Option<RootType>> = src + .leaves() + .iter() + .map(|leaf| { + let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = leaf else { + return None; + }; + self.scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .map(|p| p.root) + }) + .collect(); + let tables = roots.iter().all(|r| *r == Some(RootType::Table)); + let in_heap = roots + .iter() + .all(|r| matches!(r, Some(RootType::Table | RootType::ResourceHeap))); + if in_heap && !tables && super::shader::raw_views() != 0 { + let h = self.handle(site, src, false, (11, 0))?; + return Ok(ConstantView::Raw(h, None)); + } + if in_heap { + return Ok(ConstantView::Structured(self.handle(site, src, false, (12, 4))?)); + } + Ok(ConstantView::Cbuffer(self.handle(site, src, false, (13, 0x1_0000))?)) + } + + /// The dword at a computed byte address `a` of a constant buffer read as + /// [`Lower::constant_view`] says. As the console's: the address's low + /// two bits are not looked at. + fn constant_dword(&mut self, view: ConstantView, a: V) -> V { + let (h, most) = match view { + ConstantView::Cbuffer(h) => return self.cbuffer_dword(h, a), + ConstantView::Structured(h) => { + // Element `a / 4`, its only dword. + let c = self.cur; + let two = self.s.m.i32(2); + let element = self.s.m.bin(c, Bin::LShr, a, two); + let zero = self.s.m.i32(0); + let (mask, al) = (self.s.m.i8(1), self.s.m.i32(4)); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, element, zero, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + return self.as_int(x); + } + ConstantView::Raw(h, most) => (h, most), + }; + let c = self.cur; + let dword = self.s.m.i32(!3u32); + let mut at = self.s.m.bin(c, Bin::And, a, dword); + let zero = self.s.m.i32(0); + // A root view has no size: nothing past the bytes a constant buffer + // shows is read at all. + let inside = most.map(|n| { + let n = self.s.m.i32(n); + self.s.m.cmp(c, pred::IULT, at, n) + }); + if let Some(inside) = inside { + at = self.s.m.select(c, inside, at, zero); + } + let (u, mask, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i8(1), self.s.m.i32(4)); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, at, u, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + let x = self.as_int(x); + match inside { + Some(inside) => self.s.m.select(self.cur, inside, x, zero), + None => x, + } + } + /// `channels` channels of the element at byte `off` of raw buffer `h`, /// converted from the GFX10 buffer format `format` as the hardware's /// typed loads do (channels past the format's read 0, 0, 0, 1). @@ -7736,8 +7929,10 @@ impl<'a> Lower<'a> { .find(|u| u.user_data == rp.user_data) .map(|u| u.kind); match (rp.root, kind, props.0) { + // Root constant buffers are read as raw bytes + // (`constant_view`), never through a view of this kind. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => { - Ok(self.s.root_cbv_handle(rp.slot)) + Err("a root constant buffer read through a constant buffer view") } (RootType::Descriptor, Some(ResourceType::Srv), 11) => { Ok(self.s.root_srv_handle(rp.slot)) @@ -7795,9 +7990,11 @@ impl<'a> Lower<'a> { /// for a buffer read as raw bytes, through a table or picked from the /// heap itself (or picked and read as a constant buffer), the host's raw /// twin of that slot ([`super::shader::raw_views`]), whose reads end where - /// the view does. Everything else (textures, typed buffers, tables' - /// constant buffers) stays in place. And whether it is a twin's (inside - /// the host's heap). + /// the view does. Constant buffers (tables' and picked ones) are read as + /// raw bytes this way too ([`Lower::constant_view`]): the host makes the + /// twin of a constant buffer's slot a raw view of its bytes. Everything + /// else (textures, typed buffers) stays in place. And whether it is a + /// twin's (inside the host's heap). /// /// Tables too: a view that does not begin on 16 bytes cannot be raw, and /// a pixel program of the main pass (3711fdad456538a1, stopped at in the @@ -12295,7 +12492,7 @@ impl<'a> Lower<'a> { // A constant buffer read per lane (a dynamically indexed array). // shortcut: the console's CBV descriptor is taken to have a 16-byte // stride, as the vector loads of whole rows suggest. - let h = self.handle(site, src, false, (13, 0x1_0000))?; + let view = self.constant_view(site, src)?; let byte = match index { Some(i) => { let sixteen = self.s.m.i32(16); @@ -12310,7 +12507,7 @@ impl<'a> Lower<'a> { for k in 0..count { let four = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, byte, four); - let x = self.cbuffer_dword(h, a); + let x = self.constant_dword(view, a); self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index e835c2c55..69b72f408 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -25,10 +25,20 @@ //! sampler description). Comparison sampling (added 2026-11-23): an //! immediate sampler it uses has a comparison filter there (bit 0x80); //! a heap sampler it uses must be a comparison sampler on the host. -//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors -//! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter -//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the -//! address the title sets is the buffer's. +//! * **Root CBVs and root SRVs** as root descriptors `t<i>` (raw buffers) +//! in [`ROOT_CBV_SPACE`], `i` the title's root parameter index +//! ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the address the +//! title sets is the buffer's. Constant buffers are read as raw bytes +//! (changed 2026-11-27): a CBV's address must lie on 256 bytes on the host, +//! the console's on 16, and a raw view lets the host read the title's +//! constants where it wrote them. Root ones read zeros past +//! [`ROOT_CONSTANT_BYTES`]. Ones in the view heap are read as structured +//! buffers of dwords through their own slot: the host makes a constant +//! buffer's slot a structured view (`DXGI_FORMAT_UNKNOWN`, stride 4) of +//! the CBV's bytes (size rounded to 256, at most 64 KiB), which begins on +//! any 4 bytes and reads zeros past its end. Ones picked from the heap by +//! a computed index read the raw twin of their slot instead where the +//! host keeps twins ([`raw_views`]). //! * **Vertex fetch** (added 2026-11-23). The title's mesh and //! vertex programs fetch vertices themselves with typed-format loads //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, @@ -123,7 +133,7 @@ pub use sampler::StaticSampler; pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; pub use rect::rect_list_gs; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, ROOT_CONSTANT_BYTES, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; @@ -425,8 +435,11 @@ pub struct HostShader { /// The same samplers decoded, `s<n>` at position n: the static sampler /// descriptions the host's root signature declares. pub static_samplers: Vec<StaticSampler>, - /// Root CBVs the shader reads: root parameter indices, each bound as - /// `b<index>` in [`ROOT_CBV_SPACE`]. + /// Root constant buffers the shader reads: root parameter indices, each + /// read as raw bytes through the root SRV `t<index>` in + /// [`ROOT_CBV_SPACE`] (a root descriptor at the title's address, which + /// needs 4 bytes where a CBV needs 256; zeros past + /// [`ROOT_CONSTANT_BYTES`]). The host binds an SRV there, not a CBV. pub root_cbvs: Vec<u8>, /// Root SRVs (raw buffers) the shader reads: `t<index>` in /// [`ROOT_CBV_SPACE`]. @@ -622,6 +635,25 @@ pub fn emit( // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which // has no barrier, stays on. let wide_option = std::env::var_os("VICTORY_WAVE_WIDE"); + let tiled_water = tiled_water(c); + if tiled_water + && wide_option.as_ref().is_none_or(|v| v == "1") + && matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64) + { + // These shaders share tile depth and select a lane with scalar + // state carried across EXEC branches. Preserve the guest's + // wave-wide decisions throughout the original program, while + // keeping every vector side effect predicated by guest EXEC. + let lowered = (|| { + let wave = structure::structure_wide(p, &guest_wave_branches(st))?; + let res = resource::track(p, &native.layout, native.stage, Some(&wave))?; + emit_program(c, native, p, &wave, io, &res) + })(); + report("tiled water with guest wave branches", &lowered); + if done(&lowered) { + return lowered.map(|(shader, _)| shader); + } + } // Both archived kernels use one logical wave per group and have // validated wave32 PSOs on RTX. Explicit policy wins. // The volumetric light's two tiled programs (`CS_TransmissionVolumetrics_Tiled` @@ -629,21 +661,23 @@ pub fn emit( // an LDS read and write in one lane-branch region, so no other form translates // them on 32-lane hosts and their dispatches were dropped (no volumetric light // or fog on NVIDIA). Widened, they translate (4 and 7 branches taken wave-wide). - // The underwater one (`CS_TransmissionVolumetricsSubmerged`) likewise (29 branches). + // The full volume and portals-only variants also share LDS within one wave. + // Both need the widening retry on wave32 even when the tiled shaders compile. + // The underwater variant needs the same retry. // The triangle clip's heap defragmentation (`vfx_triangleClip:CS_DefragHeap_ // ComputeRelocations`, groups of 128) holds two console waves, which walk the heap // each its own way: their host waves meet per console wave ([`widen`]). (Its // `CS_CollectTriangles_Meshlets`, groups of 1024, does not fit that way: its own LDS // is the host group's whole 32 KiB.) let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64) - && matches!( + && (tiled_water || matches!( c.digest, [0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1] | [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c] - | [0x24, 0x12, 0x6c, 0x14, 0xdc, 0x76, 0x19, 0xb0, 0x82, 0xef, 0x57, 0x12, 0x96, 0x03, 0x88, 0x90] - | [0x70, 0x99, 0xa5, 0x7f, 0xde, 0xd1, 0x42, 0x61, 0x3b, 0x44, 0xf4, 0x10, 0x46, 0x3d, 0x6b, 0xe6] + | [0xc4, 0x0b, 0xd9, 0x53, 0x09, 0x6e, 0x88, 0x25, 0xce, 0x64, 0x50, 0xb5, 0x53, 0xf1, 0x23, 0x5c] + | [0x4f, 0xa5, 0x83, 0x20, 0xd7, 0x61, 0xbf, 0x55, 0x81, 0x20, 0xf9, 0x2c, 0x19, 0xd3, 0x84, 0xaa] | [0xf1, 0xf1, 0x61, 0xe4, 0x7e, 0xef, 0xa3, 0x64, 0x69, 0x18, 0x39, 0xfd, 0x72, 0x06, 0xcc, 0xf6] - ) + )) || matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 128) && c.digest == [0x50, 0xcf, 0x28, 0x32, 0x8b, 0x58, 0x05, 0x3d, 0xa8, 0x9a, 0x8d, 0xa0, 0x1a, 0xa1, 0x23, 0xc6]; let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1"); @@ -781,6 +815,18 @@ pub fn emit( emit_program(c, native, &p, &st, &io, &res).and_then(supported) } +fn guest_wave_branches(st: &structure::Structured) -> std::collections::HashSet<usize> { + st.wave_any.iter().enumerate().filter_map(|(block, kind)| kind.is_some().then_some(block)).collect() +} + +fn tiled_water(c: &Container) -> bool { + matches!( + c.digest, + [0x24, 0x12, 0x6c, 0x14, 0xdc, 0x76, 0x19, 0xb0, 0x82, 0xef, 0x57, 0x12, 0x96, 0x03, 0x88, 0x90] + | [0x70, 0x99, 0xa5, 0x7f, 0xde, 0xd1, 0x42, 0x61, 0x3b, 0x44, 0xf4, 0x10, 0x46, 0x3d, 0x6b, 0xe6] + ) +} + /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane /// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the /// lowering names the blocks where the two host waves must meet and could not @@ -975,7 +1021,7 @@ fn emit_program( } _ => EarlyDepth::NotAsked, }; - let l = lower::lower(&lower::Parts { + let parts = lower::Parts { native, p, st, @@ -985,7 +1031,15 @@ fn emit_program( outputs, prims, mesh_stride, - })?; + }; + let l = if tiled_water(c) && lower::host_max_wave() == 32 { + // Lane (0, 0) initializes these extrema after the depth tests. If + // just that lane has left EXEC, the rest of the tile reduces into + // undefined LDS. Initialize the same max and min before masking. + lower::lower_with_lds_seed(&parts, &[0, u32::MAX]) + } else { + lower::lower(&parts) + }?; let counted = match early { EarlyDepth::NotAsked => None, EarlyDepth::Given => Some(0), diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 5ce292d7b..2e6ff09c8 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -9,10 +9,15 @@ use super::container::{self, Binding, Psv, SigElement}; pub const USER_DATA_SPACE: u32 = 0; /// Where immediate samplers are bound: `s<n>` in this space. pub const SAMPLER_SPACE: u32 = 0; -/// Where root CBVs and SRVs are bound: `b<root parameter index>` and -/// `t<root parameter index>` in this space. +/// Where root views are bound: `t<root parameter index>` (root SRVs, and +/// root constant buffers, which are read as raw bytes too) and +/// `u<root parameter index>` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// The bytes a root constant buffer is read in: 4,096 vectors, as many as +/// a constant buffer view can show. Reads at or past them give zeros. +pub const ROOT_CONSTANT_BYTES: u32 = 64 << 10; + /// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that /// reads buffers through descriptors it picks from the view heap at an /// index it computes (SM 6.6 dynamic resources): a raw buffer of @@ -349,14 +354,19 @@ impl Shader { self.annotate(block, h, 13, u32::MAX) } - /// The handle of the root CBV of root parameter `slot`, made in the - /// entry block. - pub fn root_cbv_handle(&mut self, slot: u8) -> V { + /// The handle of the root constant buffer of root parameter `slot`, + /// read as raw bytes: the root SRV `t<slot>` in [`ROOT_CBV_SPACE`] (a + /// raw buffer), made in the entry block. The host binds it at the + /// title's own address, which needs 4 bytes where a constant buffer + /// view needs 256: constants the title placed on 16 are read where it + /// wrote them (`victory-gpu` `port`), with nothing copied. A root view + /// has no size: the code reads zeros past [`ROOT_CONSTANT_BYTES`] itself. + pub fn root_constants_handle(&mut self, slot: u8) -> V { if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) { return h; } let r = self.m.i32(u32::from(slot)); - let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)]; + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)]; let bind = self.m.aggregate(self.t.bind, &bind); let f = self.m.bool(false); let block = self.entry; @@ -368,7 +378,8 @@ impl Shader { 217, &[bind, r, f], ); - let h = self.annotate(block, h, 13, 65536); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; self.root_cbvs.push((slot, h)); h } @@ -619,41 +630,22 @@ impl Shader { dxil_kind: 13, }); } - let blob = self.m.array(16384, self.t.i32); - let ty = self.m.named_struct("RootCbv", vec![blob]); - let p = self.m.ptr(ty); - let u = self.m.undef(p); - for (slot, _) in self.root_cbvs.clone() { - let ops = vec![ - Some(i32c(&mut self, cbv_list.len() as u32)), - Some(self.m.md_value(u)), - Some(empty), - Some(i32c(&mut self, ROOT_CBV_SPACE)), - Some(i32c(&mut self, u32::from(slot))), - Some(i32c(&mut self, 1)), - Some(i32c(&mut self, 65536)), - None, - ]; - cbv_list.push(Some(self.m.md_node(ops))); - bindings.push(Binding { - kind: 2, - space: ROOT_CBV_SPACE, - register: u32::from(slot), - dxil_kind: 13, - }); - } if !cbv_list.is_empty() { cbvs = Some(self.m.md_node(cbv_list)); } let mut srvs = None; - if !self.root_srvs.is_empty() { + if !self.root_srvs.is_empty() || !self.root_cbvs.is_empty() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + // Root constant buffers are raw buffers too + // ([`Shader::root_constants_handle`]); a root parameter is + // one or the other, so their registers never meet. + let views: Vec<(u8, V)> = self.root_srvs.iter().chain(&self.root_cbvs).copied().collect(); + for (n, (slot, _)) in views.into_iter().enumerate() { let ops = vec![ Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 19009227d..64f563cf7 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -105,21 +105,22 @@ fn lowered_on( wide: &HashSet<usize>, host_wave: u32, ) -> Result<HostShader, ShaderError> { - lowered_counted(native, p, wide, host_wave, false) + lowered_with_options(native, p, wide, host_wave, false, &[]) } -fn lowered_counted( +fn lowered_with_options( native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>, host_wave: u32, counted: bool, + lds_seed: &[u32], ) -> Result<HostShader, ShaderError> { let st = structure::structure_wide(p, wide).expect("structure"); let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); let io = io::raise(p, native).expect("io::raise"); let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); - let lowered = lower::lower_counted(&lower::Parts { + let parts = lower::Parts { native, p, st: &st, @@ -129,7 +130,12 @@ fn lowered_counted( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - }, counted); + }; + let lowered = if lds_seed.is_empty() { + lower::lower_counted(&parts, counted) + } else { + lower::lower_with_lds_seed(&parts, lds_seed) + }; lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; Ok(HostShader { @@ -511,6 +517,149 @@ fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() { } } +/// Like the tiled water kernels, scalar state flows across a branch whose +/// mask can be nonempty on just one of the host wave's two halves. +#[test] +fn a_guest_mask_branch_updates_scalar_state_for_both_halves() { + let native = native(&[ + 0xBE85_0381, // s_mov_b32 s5, 1 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBF86_0001, // s_cbranch_vccz skip + 0xBE85_0382, // s_mov_b32 s5, 2 + 0x7E04_0205, // skip: v_mov_b32 v2, s5 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0xE070_1000, + 0x8002_0201, // buffer_store_dword v2, v1, s[8:11], 0 offen + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let wide = super::guest_wave_branches(&st); + assert_eq!(wide.len(), 1); + let shader = lowered(&native, &p, &wide).expect("lower"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("guest mask branch PSO"); + for (below, expected) in [(0, 1), (1, 2), (32, 2), (33, 2), (64, 2)] { + let mut ud = vec![0; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if (u.root, u.slot, u.dword) == (RootType::Constants, 0, 0) { + ud[u.index as usize] = below; + } + } + let out = host.dispatch(&root, &pso, &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [1, 1, 1], + }).expect("guest mask branch dispatch"); + assert_eq!(out[0], vec![expected; 64], "{below} lanes in the guest mask"); + } + eprintln!("ran on the hardware device: both host waves saw the same scalar value"); +} + +#[test] +fn tile_depth_extrema_are_initialized_when_lane_zero_is_masked_out() { + let mut native = native(&[ + 0x7E02_0280, // v_mov_b32 v1, 0: LDS address + 0x4A04_0081, // v_add_nc_u32 v2, 1, v0: distinct depth per lane + 0xBE8C_047E, // s_mov_b64 s[12:13], exec + 0x7DA4_0481, // v_cmpx_eq_u32 exec, 1, v2: select lane zero + 0x8AFE_7E0C, // s_andn2_b64 exec, s[12:13], exec: drop lane zero + 0xD81C_0004, 0x0000_0201, // ds_min_u32 v1, v2 offset:4 + 0xD820_0000, 0x0000_0201, // ds_max_u32 v1, v2 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0xD8DC_0100, 0x0300_0001, // ds_read2_b32 v[3:4], v1 offset1:1 + 0x4A06_0903, // v_add_nc_u32 v3, v3, v4 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0xE070_1000, 0x8002_0301, // buffer_store_dword v3, v1, s[8:11], 0 offen + ]); + let StageIo::Cs(cs) = &mut native.io else { unreachable!() }; + cs.rsrc2 |= 1 << 15; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_with_options(&native, &p, &HashSet::new(), 32, false, &[0, u32::MAX]) + .expect("lower seeded reduction"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("tile depth reduction PSO"); + let out = host.dispatch(&root, &pso, &Dispatch { + roots: vec![(0, Root::Constants(vec![0; shader.user_data_dwords().max(1) as usize]))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [1, 1, 1], + }).expect("tile depth reduction dispatch"); + assert_eq!(out[0], vec![64 + 2; 64]); + eprintln!("hardware tile reduction: min 2, max 64"); +} + +/// The tiled water kernels' lane pick (`CS_TransmissionVolumetrics_Tiled`, 0x53c and 0x2d94): +/// a 64-bit mask of one lane is kept in lanes 0 and 1 of a VGPR, read back, made EXEC, and +/// that lane's value is read with `v_readfirstlane` for the whole wave. On a host of 32-lane +/// waves the lane may sit in either half; both halves must read its value. +#[test] +fn a_lane_picked_by_a_kept_mask_is_read_by_both_halves() { + let native = native(&[ + 0x7D84_0000, // v_cmp_eq_u32 vcc, s0, v0 + 0xBE86_046A, // s_mov_b64 s[6:7], vcc + 0xD761_0003, 0x0001_0006, // v_writelane_b32 v3, s6, 0 + 0xD761_0003, 0x0001_0207, // v_writelane_b32 v3, s7, 1 + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xBE94_03C1, // s_mov_b32 s20, -1 + 0xD760_0006, 0x0001_0103, // v_readlane_b32 s6, v3, 0 + 0xD760_0007, 0x0001_0303, // v_readlane_b32 s7, v3, 1 + 0xBE8C_2406, // s_and_saveexec_b64 s[12:13], s[6:7] + 0xBF88_0003, // s_cbranch_execz past the read + 0x4A04_00FF, 0x0000_0064, // v_add_nc_u32 v2, 100, v0 + 0x7E28_0502, // v_readfirstlane_b32 s20, v2 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x7E08_0214, // v_mov_b32 v4, s20 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0xE070_1000, 0x8002_0401, // buffer_store_dword v4, v1, s[8:11], 0 offen + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let wide = super::guest_wave_branches(&st); + let shader = lowered(&native, &p, &wide).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("lane pick PSO"); + let mut wrong = Vec::new(); + for lane in [0u32, 5, 31, 32, 40, 63] { + let mut ud = vec![0; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if (u.root, u.slot, u.dword) == (RootType::Constants, 0, 0) { + ud[u.index as usize] = lane; + } + } + let out = host + .dispatch(&root, &pso, &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(64)], + samplers: &[], + groups: [1, 1, 1], + }) + .expect("lane pick dispatch"); + if out[0] != vec![lane + 100; 64] { + wrong.push((lane, out[0][0], out[0][32])); + } + } + assert!(wrong.is_empty(), "(picked lane, lane 0 read, lane 32 read): {wrong:x?}"); + eprintln!("ran on the hardware device: both halves read the picked lane"); +} + fn a_wave_or_inside(skip: u32, name: &str) { let native = program(skip); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); @@ -708,7 +857,7 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { 0xe0c8_1000, 0x8002_0201, // buffer_atomic_add v2, v1, s[8:11], 0 offen ]); let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap(); - let shader = lowered_counted(&native, &p, &HashSet::new(), 64, true).unwrap(); + let shader = lowered_with_options(&native, &p, &HashSet::new(), 64, true, &[]).unwrap(); let limit = shader .user_data .iter() diff --git a/docs/performance/AGENT_REPORTS/01-gpu-submission.md b/docs/performance/AGENT_REPORTS/01-gpu-submission.md new file mode 100644 index 000000000..ca2cfd2d1 --- /dev/null +++ b/docs/performance/AGENT_REPORTS/01-gpu-submission.md @@ -0,0 +1,199 @@ +# 01 - GPU submission and scheduling (victory-gpu: queue, host, fence, frame, list, present) + +Scope: `crates/victory-gpu` `queue.rs`, `queue/behind.rs`, `host.rs` (submit, settle, relay, present), `host/card_steps.rs`, +`host/send.rs`, `host/awake.rs`, `host/two_queues.rs`, `fence.rs`, `frame.rs`, `list.rs`, `list/thin.rs`, `shadow.rs` (`wide*` only). +Read-only review; no source edited. Tags: **[M]** measured from the logs, **[S]** static (code read), **[H]** hypothesis that needs an experiment. +Descriptor, memory, shader and streaming internals belong to reports 02-05; they are only cross-referenced. + +## 0. Evidence base and caveats + +- [M] Logs: `%LOCALAPPDATA%\victory\logs\play-20261127-*.log` (5 sessions, diagnostics build, one stats block per ~5 s window, "per frame" = per present). + Machine in `runs\*\frametime.csv`: **Ryzen 7 5700X (8C/16T), RTX 4070 12 GB, 32 GB**, not the 12900K/7900 XTX of `docs/findings.md`. + So wide pools are `16/4 = 4` threads (`shadow.rs:1549`), thin is 8 (`list/thin.rs:303`), and 8 physical cores are close to saturated (report 06). +- Numbers below are medians over the "in-world" windows (>2000 draws/frame) of each log unless stated. I wrote small scripts + (scratchpad `b.js`, `c.js`) to aggregate them; the raw lines are quoted where it matters. +- Frame time in world: median **54 ms (log 094655), 62 ms (093037)**, up to 98-139 ms medians in the stutter-heavy sessions (093851, 094254, 095317). +- The `fps` line's "0.0 on the GPU" and "copying back" are for waited submissions only. They say nothing about the card's real time in relay mode. + Real card time is **not measured anywhere in these logs** (`VICTORY_GPU_TIMING` and `victory replay --timing detailed` were not run). + +## 1. How a submission travels today (the pipeline that is the wall) + +``` +title render threads --ExecuteCommandLists--> queue.rs:593 execute -> behind::submit (queue/behind.rs:841) + (list calls only appended as words: list/thin.rs, translated by 8 threads, 43.6k calls = 233 ms CPU / frame) + | Job::Lists pushed in ONE line (LANE) in the title's call order + v +victory-submit thread (behind.rs:267 serve -> step:315 -> Job::go:620) <== ONE thread, ONE lock (host.submitted) + Host::execute_parts (host.rs:5315) -> cut_for / split -> send_late (5339) -> Host::submit (5640): + 5675 card_steps plan + record "steps done on the card" list (4.6-8.6 ms) + 5681 late_blocked if a read hits flights' declared writes: relay_wait/settle = FULL DRAIN (mean 8-14 ms, p90 35-50) + 5702 heap records begin_sync_heaps (other threads) + 5743 sweep periodic forced settle (every 1.5 s) + 5784 watch::ask_once write-watch asking (3.6-7 ms) + 5797 stale_under_flights / merge_under_writes title bytes under flights' writes (5-7 ms) + 5813 refresh_front / run_deferred / batch.flush refresh host copies, fills, copies (15-28 ms, 37 fork/joins) + 5840 take_snapshots + 5862 card_before sync list + check list (hash 185 + compare 352 dispatches, 21 MB sent up) (7-9 ms) + 5912 ExecuteCommandLists(prelude, list, check) + Signal; flight pushed in LINE; relay thread lands it later + Present job: queue.rs:1032 -> behind::present (929) -> go -> present_planes (host.rs:9747) -> swap_chain.Present (10033) +relay thread (host.rs:3565 relay_worker): waits card fence, fetches pieces, merges into title memory, then tells the title (fences, values) +``` + +Frame pacing facts [S]: the title may be at most one present ahead (`frames_most` = 1, `behind.rs:736`; `wait_presents` `behind.rs:250`), +up to 64 submissions in the line (`runs_most`, `behind.rs:728`), up to 256 lists in the air (`late_most`, `host.rs:2722`), +swap chain has 2 buffers and `Present(0,0)` (`host.rs:9222`, `10033`). `VICTORY_FRAME_INTERVAL_US=1000` means we do not pace the title. + +### 1.1 Measured split of a world frame (submit thread = "the wall") + +| per frame, medians [M] | log 094655 (54 ms frame) | log 093037 (62 ms frame) | +|---|---|---| +| victory-submit thread worked (`behind.rs` BUSY) | 49.9 ms (92 % of the frame) | 58.4 ms (94 %) | +| of it: write-watch asking | 3.6 | 4.9 | +| title bytes put under flights' shader writes | 6.9 | 5.2 | +| lists' steps (refreshes 10.0 / 13.0 of it, in 36-38 flushes) | 15.4 | 19.4 | +| copies in the card's memory (card_before) | 6.8 | 7.6 | +| planning steps done on the card (5.4k fills) | 4.9 | 4.6 | +| sending lists | 1.1 | 1.2 | +| waiting for flights (median / **mean**) | 4.7 / **14.4** | 0.1 / **12.0** | +| title threads waiting at presents | 19.7 | 23.6 | +| card "nothing of ours queued" (idle while submit thread works) | 7.3 (7.2) | 8.3 (8.0) | +| card clock "busy" | 85 % | 86 % | +| relay thread: waiting for the card / landing | 29 / 15 ms | 38 / 13.6 ms | + +Reading [M]: the title's render thread sits ~20 ms per frame at the present because the submit thread is the pipeline's slowest stage. +The card is queued-busy 85-90 % of the time (its own fence clock, `host.rs:648-735`), idle only 7-9 ms per frame, all of it while our thread is preparing. +So **two walls are close to each other**: the submit thread (~50 ms) and the card (up to ~45-49 ms of queued work, composition unknown). +Reports that say "the card is not the wall (6.8 ms of GPU)" read a counter that only counts waited submissions. The honest status is: **unknown, must be measured** (section 5, item 0). +Whatever the card's real time is, speeding up the CPU side alone can at best lower the frame to about the card's time. + +Regime split [M] (settle reasons, `c.js`): "title memory read" settles average **8.4-11.8 ms per frame in every log**, p90 of 5 s windows 34-50 ms, and +the `fps` windows with mean frame >100 ms in logs 093851/094254/095317 are the ones with the large `waitfl`. This is the biggest *stutter* mechanism in my area. + +## 2. Mechanism inventory: why it exists, requirement or artifact + +| Mechanism | Why it exists | Real Xbox requirement? | Why per frame | Can it go | +|---|---|---|---|---| +| One serial prepare+send thread under `host.submitted` (`host.rs:5647`) | host copies, snapshots, numbered sends and the compare area are per host copy, not per submission (comment `host.rs:5644`) | No. Artifact of shared mutable per-copy state | every submission, 28 a frame, in title order | Split into stages (R2) | +| Cut at memory-value waits, 29 parts a frame (`host.rs:3200-3207`, `queue.rs` `cut_list`) | the title's lists wait on values the GPU writes; the host can only wait on fences | Partly: a real ordering dependence, but 18.7 of them per frame are met by a flight in the same stream ("met by a flight's bottom-of-pipe write", log) and need no cut | each wait | Join more (R4), elide waits met by an earlier part of the same queue | +| Refresh host copies at submit (`Batch`, `host.rs:8121`; `defer_refresh` `host.rs:7250`) | card cannot read title memory | **Yes**, a card-visible copy is required (or in-place heap, `inplace.rs`) | nobody tells us when the CPU wrote | Make it incremental/push (R5) | +| Heap-buffer pass: ~10k buffer views refreshed once per frame (`draw.rs:2382-2413`, `heap_buffer_pass`) | bindless SM6.6 shaders index any view | Artifact of "no idea which view a computed index names" | per frame | descriptor report 03 | +| Write-watch asking + guards (`watch.rs`) | detect CPU writes | Required in some form | per submission (`ask_once`) | report 02 | +| Title bytes put under flights' writes (`merge_under_writes`, `host.rs:3199`) | the title's 480-byte constants ring lives in the same 174 MB heap that 11 skinning dispatches write as a whole (`card_steps.rs:12-24`) | **Artifact** of declaring a whole-heap root view as written | per frame, 58k changed runs / 2.3 MB | R1 (narrow declared writes) | +| Card steps: copy/fill done on the card (`card_steps.rs`, `stage()=2`) | avoid waiting for flights before reading what they write | Artifact (same root cause) | 5.4k fills / frame | R1, then R3 (batch) | +| Settle/drain for "title memory read" (`late_blocked` `host.rs:2891`, call site `5681`) | a CPU step reads memory flights may still write | Artifact of the same over-declaration | 0.17-0.2 per frame, each 40-50 ms | R1 | +| Card hash+compare (`card_before` `host.rs:4411`) | find what shaders wrote | Requirement is "know what shaders wrote" (audit I3), not "hash" | 185 hash + 352 compare passes | R4/R6 | +| Landing thread (relay, `host.rs:3565`) | R1 invariant: CPU must see GPU results before a fence/present/value | **Yes** (ocean maps, culling, skinning lists) | each flight | keep, but do less | +| Present on the submit thread (`queue/behind.rs:677-689`, `host.rs:9747`) | order with lists | No | per frame, 1.2-1.9 ms | R7 | +| Forced settle at the sweep every 1500 ms (`host.rs:5745-5753`) | free retired objects when nothing is in the air | No: could retire by fence value | every 1.5 s | R8 | +| `CARD_AWAKE` spin kernel (`host/awake.rs`) | keep NVIDIA/AMD clocks up across 30 gaps a frame | Artifact of the gaps | continuous | disappears with R2 (fewer gaps) | + +## 3. Ranked structural opportunities + +Estimates are for the submit thread's ms/frame unless said otherwise; they do not add up (overlap). Risk is risk of wrong pixels/lost writes. + +### R1. Stop over-declaring the title's heap as shader-written: removes the full drains, most "under flights" merging and part of the card steps +- **Evidence** [M] waiting for flights mean 12-17 ms/frame (median 0-5) in 4 of 5 logs; "title memory read" 8.4-11.8 ms/frame mean; `submissions sent ahead ... 0.2 settles, 6.3 ms waiting` and + `0.17 submissions refused and waited` (card_steps line). Per occurrence ~30-50 ms (a whole drain of the flights). Title bytes under flights' writes 5-7 ms. [S] root cause in + `card_steps.rs:12-24`: eleven skinning dispatches write "through one view of the title's whole 174 MB heap, at places they read out of job records", so `Line.written` (`host.rs:2782`) covers the heap and + every fill/copy of the title's constants ring (also in that heap) "reads what flights write" (`blocked_by` `host.rs:3072`, `read_blocked` `3059`). +- **Why a drain** [S]: when `card_steps` refuses (`card_steps.rs:661-679`; refusal strings at `:261-409` and `:723-785`: "a step of ours runs" (`Does::Run`), "a texture reads it", "flights write it through two host copies", + "no host copy holds all of it", "too much at once", ...), `submit` falls to `relay_wait`/`settle` (`host.rs:5681-5693`) which waits for the whole line. + A blame line exists but only in diagnostics when enabled (`log_blame`, `host.rs:3024`): "waited for flights, per frame: ..." did **not** appear in any of the five logs, so the refusing step kind is not known from the data. +- **Design (replacement)**: replace "declared range" by "learned write zones" for the purpose of *blocking*. + 1. Keep the conservative declaration for the *compare/landing* (correctness: R1 invariant), but compute `Line.written` for blocking from `watch.rs` `LANDED` journal + (`landed_lately`, `watch.rs:1944`, 4 KiB pages, last-landed frame): a read is blocked only if its pages were landed in the last K frames or are in a range whose shader writes are bounded by the pipeline's observed extent. + This is what `VICTORY_FILL_TITLE=1` already does for small fills (`host.rs:2921`, 600 frames, **off by default**). Extend it to copies/textures/steps and make the whole-heap compare run each frame on pieces to verify. + 2. Verification: the compare already hashes declared pieces; hash the *whole* heap's pieces (174 MB / 64 KiB = 2.7k pieces, one pass) every frame in the check list. A write into a "never written" piece marks it learned and + raises a counter `learned_violations` (log); the affected frame can be one frame stale for that constant, which matches the existing `FILL_TITLE` risk note (`host.rs:2915-2919`). + 3. Optional split: allocate the constants ring in its own host copy (a second `Shadow` over the ring's address range) so it is not part of any whole-heap declaration at all. +- **Quick experiment before any code**: A/B `VICTORY_FILL_TITLE=1` (exists, off) on the same save; watch `title memory read` ms and `waitfl`. Also run once with diagnostics blame to name the refusing step. +- **Estimated gain**: -8 to -12 ms mean on the submit thread (more important: removes 40-50 ms spikes, the main stutter source here), plus -3 to -5 ms of "under" merging, plus part of `plan` if fewer steps are needed. +- **Risk**: medium (one-frame-stale constants if wrong). **Files**: `host.rs` `blocked_by` (3072), `late_blocked` (2891), `read_blocked` (3059), `fill_is_titles` (2921), `stale_of`/`merge_under_writes` (3199); + `host/card_steps.rs` `card_steps` (660), `plan` (259), `take_steps` (682); `watch.rs` `landed_lately` (1944); `host.rs` `card_before` (4411, whole-heap verify pass). + +### R2. Pipeline the submit thread into two stages (prepare / send) - the audit's own "next" item +- **Evidence** [M]+[S]: thread 92-94 % occupied; stage P (watch 3.6 + under 6.9 + steps 15.4 = ~26 ms) and stage S (card_before 6.8 + plan 4.9 + send 1.1 + after-send ~1 = ~14 ms) are + independent enough to overlap *different submissions*. `findings.md` "What is next" item 1 asks for this; report 06 ranks it #2 (high risk). +- **Why possible** [S]: what P of submission N+1 needs from N is only N's *declared writes* (to know what is "in the air": `let air = line().written.clone()`, `host.rs:5810`) and numbering of sends (`QUEUE_ORDER`, `card_before` `host.rs:4424`). + Both are computable from the lists before N is sent (`declared_writes(runs)`, `host.rs:3960`). +- **Design**: split `Host::submit` (`host.rs:5640`) at `host.rs:5862`. Stage P runs on a second thread `victory-prep` that pulls the next ready job from `Lane` (`behind.rs:315 step` currently pops one job at a time and runs it inline in `Job::go`), + holds a *prep lock* (not `submitted`), and appends the declared ranges of the job to a `pending_air` list under `Line` *before* it starts; it produces a `Prepared` (batch.placed, picked, declared, `own`, lists vec). + Stage S (existing thread) holds `submitted`, runs `card_before`, `ExecuteCommandLists`, `Signal`, pushes the flight. Order of S = order of jobs (a bounded queue of `Prepared`, depth 2). + Keep `take_along` (joins, `behind.rs:557`) before P so joined parts are prepared together. + The present job and signals pass through S only. +- **Estimated gain**: submit-thread critical path 50 -> ~30-35 ms if P and S overlap fully; realistic -10 to -15 ms. Also halves the card-idle gaps (7-9 ms) because S sends sooner. + Bound by the card (section 1.1) and by core count: P adds a busy thread on an 8-core machine already carrying ~8 logical CPUs of work. +- **Risk**: high (ordering, R2 "never overwrite newer title bytes", numbered sends). Test with replay `--compare` and the lost-write stress (audit C4: 600 runs; `SUBMIT_DEPTH=1/64`). +- **Files**: `queue/behind.rs` `Lane::step` (315), `Job::go` (620), `Job::take_along` (557); `host.rs` `submit` (5640), `send_late` (5339), `card_before` (4411), `Line` (2782); `host/card_steps.rs` `card_steps` (660). + +### R3. One gather dispatch instead of ~5,400 small copy commands per frame (card steps' fills) +- **Evidence** [M]: `steps done on the card ... 5409.44 fills, 0.00 buffer copies, 2296.9 KB` (log 093037, line 18711 area); fills of ~430-480 B. `planning steps done on the card` 4.6-8.6 ms per frame. + [S] `card_steps::record` (`card_steps.rs:546-600`) emits one `CopyBufferRegion` per read and per write plus barriers per level; `places` dedupes by (copy, src, len, level) but every distinct 480-byte constant is still its own command. + The code already has the right tool: `send.rs:277-314` sends runs "as pairs of offset and value, stored by one dispatch per copy". +- **Design**: add a tiny compute kernel "gather": input = a table `{src_off, dst_off, len}` (built on the CPU in one upload, 5.4k x 16 B = 86 KB), source = the host copy of the heap, destination = `between` (`BETWEEN` 4 MiB, `card_steps.rs:111`). + One dispatch per level. Coalesce adjacent src/dst runs on the CPU (the ring is written sequentially). CPU: build table instead of 5.4k D3D12 calls; GPU: one dispatch instead of 5.4k copies (each a tiny serialized copy). +- **Estimated gain**: -3 to -6 ms CPU on the submit thread (recording 5.4k commands at ~1 us), plus unmeasured GPU time (5.4k tiny copies; likely several ms of card time, [H]). +- **Risk**: low-medium (self-contained, replay `--compare` verifies bytes). **Files**: `host/card_steps.rs` `record` (546), `take_steps` (682-800), `Op`/`To` (520-536); new kernel next to `send.rs:300-320`. + +### R4. Fewer, bigger submissions and one coherence pass set per frame segment +- **Evidence** [M]: 28 submissions/frame, only 13 prepared together with the previous (`JOIN_PARTS=8`, `JOIN_LISTS=48` default `host.rs:3215-3226`), 16.1 "submissions sent ahead", 18.7 waits met by in-air flights. + Each prepared unit pays a fixed cost: lock, `begin_sync_heaps`, `ask_once`, `refresh_front` fork/join, `card_before` (a sync list *and* a check list with a full UAV barrier each, `host.rs:4635-4643`, 4553), `Signal`, `awake::sent`, `land()`. + `card_before` costs 6.8-9.9 ms/frame; 185 hash + 352 compare passes are recorded per frame (log line "our passes over copies"). +- **Design**: (a) cheap: raise `JOIN_PARTS` to 16-32 and `JOIN_LISTS` to 96-128 (existing env vars) and A/B; (b) in `Job::take_along` (`behind.rs:557`) treat a `Job::Value` wait that a flight *before it in the same queue's joined part* will meet + (`will_meet`, `host.rs:3236`) as satisfied without cutting (it already does for `hosts()`, but `late_met_known` waits split); (c) structural: record all hash passes of a prepared unit into one list with one barrier and + collapse per-copy `SetComputeRootShaderResourceView/UnorderedAccessView` into one bindless table kernel (SM6.6 `ResourceDescriptorHeap`, same mechanism as the heap strides table). +- **Estimated gain**: (a) -1 to -3 ms, (c) -3 to -5 ms CPU and fewer GPU pipeline drains (2 global UAV barriers per submission x ~15 = 30 drains/frame, [H] 1-3 ms of card time). +- **Risk**: (a) low; (b) medium (ordering); (c) medium-high (hash exactness; `--skip-hash-passes` replay oracle exists). **Files**: `queue/behind.rs` `take_along` (557); `host.rs` `joins`/`joinable` (3211-3245), `card_before` (4411-4670), `card_pass` (2232). + +### R5. Make refresh incremental: one fork/join per submission (not 37 per frame) and no per-span lock chatter +- **Evidence** [M]: refreshes 10-13 ms/frame in `36-38 flushes of 9,939` spans; 8,849 known to copy nothing; `wide`'s helper wake costs "50 us and more, 95 times a frame" (`shadow.rs:1529-1533`, `VICTORY_WIDE_SPIN` default 0); copies 11-20 ms thread time / 30 MB. + `nothing_new` takes three mutexes per span (`shadow.rs:3959-3984`: `pending`, `copied`, `ranged`) on ~10k spans (the ~4,100 heap-buffer copies come with `heap_buffer_pass`, once per frame, but re-flushed per submission). +- **Design**: (1) per frame, compute the set of dirty copies once from the `watch` journal (`ask_ahead`) into a `Vec<Arc<Shadow>>` and give each `Batch` only those (O(dirty), not O(10k)); (2) one persistent job queue (`Workers`, `shadow.rs:1520`) that stays awake + between flushes inside a submission (spin 20-50 us only while a submission is being prepared, never otherwise); (3) merge flushes of joined parts (`refresh_front` already does for `JOIN_PARTS`; raise parts, see R4). +- **Estimated gain**: -3 to -6 ms [H] (fork/join latency 37 x ~0.1-0.2 ms + lock chatter). Cheap probe: `VICTORY_WIDE_SPIN=100` A/B (expect little on a CPU-saturated 8-core, positive on the 12900K). +- **Risk**: low-medium. **Files**: `host.rs` `Batch::refresh_front` (8520), `flush_all` (8701), `copy_spans` (8410); `shadow.rs` `wide` (1593), `wide_each` (1655), `Shadow::nothing_new` (3959). + +### R6. GPU-side cost of the coherence machinery: measure first, then cut +- **Evidence** [M]: card queued 85-90 % of every frame; [S] per frame the card runs ~540 hash/compare dispatches, ~5.4k tiny copies, 16 sync lists + 16 check lists, 30 global UAV drains, 21 MB of sends, ~18 MB fetched for 0.77 MB landed (report 02). + None of it is the title's own work. If the title's own GPU time is 30-35 ms (Series X 30 fps target), the emulation overhead is a double-digit percentage of the card's frame. **Unknown without the replay tool** (`docs/replay.md`: `--skip-hash-passes`, `--no-barriers`, `--merge-barriers`, `--timing detailed`, `--one-submit`, `--pace`). +- **Design**: run `victory replay <capture> --compare --skip-hash-passes` and `--one-submit` on the 4070; attribute card ms to (a) title commands, (b) coherence passes, (c) fills/copies, (d) gaps. Only then choose between + R3/R4(c) (fewer commands), declared writes replacing compare (audit C3, `PICKED_WRITES`), and async compute (`two_queues.rs` is a plan only: every host list is a DIRECT list, `two_queues.rs:11-28`). +- **Estimated gain**: unknown, potentially the dominant term once the CPU is below ~45 ms. **Risk**: n/a (measurement). + +### R7. Move Present (and the panel/menu/meter) off the submit thread +- **Evidence** [M]: "1.47 ms in [Present] (the longest 4.9 ms), 0.39 ms recording the upscaling" per frame on the presenting thread (log line 18711); median 0.9-1.9 ms over the logs. [S] it runs inline in `Job::go` (`behind.rs:677-689`) -> `present_planes` (`host.rs:9747-10050`): + swap-chain access, composite list, `Present(0,0)` (blocks when both of the 2 buffers are queued), `p.panel.frame`, `p.menu.frame`, `p.meter.frame`. +- **Design**: after recording the copy list and sending it (`execute_own`, `host.rs:5402`), hand `Present` + frame meter to a presenter thread that waits for the flight's fence. Raise `BUFFERS` to 3 only if it measurably stops `Present` blocking. + Streamline's per-present tagging (`streamline::present_begins/called/returned`) must stay in order on one thread; the presenter thread owns it. +- **Estimated gain**: -1.5 to -2 ms/frame, and less jitter (`longest 4.9 ms`). **Risk**: low-medium (Streamline thread rules). **Files**: `queue/behind.rs` `Job::go` (620), `host.rs` `present_planes` (9747), `streamline.rs` present hooks. + +### R8. Retire resources by fence value instead of the periodic forced drain +- **Evidence** [S]: `host.rs:5743-5753`: when `late_free_present()` and 1.5 s passed since `SWEPT`, `submit` calls `settle(.., WHY_SYNC)` = full drain of the flights, then `sweep()`; also `present_planes` resize path `settle_now(WHY_SYNC)` (`host.rs:9800`). + [M] `a synchronous submission or present` averages 0.2-0.4 ms/frame (= a drain every ~1.5 s, each ~10-30 ms): a recurring hitch every 1.5 s, invisible in averages. +- **Design**: give every retired object (texture/view memory, tables, scratch) the fence value of the last flight that may use it (`Flight.fence`, `host.rs:2760`) and free when `fence.completed() >= value` on the relay thread; keep the drain only for resize/shutdown. +- **Estimated gain**: removes a periodic 10-30 ms hitch; mean ~0.3 ms. **Risk**: low-medium (lifetime bugs = device loss; run `SLOT_CHECK`). **Files**: `host.rs` `sweep` (435), `submit` (5738-5754), `retire`/`bury` (`host.rs`, uses `FINISHED`). + +### R9. Things I checked and do NOT recommend now +- Raising `VICTORY_SUBMIT_FRAMES` (queue depth): only moves the wait from the title's present to the line; the submit thread is the bottleneck (title waits 20 ms at presents anyway). It also holds more list allocators (findings: 9 GB). +- A second drawing queue / `ASYNC_SUBMIT` off: already measured negative (`findings.md`). `two_queues` async compute stays a plan until R6 says the card is the wall. +- Barrier removal: "nothing to 0.1 ms each" (`findings.md`); only `--merge-barriers` in R6 for the UAV drains. +- `VICTORY_SUBMIT_DEPTH` (64 = two frames): not a limiter (`threads of the title waited 0.0 ms for room in the line`). + +## 4. Order of work (what I would do, cheapest and most certain first) + +0. **Measure the card** (replay `--compare --skip-hash-passes`, `--timing detailed`) and capture one diagnostics run with blame lines for `waited for flights`; decide R1 vs R6 priority. (No code.) +1. R1 step A: A/B `VICTORY_FILL_TITLE=1`, `VICTORY_JOIN_PARTS=16 VICTORY_JOIN_LISTS=96`, `VICTORY_WIDE_SPIN=100` - three env-only experiments, 15 intervals each (audit method: median of >=15 intervals with >=1000 draws/frame). Expected: -3 to -12 ms and far fewer spikes. +2. R7 and R8 (small, low risk, remove 1.5 ms and the 1.5 s hitch). +3. R3 (self-contained, replay-verifiable), then R1 step B (learned write zones with whole-heap verification). +4. R2 (two-stage pipeline) once the stages are smaller (after R1/R3 the P stage is ~15 ms and S ~8 ms, so the split no longer needs to be perfect). +5. R6 follow-ups chosen from the replay breakdown. + +Projection [H]: R1+R3+R4(a)+R5+R7 take the thread from ~50 to ~28-32 ms; R2 would take it under 25. The frame then equals the card's time, so the achievable fps on this 4070 is +set by item 0: if the card's real time is ~45 ms the CPU work buys ~20 -> 22-25 fps and the GPU-side cut (R6) is the only way past it. + +## 5. What I could not establish (and how) + +- Real card time and its split (title vs coherence): replay tool, `VICTORY_GPU_TIMING`, or timeline (`VICTORY_TIMELINE`) with `card_wait` spans. +- Which step kind causes the 0.17-0.2 refused submissions per frame: diagnostics `log_blame` (`host.rs:3024`) was not enabled in these logs. +- Whether the thin-translator's 5.3 us/call (43.6k calls, 233 ms CPU/frame, `list::thin` line) is dominated by the ~4.7k draws (233/4700 = ~50 us per draw incl. bindings) or by the cheap state calls: needs a per-op timer; out of my scope (report 06, 03). +- Residency waits: "new card memory waited for until it is mapped ... 18600 times, 2986 ms, the longest 63.6 ms" (log 093037, line ~18690) is a submit-path stall source; belongs to report 02. diff --git a/docs/performance/AGENT_REPORTS/02-memory.md b/docs/performance/AGENT_REPORTS/02-memory.md new file mode 100644 index 000000000..1fa68c08c --- /dev/null +++ b/docs/performance/AGENT_REPORTS/02-memory.md @@ -0,0 +1,250 @@ +# 02 - Memory architecture (shadow, watch, land, uploads, residency) + +Scope: `crates/victory-gpu` shadow.rs, watch.rs, land.rs, titlewrite.rs, inplace.rs, copystat.rs, +memory.rs, residency.rs, safecopy.rs, upload.rs, texback.rs, tiles.rs, popwatch.rs, pool.rs, +plus `victory-hle/src/modules/xmem.rs`. Read-only investigation; no source was edited. + +Evidence labels: **[S]** static reading of code, **[M]** measured in a log, **[H]** hypothesis that needs an experiment. + +Logs used: `%LOCALAPPDATA%\victory\logs\play-20261127-094655-17644.log` (RTX 4070 12 GB, series-s profile, DLSS + frame gen 2x, +title started 09:47:00, world entered about 09:49:05) and `play-...093851-14116.log`. Line numbers below are in the 094655 log +unless stated. `runs\*\victory.log` were not needed. + +## 0. Summary of where the memory machinery costs + +Steady gameplay, 09:51-09:53 [M] (lines 21940-22010, 25978): + +| Quantity per frame | Value | +|---|---| +| Frame | 48-51 ms (20 fps); `fps` line: 33.7 preparing (copies 10.6 ms / 30 MB, textures 0.6 ms), 6.8 GPU, 11.4 "copying back" | +| Submitting ("preparing") thread | 46-48 ms, of which: 9.6 title bytes put under flights' shader writes, 15.4 list steps (refreshes 9.8), 7.2 copies in card memory, 6.1 planning card steps, 4.1 asking the write watch, 1.1 sending lists | +| Landing (what shaders wrote -> title memory) | relay thread 17.3 ms busy, 27-30 ms waiting for the card; 280 pieces of 64 KiB fetched (about 18 MB), of which 872 of 2482 pages have a new byte (3.4 MB) and only **0.77 MB** actually go in as dwords | +| Card-side coherence passes | 150 hash passes over 260 pieces + 360 compare passes; 5.5-5.8 thousand "fills" for card steps | +| CPU -> card | 18 MB / 760 runs sent as scatters (2.7 ms to extract); 2.2 MB / 61,000 changed runs put under flights' writes | +| Descriptor-heap records | 200-240 changed 4 KiB heap pages, 210-250 k slots looked at, 8-9.5 k mirrored, 17 ms of thread time | +| Texture refreshes | 5-8 ms of thread time (read, hash, detile) | + +The card is not the wall in steady state (6.8 ms of GPU in the `fps` line, though the "card's clock" line says 86 % busy, which +includes our own hash/compare/fill passes). The wall is CPU-side coherence work: **about 42 of 48 ms is "noticing and moving"** +(`docs/findings.md`: "the one idea behind most of it"). The fix is not a faster scan; it is to stop scanning, comparing and +landing data that is provably (or learned to be) in one direction only. + +## 1. Mechanism inventory: why it exists, requirement vs artifact + +### 1.1 Host copy ("shadow") of every title buffer a draw uses - `shadow.rs:28` `Shadow` +- Why: title buffers are CPU memory the host GPU cannot address. A GPU-visible twin is mandatory (the card cannot read an arbitrary + `VirtualAlloc` address) unless the memory itself is opened as a heap (`inplace.rs`). **Real requirement: a card-visible + representation.** Copying is the implementation choice. +- Why per frame: nobody tells us when the CPU wrote, so each submission asks (`defer_refresh` at `host.rs:7250`, `Shadow::update` + `shadow.rs:3926`, `copy_stale` `:4083`). +- Large buffers (>= 64 KiB, `VICTORY_CARD_BUFFERS_MIN_KB=64`) have two sides: PC-memory staging (`Card::staging`, `shadow.rs:112`) + and the card-memory buffer shaders use (`shadow.rs:170` `cards()`). Every CPU change is copied twice (title -> staging -> + card, `card_before` `host.rs:4411`), and every GPU change twice (card -> fetch -> title, plus staging merge). +- The big one: the 174 MB heap (`start=0x1a1f0000 len=182452224`, line 278), 14 refreshes a frame of ~4 MB each (comment + `shadow.rs:4150`), declared as written "from dozens of offsets" (`shadow.rs:3774` comment). +- [M] 3,935 card copies, 1,937 MB (line 25977). Pool has `texture room: 8.1 GB in use`. + +### 1.2 Write watch + guards (CPU writes noticed) - `watch.rs` +- Why: need to know which pages the title wrote since the last copy. Private memory uses kernel dirty bits (`GetWriteWatch` + `watch.rs:262,275`); view memory (the page pool, SEC_RESERVE sections) cannot be write-watched, so a vectored handler + (`watch.rs:3058` `on_write`) makes blocks read-only and notes the first write. +- Real requirement: yes, for any buffer the title writes after first use. Implementation artifacts: (a) protection changes at + ~5 us each, 590 write faults/frame measured earlier (`titlewrite.rs` header, `watch.rs:1631`: 321-1,017 blocks re-protected + and 323-331 faults per frame); (b) 64 KiB block granularity for views; (c) one syscall-level ask per refresh range + (4.1 ms/frame [M], "0.6 finding what to ask"). +- Per-frame because reset is part of the ask (asking also clears). Could be anticipated: **yes** for memory the title never + writes after init (never faults/never dirty), which the code only handles implicitly (`ranged`/`nothing_new` fast path, + `shadow.rs:3959`). +- `VICTORY_STORE_BESIDE` / `VICTORY_COPY_BESIDE` (titlewrite.rs) are off by default [M: no log line, play.rs does not set them]. + +### 1.3 Landing: what shaders wrote -> title memory - `land.rs`, `shadow.rs` `card_merge`, `host.rs:5013 relay_land`, `:5158 card_back` +- Why: on the console the CPU sees GPU writes for free. Here it must be copied back, in order, before the title is told + anything (land.rs header: "a landing is done, whole, before the title is told anything"). +- **Real requirement only for ranges the title's CPU reads.** Known cases: ocean height/displacement textures (`texback.rs`), + the culling/occlusion data the title reads to decide "camera in a room" (`host.rs:3984` walls trace), BVH/structure builder + results (`memory.rs`). Everything else is an artifact of "declare the whole UAV view". +- Declaration is the whole bound range: `readable()` -> `shadow.gpu_writes(list, address, len)` (`draw.rs:5589`), root UAV + "cover all that is left of the title's buffer" (`draw.rs:2167` shortcut comment). [M] 109,228 MB/frame "declared written" in + WC memory left on the card (line 22003 area): the declared extent is ~600x the actual heap, because the same 174 MB heap is + declared dozens of times per frame. +- WC shortcut exists: memory the title mapped write-combined is not landed (`shadow.rs:3237`, `VICTORY_WC_NO_BACK`, min 1 MB). + 64 regions found in the log (lines 9168..). Non-WC (cached) memory, notably the 174 MB heap, is all landed. +- [M] fetched ~18 MB vs 0.77 MB dword-changed per frame: 96 % of the fetch/hash/compare traffic is false positive at + piece granularity. 17.3 ms thread time landing (relay) and 7-11 ms visible as "copying back". +- Could be persisted: yes. `picked.rs` already learns "a buffer written so once is written so again" within a session + (`picked.rs` header), proving the premise, but only for the picked-view case and not persisted. + +### 1.4 Title bytes put under flights' shader writes - `shadow.rs:3729 merge_under_writes`, `host.rs:2488 late()`, `:2529 late_exact()` +- Why: submissions are sent ahead without waiting (`VICTORY_LATE_WAIT=2`). A range a flight may write is "pending"; if the + title meanwhile wrote bytes into the same 64 KiB the refresh must merge only the changed dwords instead of overwriting + what shaders wrote. +- [M] 9.6 ms/frame of the submitting thread: 186 pages looked at, 61,334 changed runs, 2.24 MB (lines 21990-22000). + 36 bytes per run: small CPU stores (constants, counters, free-list links) in blocks that are only "pending" because the + declared extent covers them. +- Real requirement: only where the same bytes can be written by both sides in flight. Artifact: false sharing from the + over-wide declaration (see 1.3). This is the single most expensive item on the submitting thread. + +### 1.5 Card-side hash/compare passes - `host.rs:4411 card_before`, `shadow.rs:4459+ card_span / card_hashed` +- Why: with the card holding the copy, shader writes are found by hashing declared 64 KiB pieces before/after and fetching only + differing pieces (`Card::before`, `shadow.rs:112+`). [M] 150 hash passes over 260 pieces, 360 compare passes per frame + (line 21946). +- Real requirement: finding shader writes. Artifact: the number of dispatches (per range, per submission) rather than one + pass per buffer per frame; and the pieces compared that are never going to be landed (WC) are skipped already. + +### 1.6 Descriptor heap mirror (records the title copies as bytes) - `descriptor/host.rs`, `heap_marks.rs` +- Why: the console GPU reads descriptors from memory; the host needs real views. The runtime notices heap bytes the title wrote + and translates them. +- [M] 17 ms/frame thread time, 210-250 k slots looked at for 8-9.5 k new records, 124 of 200 changed pages are guarded views + (line 22000 area). 80 % of slots looked at are unchanged or empty. +- Not my main area, but it is the same pattern: **scan memory to find the 4 % that changed**. + +### 1.7 Texture refresh (CPU-written texture memory -> detile -> host texture) - `texture.rs:1410 refresh`, `:1621 ...` +- Why: textures are written by CPU/DirectStorage into tiled memory; the host copy is detiled linear. 5-8 ms/frame thread time [M]. +- Already has learned state: `once` flag (`texture.rs:1448`), `last.asked`, `exact`; 30-frame partial re-read (`:1560`). +- Memory of textures in view sections is guarded; hash whole texture otherwise (`texture.rs:1570-1580`, `digest(tiled)`): + an artifact for textures that are never rewritten. + +### 1.8 Uploads/staging/pool - `upload.rs`, `pool.rs`, `texture.rs`, `residency.rs` +- Why: GPU textures are separate objects from the title's memory; each texture needs a card allocation + staging. The pool + (`pool.rs:20-60`) cuts blocks of 64 MiB to avoid 310 us allocations. +- [M] "83,816 textures uploaded (5,057 MB)" over the first 5 minutes; "83,393 reads of the GPU side served from the pages (4,017 MB)" + per 10 s window (line 26086). + +### 1.9 In-place / zero-copy path - `inplace.rs` +- Exists: `VICTORY_INPLACE=0/1/2` (`inplace.rs:89`), default **off** (unset in the play settings; `grep VICTORY_INPLACE` in + the log header: absent). Reasons it is off (static): view memory (page pool) is a SEC_RESERVE section, the host refuses it + (`inplace.rs` header, `xmem.rs:706`); level 2 cannot combine with `VICTORY_LATE_WAIT` (`inplace.rs:86`); opening locks all + pages (256 MiB: 70 ms); `VICTORY_PORT_CONSTANTS` doc says "constants heap in place: the GPU then waits (slower overall) on a + 12 GB card" (`docs/README-foxhound.md:142`). +- Conclusion: in place is not a free lunch on a PCIe card because the card then reads PC memory over the bus. + It is the right answer only for read-once, write-combined, upload-style memory (constants, streamed instance data). + +## 2. Ranked structural opportunities + +Estimates are for the submitting/landing critical path on this PC (RTX 4070). Frame is ~48 ms; items overlap, do not sum. + +### R1. Learn and persist the GPU-write footprint; stop declaring whole UAV views - est. 10-18 ms/frame, risk medium +**Problem [S+M]:** declared writes = the whole bound range (`draw.rs:2167`, `:5589`). The 174 MB heap is declared from dozens +of offsets, so (a) a large part of the heap is "pending" in every flight, forcing `merge_under_writes` (9.6 ms), gap-splitting in +`update` (`shadow.rs:3926`, comment "copying the gaps whole cost ~1 s per frame"), snapshots and compare passes; (b) the card +hashes and fetches 260 pieces/frame to land 0.77 MB. + +**Design:** +1. Per Shadow keep `gpu_blocks: BitVec` (64 KiB blocks of the copy ever found changed by the card compare) plus a probation + cursor. Feed it from the existing compare result (`card_back` `host.rs:5158` / `walls_merged` shows the same data: which + pieces differed). +2. `Shadow::gpu_writes` (`shadow.rs:3220`) clamps `[address, address+len)` to `gpu_blocks` plus the block(s) probation selects + this frame (e.g. 1/16 of the unlearned blocks of that copy, rotating, as `picked.rs` `slice` already does at 32 MB/frame). + Everything downstream (pending ranges, snapshots, merge-under-writes, hash/compare passes, fetches) then only sees the + learned footprint. The hash passes for non-landed blocks can keep running on the card (cheap, no CPU work) if exactness is + wanted. +3. Anything discovered on probation joins the set, lands, and is logged. +4. Persist: `cache_dir/memory-profile/<build>.json` with key = (copy size, allocation sequence number or xmem allocation + site hash) -> block bitmap. Addresses vary between runs (xmem address-range logic, `xmem.rs:80`), so key by allocation + identity + offset, not address. Validate on load with the first N frames (any differing block promotes). +5. Metrics: log `gpu_blocks` size, probation discoveries, and `0.77 MB real vs fetched` ratio. + +**Risk:** a first-ever GPU write to an unlearned block while the title also writes the same page in flight loses the GPU +bytes (the page goes full copy). Mitigation: probation + the existing `merge_under_writes` path is kept as fallback for unlearned +blocks; persistence removes the cold start; kill switch like `VICTORY_PICKED_WRITES`. +**Files:** `shadow.rs` (`gpu_writes`, `Entry`, `update`), `host.rs` (`declared_writes` :3960, `card_back` :5158), +`draw.rs:2167,:5589`, new `memory_profile.rs`. +**Experiment first [H]:** count distinct blocks of the 174 MB heap ever differing across 60 s of gameplay. If it is +under ~20 % of 2,784 blocks the saving is as estimated. + +### R2. Learned CPU-read set for landings ("demand landing") - est. 5-11 ms/frame (the fps line's "copying back"), also shortens frame latency, risk high +**Problem [M]:** landing is on the critical path because the title is told nothing before it is done; relay thread waits +27-30 ms for the card and works 17 ms; only 0.77 MB of 18 MB is real. +**Requirement [S]:** only memory the title CPU reads after a GPU write needs landing (ocean textures `texback.rs`, room +culling readbacks `host.rs:3984`, BVH structures `memory.rs`). There is no read detection today (`VICTORY_READ_WATCH` is +mentioned only in a comment, `texback.rs:7`; nothing in the tree implements it). +**Design:** add read observation on the same vectored handler (`watch.rs:3058`): in a probe mode, make landed pieces +`PAGE_NOACCESS` for K frames; a read fault records (copy id, block) in `cpu_read_blocks`, unprotects, lands that piece +synchronously and resumes. Kernel-side reads (ReadFile/DirectStorage into the page) bypass faults: `safecopy.rs` already +covers our own copies; title I/O into GPU-written pages must be excluded (treat as read-set if ever seen). Then landing is +restricted to `cpu_read_blocks`, all other pieces never fetched. Persist the read set with R1's profile. +**Risk:** high (unobserved reader means stale data, e.g. frame-delayed culling flicker, "outdoor flicker" in +`docs/findings.md` item 4). Start in measure-only mode and ship R1 first; keep a once-per-N-frames full landing as a safety. +**Files:** `watch.rs` (handler, protection), `land.rs`, `shadow.rs` `card_merge`, `host.rs:5013`. + +### R3. Persisted per-resource write classes at allocation time - est. 3-6 ms/frame, risk low +**Idea [S]:** XMem flags tell the class for free: write-combined = CPU write-only, GPU read-only or GPU-private (no landing, +already used by `VICTORY_WC_NO_BACK`, min 1 MB); cached = bidirectional. Extend to: +- WC & GPU-read-only (never in a UAV): "upload class": no snapshot, no pending logic, no landing, refresh only + (`wc_no_back_min` 1024 KB limits this today; use class for every size). +- Never dirty after N frames ("frozen"): skip `defer_refresh` entirely until the guard handler or the kernel dirty bit says + otherwise. Today every draw still enqueues a refresh (`Shadow::refresh` `shadow.rs:3155`): [M] 9,551 flushes/frame, 8,477 (89 %) + "known to copy nothing" and still 9.8 ms. A per-copy `epoch` (set by guard fault / one batched `GetWriteWatch` per region + per frame) lets `defer_refresh` return in one atomic compare, recorded once per list instead of per draw. +- Classes persisted with R1's profile so frame 1 already starts with the right state. +**Files:** `shadow.rs` (`refresh`, `nothing_new`, `watched`), `host.rs:7250 defer_refresh`, `watch.rs` (epoch), +`xmem.rs:189` (flag capture). + +### R4. One batched write-watch ask per region per frame - est. 2-3 ms/frame, risk low +`watch::asked/writes` (`watch.rs:660,674`) are asked per range; 4.1 ms/frame, 3.5 ms of it kernel asking. Ask the 3-5 +large regions (174 MB heap, page pool views) once at frame start, publish into the journal, and let all refreshes read the +journal (they already can: `asked()`). + +### R5. Texture residency: late loading is VRAM-room bound, not CPU-bound - est. late load 5 min -> 1-2 min [H], risk medium +**[M] evidence (lines 5430-20000 region, texture-room lines):** +- `no room, new textures wait` from 09:49:47 until the end: "8,092 MB in use - 1,500 MB free in texture blocks + 115 MB card + copies + 1,846 MB render targets = 8,553 MB against a line of 7,932 MB (80 % of a budget of 9,915 MB)". +- Queue: 25,875 slots (09:49:47), 520 due with oldest waiting **533 frames** (09:50:08), 17,991 slots at 50:23. +- Uploads stall at 55,000 textures / 3.1 GB for ~60 s (09:50:02-09:50:23), then burst +12,000 at 09:50:29. +- Plus "textures picked by index: 15,195 passed over unmapped" - title had not mapped them. +- Settings cause part of it: `play.rs:213` sets `VICTORY_TEXTURE_ROOM_PERCENT=80` with frame generation (86 without), vs the + computed `line_for` (95 %); `VICTORY_LEVELS_ON_DEMAND=0` (`play.rs:58`) although `docs/README-fxceless.md:69` + measured 3.1 GB of card memory not allocated for levels the title does not hold ("no device loss"). tiles.rs:20-50 + quotes run 189: 2.2-3.0 GB of 4.3-5.5 GB copies were unmapped levels. +**Design:** +1. Turn levels-on-demand on by default on tier-2 tiled cards (RTX 4070 qualifies) and re-measure: frees ~2-3 GB, i.e. the + whole "no room" deficit (621 MB) several times over. +2. Add usage feedback instead of uploading by written order: the pass uploads textures picked by index in the order the title + wrote the slots (`draw.rs:3140+`, `HEAP_TEXTURES_QUEUE`), with no knowledge of which are sampled. `memory.rs` already has + the pattern for pages ("faults the shaders found empty, read back once a frame"). Do the same for descriptor-heap indices: + shaders OR the index into a visibility bitmap, read back once a frame; upload used slots first, evict slots unseen for N + frames. (Nothing like it exists: grep for slot-use feedback is empty.) +3. Persist "textures used in this area" (key: texture fingerprint, `texture::fingerprint(at, len)` exists) so the next session + prefetches the first-minute set as soon as the title writes the slots. +4. Do not hold 1.4-1.5 GB "free in texture blocks" as unusable: it is counted in "in use" and then subtracted; check whether + `pool.rs` blocks of one size class can serve another (`Pool::take` `pool.rs:211`). +**Files:** `resource.rs` (`room`, `line_for`, :1963-2000), `draw.rs` (`heap_textures` ~3140), `pool.rs`, `tiles.rs`, +`apps/victory/src/play.rs:58,213`, shader emit for the visibility bitmap (victory-shader). + +### R6. Descriptor records: dirty-slot list from guards instead of scanning - est. 5-8 ms thread / 2-4 ms critical, risk medium +[M] 210 k slots looked at for 9 k new; 124 of 200 changed pages are guarded views, so the fault handler can note the +4 KiB heap page (and the slot range from the fault address) at the instant the title writes; then compare only those +slots. Also cache record bytes -> host view (content-addressed), since 13 k of the mirrored are "no views" (empty). +Files: `descriptor/host.rs`, `heap_marks.rs`, `watch.rs`. (Probably owned by the descriptor agent; listed because it is the +same noticing problem.) + +### R7. Guarded-store handling by default (`VICTORY_STORE_BESIDE` / `COPY_BESIDE`) - est. 1-3 ms title-thread time, risk medium +`titlewrite.rs`: 590 write faults/frame, a protection change is ~5 us and serialised. Both options exist and are off. +Evaluate on the current build (store beside + memcpy interposition) against the run `faults-1` numbers; the prior measurement +was 69 ms of threads' time before fixes -> ~6 ms after (`docs/findings.md` table), so most of this may already be gone. + +### R8. Textures: skip hash for textures learned as write-once - est. 1-3 ms thread time, risk low +`texture.rs:1570-1620`: view-memory textures are hashed whole whenever not write-watchable. The `once` flag already exists +(`texture.rs:1448`); extend it with the persisted classes of R3. + +## 3. Things that were checked and are not worth it (or are blocked) + +- Full in-place heaps (`VICTORY_INPLACE=2`) for hot GPU-read data: the card would read system memory over PCIe (docs: the + constants heap in place made the card wait). Blocked for view memory (SEC_RESERVE). Only upload-class memory (R3) is a candidate. +- Bigger landing thread pools: the 4 threads are already waiting 8.9-10.4 ms "for the title's bytes going in" + (line 22003); the problem is volume, not parallelism. +- Replacing the title's `memcpy` (`COPY_BESIDE`) with more hooks: marginal compared to R1. + +## 4. Suggested order and measurement + +1. **Measurement patch (no behaviour change):** per-copy counters of distinct 64 KiB blocks changed by the card, of landed + blocks read by the CPU (probe mode), of blocks the title CPU wrote while pending (the 61 k runs), keyed by copy id. + Decides R1/R2 gains before any risky change. Log once per 5 s next to the `shadow:` lines. +2. R3 + R4 (low risk, a few ms). +3. R1 (largest) with persistence, probation, kill switch. +4. R5.1 (turn on levels-on-demand, a settings change) immediately: cheapest test of the late-loading hypothesis. +5. R2 only after R1 data shows how much remains. + +Open questions that need data rather than code reading: (a) fraction of the 174 MB heap's blocks ever GPU-written; +(b) which non-WC GPU-written ranges the title CPU actually reads; (c) why uploads pause for ~60 s while "no room" holds +(eviction policy vs. title streaming), i.e. whether `no room` alone explains the 5 minutes. diff --git a/docs/performance/AGENT_REPORTS/03-descriptors.md b/docs/performance/AGENT_REPORTS/03-descriptors.md new file mode 100644 index 000000000..29dca4b0c --- /dev/null +++ b/docs/performance/AGENT_REPORTS/03-descriptors.md @@ -0,0 +1,299 @@ +# 03 - Descriptor and resource architecture + +Scope: `crates/victory-gpu` descriptor.rs, descriptor/host.rs, heap_marks.rs, the descriptor +parts of draw.rs, watch.rs. root.rs, signature.rs, sampler.rs, external.rs and port.rs are +not hot (small, set up once or per pipeline). Read-only study, no source edited. + +Evidence labels: **[S]** static (read from code), **[M]** measured (log line), **[H]** hypothesis. +Main log: `%LOCALAPPDATA%\victory\logs\play-20261127-095317-11396.log` (steady state 09:56:34-09:58, +72-80 ms/frame, 7,100 draws; loading phase 09:54:10-09:56:40, 250-380 ms/frame). + +## 1. How the machinery works (S) + +- The console's descriptors are 32-byte records in plain title memory (descriptor.rs:1-8). The title + creates them with API calls (`create_srv` etc., descriptor.rs:1557) and also builds a table per draw + by **copying records as bytes** into its own shader-visible heap, with no API call (descriptor.rs:418-427). +- Our record is only `{VIEW_TAG, i, generation}` (12 bytes, descriptor.rs:1466-1475), so bytes survive being + copied. `i`/`generation` name an interned `View` in the global `VIEWS` RwLock table (1079-1103), or inline + the constant/placed address (1105-1192). +- Translated shaders index a **host heap that mirrors the title heap slot for slot** (`HostHeap`, + host.rs:126). Every title slot must therefore have a host descriptor before a shader can pick it. + Three routes make one: + 1. API-call route: `record()` -> `mirror(handle)` (descriptor.rs:193) -> `HostHeap::mirror` (host.rs:3877). + 2. Draw route: `State::tables` (draw.rs:4423) / `table_entry` (4390). A table with a CBV or indexed + entries gets a **fresh run of dynamic slots per draw**, each `make_at`/`make_listed` (host.rs:3448/3464). + 3. Byte-copy route: `sync_heaps` (descriptor.rs:428-636) asks the kernel which 4 KiB pages of the + heap changed (`Tracked::take`, watch.rs:781 -> `GetWriteWatch`), reads them, compares each 32-byte + record with the one last seen (`Copied::changes*`, host.rs:5279+), and mirrors the new ones. + It runs on thread `victory-heap-sync` (descriptor.rs:265-327), a round per submission plus an + "early" round every 4 ms. +- Slots a shader picks **by a computed index** (bindless) are served by two passes that run on a + recording thread once per frame at the first list that needs them (draw.rs:2378 `heap_buffers`): + `heap_buffer_pass` (draw.rs:1164) makes host slots for all buffer views and refreshes the host copy + behind each one; `heap_textures` (draw.rs:3033) uploads textures whose slots wait in `TextureQueue` + (host.rs:1179, a `BTreeMap` behind one `Mutex`). + +## 2. Measured numbers (M, steady state, per frame) + +| Item | Value | Source | +|---|---|---| +| Heap pages with changes / slots looked at / slots mirrored | 264-285 / 271-297k / 8.0-9.9k | "descriptor records..." line | +| Of the changed records: new table records left to draws / waited for a draw / waited, no draw came | 27-32k / 8.9-11.9k / 2.1-2.2k | same | +| Bytes read per frame | 16.5-17.8 MB (about 63 KB per changed range, i.e. ring pages are rewritten almost whole) | same | +| `sync_heaps` wall | 25-29 ms (asking 6.3-9.9, reading+comparing 2.9-4.7, making 4.7-8.2) | same | +| Submitting thread waiting for those rounds | 0.25-1.4 ms, plus 0.6-1.0 "heaps' records and what is swept" | "preparing per frame", heap_marks lines | +| Raw twins of buffer views made | 17.3k (590 of them off 16 bytes and null) | "raw twins" line | +| View-slot writes (note_buffer path) | 14.3-17.0k | "writes of view slots" line | +| Texture-view slot writes | about 640 placed + 1,030 object per frame | "texture slots written so far" deltas | +| Heap-picked buffer set | 139k views, 4,519 host copies, 2,448 MB | "made ready for shaders that pick them" line | +| Refreshes on the submitting thread | 16-18 ms in 37-41 flushes of about 6,400 copies, about 5,350 known to copy nothing | "preparing per frame" line | +| Texture queue lock | 32-37k takes / 5 s, 664 ms waited / 5 s (558 by non-pass threads), 857k takes avoided by marks | "texture queue's lock" line | +| Views table lock | about 410 ms waited / 5 s by non-pass threads | "its rest" line | +| Texture queue | 10.8k slots, 9.6-9.8k "uploaded whole, waiting to be looked at again" | "textures picked by index, the queue" | + +Loading phase (09:54:10-09:56:40, about 150 s at 3-5 fps, 250-380 ms/frame): +- Queue 23-32k slots waiting, "37,715 held back for room" in one 5 s window; texture line 8.2 GB against + a 10.3 GB budget with 9.6 GB in use. 700 -> 60k textures uploaded (3.1 GB) over 2.5 minutes. +- "new card memory waited for until it is mapped" 18,200 times, 7.15 s; the waits were 0.1 ms each at the + start and 2-4 ms each at 09:55:34-09:56:06. +- `list::thin` 55k calls cost 961 ms (all threads) against 300-325 ms in steady state; the title waited + 229 ms/frame at presents while our submitting thread worked 65 ms; the card was 20% busy. The frame is + limited by recording/translation threads, not by the card or the preparing thread. +- Lock waits of the two descriptor locks in loading: queue 664 ms + views 396 ms + pass 145 ms per 5 s + (about 75 ms/frame of thread time at 3.2 fps). The texture pass itself: 777 ms per 5 s, 413 ms in + the frame's passes, 40 stopped at their time (draw.rs:3173-3186: 250 ms, tripled to 750 ms by catch-up). +- The title writes about 535k placed and 193k object slots in the first 80 s (frame lines). + +## 3. Mechanism by mechanism: why, requirement or artifact, why per frame, can it go + +### 3.1 Mirror heap with identical slot order +- Why: translated shaders index the heap by the title's descriptor positions (host.rs:1-6). [S] +- Requirement for bindless picks (ResourceDescriptorHeap[i] on D3D12 needs a real descriptor at i). + Artifact for table reads: those are bound by draw, and we already create fresh dynamic copies per draw. +- Per frame: the title rewrites its tables every frame (ring), and the records name new addresses. +- Can it go: not the mirror for bindless picks. The mirror for table-read slots can be skipped + (it already largely is: "left to the draws"). + +### 3.2 `sync_heaps` (write watch, read, compare, mirror) +- Why: no API call sees the title's byte copies (descriptor.rs:418). Requirement: some route to + find those writes. The write watch is the only non-invasive one. [S] +- Artifact: it scans 8.5 MB (271k slots) a frame to find 8-10k records, 3% hit rate. The pages + it reads are the title's draw-table ring: 27-32k new records per frame are "of draws' tables, left to + the draws", meaning the scan finds, compares and then discards them. [M] +- Per frame: rounds are asked per submission (17 a frame) and every 4 ms; asking costs 6-10 ms + of sync-thread time per frame (about 0.4-0.5 ms a round, `Tracked::take` -> `GetWriteWatch` over the + heap range plus a `BTreeMap` of last seen writes under a mutex, watch.rs:786-789). [M for total, H for per-round] +- Mostly off the critical path: the submitting thread loses 0.3-1.4 ms waiting plus about 1 ms. It does + use the shared `land::each_view` workers and 25-29 ms of wall on fast cores that 8 translation + threads and the title also want. [H: 2-5 ms/frame of contention] +- Can it be anticipated/persisted/eliminated: see opportunity C. + +### 3.3 Fresh dynamic tables per draw (`State::tables`, draw.rs:4423) +- Why: CBVs must be 256-aligned on the host and constant bytes are copied to scratch per draw + (draw.rs:4411-4416, 4641-4649); indexed ("descriptor array") tables need all n entries. Requirement of + the alignment mismatch, artifact in that it is done by recreating descriptors. +- Per frame: constants live at new addresses each frame (the comment at descriptor.rs:1067 puts it at + 14,000 CBV writes a frame), so a per-list key hashes the n record words (4495-4503) and a per-recording + `ListViews` (host.rs:3464) caches descriptors only until the recording changes (`views.made.clear()`). +- Costs: 17.3k twins and the views they twin are created per frame (`twin_window` counter, host.rs:4454; + one buffer view = typed/structured view + raw twin = two `Create*View`). 222 lists a frame means + about 78 twinned buffer views per list, many identical across lists. [M count, H cost] +- Can it go: the per-recording cache can be made global (opportunity B). + +### 3.4 Interned view table (`VIEWS`) +- Why: records are 12 bytes and must survive byte copies; the table gives them identity and a + generation so released resources go stale (descriptor.rs:1056-1078). Requirement. +- Artifact: `BTreeMap<View, u32>` keyed by a `View` that can be 27 u32 (sampler) or 30 u32 (placed); + a write lock for every new view and for every `forget(resource)` (descriptor.rs:1478-1502); every + `view_at` clones the `View` under the read lock, including in the `mirror` quick path (host.rs:3900-3906), + which is meant to be the cheap one. Measured 410 ms/5 s waiting by non-pass threads (about 6 ms/frame + of thread time). [S + M] +- Can it go: reads can be lock-free (opportunity E). + +### 3.5 Texture queue (`TextureQueue`, host.rs:1179) +- Why: textures the title fills itself (placed memory) have no host texture until something reads them. + Table reads upload them at draw time; bindless picks need a pass over every such slot because nothing + says which one a shader will pick. Requirement given the bindless model, artifact in the lock design. [S] +- Per frame: 640 placed + 1,030 object slot writes a frame; each takes the queue's mutex unless the mark + says nothing changes (QueueMarks, host.rs:1082): 32-37k takes and 857k avoided per 5 s. [M] +- The queue is single mutex, `BTreeMap<u32, Waiting>`, plus `held` map; the due scan walks it under lock + (`due_and_census`, host.rs:1252: held 57-84 ms / 5 s). Writers wait 558-1,260 ms / 5 s. [M] +- Can it go: structurally yes (opportunity D) and the volume can be cut by demand (opportunity A). + +### 3.6 Bindless buffer pass and refresh coverage (`heap_buffer_pass`, draw.rs:1164) +- Why: a shader may pick any buffer view of the heap, so every host copy a buffer view shows must be + fresh when the list runs, "nothing tells us which of the heap's a computed index names" (draw.rs:2370). + Requirement under the current model, but it is a **conservative over-approximation**: 139k views + over 4,519 host copies, 2.4 GB, are declared read by every frame. +- Per frame: it is the set that is refreshed, per frame, because the title writes buffers every frame. +- Cost: part of the submitting thread's "refreshes 16-18 ms in 37-41 flushes of about 6,400 copies, 5,350 + known to copy nothing". The heap set is about 4,500 of those 6,400 copies. [M for counts; H that most of the 16 ms is + attributable to them, no measurement separates it. Experiment in section 6.] +- Can it go: opportunity A (demand). + +### 3.7 Raw twins (`RAW_TWINS`, host.rs:1864, `twin_window` 4454) +- Why: shaders that load a typed/structured buffer with raw loads read a byte-addressed alias at slot + `raw + index` (victory-shader `emit::raw_views`). Requirement of the shader translation. +- Per frame: created along with each buffer view made for a draw table or the buffer pass (17.3k a frame). + Persistable: the view is a pure function of (resource/shadow identity, range, format, stride). + +### 3.8 `WAITING`/`make_waiting`, `show_after`/`show_new_later`/`kept views` +- Why: a texture view written before its texture has a host copy is left null until first use + (descriptor.rs:1378-1464); an upload still in flight must not be visible (device loss every 16 min before + SHOW_AFTER, findings.md). Requirement. Counters: 40,000 slots shown after upload, 39,123 on the + neutral texture meanwhile, 64.8k "kept what they showed". [M] +- Per frame, small. Not a priority except that all of these go through `FLIPS`/`NEW_PENDING` mutexes + (host.rs:3983-4005); fine while the volume stays at hundreds a frame. + +### 3.9 `Made`/`kept`/`quick` per-slot arrays and the 512 locks +- Why: slots are made by several threads; a key per slot plus lock stripes (host.rs:93-122). Already + tuned (profile thin-2 in the comment). `kept` is a `Mutex<Option<ID3D12Resource>>` per slot, so a host + COM pointer is `AddRef`'d and replaced under a mutex for every make (host.rs:3564-3583). Minor. + +## 4. Ranked opportunities + +Estimates are for the submitting/critical path in ms/frame unless stated; thread-time is the sum +over all threads. All estimates are [H]; counts above are [M]. + +### A. Demand feedback for slots picked by index (GPU-written "picked" bitmap) +- Replaces: the "everything the heap names" assumption of `heap_buffer_pass` (draw.rs:1164) and + the all-or-nothing upload queue of `heap_textures` (draw.rs:3033). +- Design: translated shaders already know when they pick a heap slot by a computed index (the + `SLOT_STRIDES` table and raw twins prove the emitter distinguishes them). Add, at that site only, an + `InterlockedOr` into a per-slot bit table in a UAV buffer (1 bit per slot: 8 KB per 64k slots; + clear it per frame). Read it back with two frames of latency through a readback buffer (the relay + thread that lands results already exists). Then: + - buffers: the heap pass refreshes only host copies whose slots were picked in the last N + frames, plus slots written since (fallback: refresh stays as today for slots of unknown state, one + of every 16 passes already exists: `HEAP_ROUND`, draw.rs:702); + - textures: queue priority by "picked last frame", upload only those; the rest stay neutral (the + neutral stand-in and `show_after` already exist, host.rs:411-527, 337-357). +- Estimates: steady state 4-10 ms off the submitting thread if the heap coverage explains most of its + refreshes (see experiment E1); the loading phase (2.5 min at 250-380 ms/frame, 60k textures, + 3.1 GB) probably shrinks several-fold if the number of textures actually sampled is a small share + of the queue. Neither is measured. +- Risk: medium-high. Pop-in of 1-3 frames; shaders that read through waterfalls or descriptors written + and read in the same frame; the ocean height/displacement read-back (texback) must stay on the + non-demand path. Mitigation: A/B switch and keep the full pass available (`VICTORY_HEAP_DEMAND=0`). +- Files: victory-shader `emit` (instrumentation), `descriptor/host.rs` (bitmap + consumer), + `draw.rs` `heap_buffer_pass`, `heap_textures`, `TextureQueue::due*`. + +### B. A persistent descriptor cache across lists and frames +- Replaces: `ListViews` rebuilt per recording (`views.made.clear()`, host.rs:3464-3478) and the `Create*View` + work per twinned buffer view. +- Design: a global CPU-only staging descriptor heap, keyed by the interned record `(i, generation)` plus + the host copy identity (`Shadow::id`/gpu address, since the host copy can be replaced), holding the + typed view and the raw twin in adjacent slots. A draw or the buffer pass obtains slots with + `CopyDescriptorsSimple` (already used: `copy_from`, host.rs:3513) instead of `CreateShaderResourceView`. + Invalidate on `forget(resource)` (descriptor.rs:1478, already bumps the generation, so a stale key + cannot hit) and when the shadow's GPU address changes. Constant buffer views stay per draw + (`View::Constant` is rejected by `make_listed`, host.rs:3477). +- Estimate: 17.3k twinned views = about 34k `Create*View` a frame. At 0.5-1 us each that is 17-34 ms of + thread time, spread over the translation threads (8 on this machine), so 2-4 ms of wall. [H, not + measured: the code does not time view creation. Add a counter first.] +- Risk: low-medium. Lifetime of the host resource (descriptors for released host copies must not be + copied: `keep` and `retire_resource` already govern that). +- Files: `descriptor/host.rs` (`make_listed`, `make_at`, `twin_window`, `make_twinned`, `ListViews`). + +### C. Stop scanning the title's table ring; gate rounds on need +- Replaces: `sync_heaps` reading/comparing pages that are tables (descriptor.rs:486-592) and the 4 ms/ + per-submission rounds (descriptor.rs:241-416). +- Design in three small steps: + 1. A page whose changed slots are, for several consecutive frames, >90% `copied_tabled` or "of draws' + tables" is a **ring page**. Skip its read/compare/mirror (keep the `Tracked` bookkeeping). The draws + read those records directly (`view(handle)` at draw.rs:4525, 4640), so nothing is lost for them. + Slots in a ring page that a bindless shader picks are exactly what opportunity A's bitmap detects; + until then keep a low-rate sweep of ring pages (1 of 16 rounds, like `HEAP_ROUND`). + 2. A list sets a flag when it records a pick-by-index draw (`heap_buffers`/`heap_strides`/`lent_heap`). + `begin_sync_heaps` for a submission is asked only when one of its lists has it set. Dirty ranges accumulate in + `Tracked`, so one round in a frame (the first submission with picks) is enough. + 3. Coalesce the kernel ask: one `GetWriteWatch` per round across both heaps, not per heap; keep + `seen` as a flat per-page `Vec<u64>` instead of a `BTreeMap` behind a mutex (watch.rs:789). +- Estimate: sync-thread time 25-29 ms -> about 8-12 ms (asking is about 7.7 ms of it and falls with rounds; + reading/making fall with the ring skipped); critical path 1-2.5 ms (waiting 0.3-1.4 + 0.6-1.0), plus + relief on the shared worker pool and fast cores (H: 2-4 ms/frame wall). This is the cheapest of the ranked items. +- Risk: low for step 2, medium for step 1 (a bindless-picked record on a ring page would go stale; the + sweep and the bitmap cover it, and a diagnostic can count "mirrored from a ring page later read by a draw"). +- Files: `descriptor.rs` (`sync_heaps`, `begin_sync_heaps*`, `round_after_now`), `heap_marks.rs`, + `descriptor/host.rs` (`copied_tabled`, `Copied`), `watch.rs` (`Tracked::take`), `draw.rs` (flag). + +### D. Lock-free texture queue +- Replaces: `Mutex<TextureQueue>` + `BTreeMap` (host.rs:1179, 2206-2232) and its 7 lock sites + (`queue_site`, descriptor.rs:42-60). +- Design: per slot an atomic word `{state, due_frame, write_seq}` in a `Vec<AtomicU64>`. Writers do a + single CAS and push the slot into the existing lock-free `Slots` bitset (host.rs:29-83: dirty set). + The pass (one consumer thread at a time, as `IN_TEXTURE_PASS` already assumes) takes the dirty bits, orders + by `due`/`write_seq` and does everything else on its own non-shared structures (`held`, census). + `QueueMarks` (host.rs:1082) is the first half of this idea; make it the whole thing. +- Estimate: 558 ms/5 s steady (about 8.5 ms of thread time per frame) and 664+145 ms/5 s in loading + (about 50 ms of thread time per frame at 3.2 fps) of waits disappear. Wall effect 1-2 ms/frame + steady; in loading it removes a share of the 3x inflation of `thin` (961 ms vs 300 ms), which + the other loading causes (memory, staging) also drive. [M for waits, H for wall] +- Risk: medium (ordering semantics in `TextureQueue::written/later/hold/recheck`: unit tests exist, host.rs:6158+). +- Files: `descriptor/host.rs` (`TextureQueue`, `QueueMarks`, `queue_texture`, `tabled_in*`), `draw.rs` `heap_textures`. + +### E. Lock-free `VIEWS` +- Replaces: `RwLock<Views>` with two `BTreeMap`s (descriptor.rs:1095), `view_at` clone per lookup. +- Design: entries in an append-only chunked arena (stable addresses), `generation` an `AtomicU32` per entry, + readers take no lock: `view_at(i, g)` checks the atomic generation, reads the immutable `View`, and + returns `&View` or `Arc`. Writers (new view, forget) use one writer mutex and a sharded hash index + (e.g. 64 shards by hash of the `View`) in place of the global `BTreeMap` index. +- Estimate: 6 ms/frame of thread time in waits (410 ms / 5 s, steady); more in loading (396 ms / 5 s). + Wall 0.5-1.5 ms. `forget()` stops blocking every reader when textures are released in bulk. +- Risk: low-medium. Files: `descriptor.rs` (`Views`, `view_at`, `words_for`, `forget`, `views_read/write`). + +### F. Stop the per-slot COM traffic in `keep` +- `kept: Box<[Mutex<Option<ID3D12Resource>>]>` (host.rs:175) clones and swaps a COM pointer under a mutex + per make. With B in place a draw's dynamic slots can take `Arc`-less "borrowed by the cache" references + retired in bulk at list reset (`crate::host::retire_resource`). Small (about 1 ms of thread time). Skip unless B lands. + +### G. Long-term: make the shader read the title's records and resolve through a persistent table +- Idea: have the shader read the 12-byte `{tag, i, generation}` record from a GPU-visible alias of the + title heap (e.g. `ID3D12Device3::OpenExistingHeapFromAddress` over the title's heap memory; **unverified** + whether the title's `MEM_WRITE_WATCH` placement allows it) and index a persistent global descriptor + table by `i`. This removes the host mirror, the byte-copy scan (3.2) and the fresh per-draw tables + for non-CBV tables. Cost: placed texture/buffer and constant views carry addresses, not entries + (descriptor.rs:1067-1078: 2.45M entries in 4 minutes if interned), so they need either an + address-keyed resolver on the GPU (raw loads, no descriptor) or a persistent LRU. A large rewrite of + `victory-shader::emit`. High risk, one to two months. Do not start before A, B, C, D, E are measured. + +## 5. What the data says about "late loading" (about 150 s in this run; user reports about 5 min) + +- Loading frames are CPU-bound on recording/translation threads (card 20% busy, title waits 229 ms/frame at + presents, `thin` 961 ms vs 300). The descriptor locks account for about 8% of thin's thread time. [M] +- The structural cause visible in my area: after world entry the title writes a large part of its texture views + at once (535k placed slot writes in 80 s), and the pass uploads each as a host texture (3.1 GB, 60k) under a + per-frame time/byte budget (draw.rs:3173-3186) that runs on the recording threads and holds back slots when + the 8.2 GB line is full (37.7k held in one window). Most of those uploads are for textures no draw samples + yet. [H: needs the picked bitmap of A to prove] +- Memory waits: 18.2k "new card memory waited for until it is mapped" = 7.15 s, concentrated when the line was full. [M] +- First experiments (no new code): `VICTORY_TEXTURE_STAGE_MB`, `VICTORY_TEXTURE_CATCHUP=0`, + `VICTORY_HEAP_TEXTURES=0` (draw.rs:3041) to see the frame time and visual cost without the pass. + +## 6. Measurements to add before building (cheap) + +- E1: gate `heap_buffer_pass` coverage (a switch that uses only slots written in the last N frames plus the + sweep) and read "refreshes" in the preparing line: tells how much of 16-18 ms is bindless coverage. +- E2: time and count `make_twinned`/`CreateShaderResourceView` calls on the translation threads (a per-thread + counter flushed in batches, as `not_taken` does); gives B's real value. +- E3: count how many of the 4.5k heap copies and 10.8k queue slots a shader actually picks per frame (A's + bitmap, even diagnostic-only, reading back every 30 frames). +- E4: split the "asking" 6-10 ms of `sync_heaps` into kernel call and journal work (`Tracked::take`, `writes`). +- E5: a one-line counter of ring pages (changed pages where tabled share >90%). + +## 7. Priorities in one table + +| Rank | Opportunity | Est. critical-path ms/frame | Thread-time relief | Risk | Effort | +|---|---|---|---|---|---| +| 1 | C. Gate and coalesce heap rounds, skip ring pages | 1-2.5 | 12-17 ms | low-med | days | +| 2 | A. Demand bitmap for picked slots | 4-10 (steady, unproven), loading time several-fold | large | med-high | 2-3 weeks | +| 3 | B. Persistent descriptor cache | 2-4 | 17-34 ms | low-med | 1 week | +| 4 | D. Lock-free texture queue | 1-2 (more in loading) | 8-50 ms | med | 1 week | +| 5 | E. Lock-free views table | 0.5-1.5 | 6 ms | low-med | 3-4 days | +| 6 | F. Drop COM traffic in `keep` | under 1 | 1 ms | low | days, after B | +| 7 | G. Shader reads records | unknown | very large | high | months | + +Caveats: sum of the above is not additive; the heap-sync thread is already beside the preparing thread, so the +direct gain from C is small and the main gain from C, B, D, E is shared-core relief that helps translation +threads (`thin` 300 ms over 8 threads) and the title's own threads. The preparing thread's 70 ms is mostly +buffer refreshes and steps (outside this report) except where A and its 4,500 copies matter. diff --git a/docs/performance/AGENT_REPORTS/04-shader-pipeline.md b/docs/performance/AGENT_REPORTS/04-shader-pipeline.md new file mode 100644 index 000000000..f0225669b --- /dev/null +++ b/docs/performance/AGENT_REPORTS/04-shader-pipeline.md @@ -0,0 +1,130 @@ +# 04 - Shader and pipeline architecture + +Scope: `crates/victory-shader`, `crates/victory-gpu` (`pipeline.rs`, `pipeline/{make,library,known,host}.rs`, `shader_cache.rs`, `indirect*.rs`, `device.rs`), `apps/victory/src/warm.rs`. +Machine in the logs: RTX 4070 (driver 621.1), Series X profile, 1440p, DLSS balanced + frame gen. Read-only analysis; no source edited. +Labels: **[S]** static (read from code), **[M]** measured (from `%LOCALAPPDATA%\victory\logs\play-20261127-*.log` and the `cache\pipelines` files), **[H]** hypothesis. + +## 1. Headline + +The "~5 minute late loading" is the host driver compiling about 1,360 pipelines after the world starts, on the render path's wait budget. It is not shader translation. + +- **[M]** Translation is fully cached. Warm runs show `hits=1276 misses=0` about 18 s after start, and all 2,731 shader translations are logged within the first seconds of loading. The cold run (093037) showed `hits=0 misses=2717`. +- **[M]** The pipeline library is persistent (428 MB, mapped, loads fine: `loaded=1139`). Yet every warm run still reports `made ~1,360` host pipelines, the same as a cold run (cold: `made=1991 loaded=495`; warm: `made=1362 loaded=1139`). +- **[S]** Cause, commit `7fa0e95` ("Pipelines with static samplers are not loaded from the pipeline library"): `library::pipeline()` ignores the library whenever `STATIC_SAMPLERS` is set, so those pipelines are compiled by the driver every run and never stored (`pipeline/library.rs:572`, `pipeline/host.rs:604`). +- **[M]** The numbers agree: 1,362 / (1,362 + 1,139) = 54% of used pipelines. Of the 2,731 translated shaders, about 1,250 have `samplers>0` (pixel 5/2/1/7/3/6/4, compute 1/2/7/...). It fits, but I have not matched pipeline by pipeline. + +## 2. What the logs show (measured) + +| Run | Loading to world | Pipelines still being made at world entry | Frames after world entry | +|---|---|---|---| +| 093037 (cold) | ~60 s | 924 | 290-313 ms for ~2 min (09:31:48-09:33:14), then 56-62 ms. "all made" at +5m11s | +| 094255 (warm) | ~2 min | ~0 | 49-80 ms | +| 094655 (warm) | ~2 min | 0 | 48-81 ms (2,700 draws dropped for 20 s, then 260) | +| 095317 (warm) | ~60 s | 525 | 250-340 ms for ~2.5 min (09:54:20-09:56:30), 78-80 ms until mk=2 (09:57:54), 59-72 ms after | + +- **[M]** `made` grows steadily through the run: 451 at +26 s, 863 at +66 s, 1,191 at +2m30s, 1,362 at +4m40s (run 095317). `host pipelines all made` fires at +4m44s. +- **[M]** Whether the stall appears depends on how long the title's own loading screen lasts. Run 094655 had a 2-minute loading screen and the workers finished first (`mk=0` at world entry). Run 095317 had 1 minute and did not. The compile work is the same in both, about 125-280 s of 8 workers at lowest priority. +- **[M]** The 250-340 ms frames coincide with `mk` falling from 525 to ~150 and with 290-1,300 draws dropped per frame (`dropped N without a host pipeline`). Steady state afterwards is 50-80 ms. +- **[M]** `slow-pipelines.txt` has 907 keys of 1 s or more, summing to 4,380 thread-seconds (maximum seen per key). 236 are 5 s or more, 149 are 10 s or more (2,350 s), and the worst is 58.8 s. All 907 are in `early-pipelines.txt` (5,539 keys). Those figures are maxima, so they include cold-run contention. +- **[M]** `known-pipelines.bin` holds 83,555 title pipelines from 19,100 shaders (50 MB, plus 198 MB of containers). About 2,500 are started early per run. +- **[M]** `victory warm` has never run on this machine: `warm-done.txt` and `warm-bad.txt` are 0 bytes. +- **[M]** The NVIDIA driver cache `%LOCALAPPDATA%\NVIDIA\DXCache` is 7.9 GB. The comment in `library.rs` says the driver's own cache "keeps that quick" for static-sampler pipelines. +- **[H]** The logs do not show whether the driver cache really hits for these. The 125-280 s of work for 1,362 pipelines on 8 workers (~0.7-1.6 s each) suggests many are not quick. A per-pipeline `made in N ms` line is only emitted through `host::trail` (diagnostics builds), so release logs cannot confirm it. See item 1 (instrumentation). + +## 3. How pipelines are made today (static) + +- **[S]** The title's `CreateGraphicsPipelineState` and `CreateComputePipelineState` only record the shader containers and the graphics state. `pipeline.rs:569 hand_out` builds a `make::Pending` (key = BLAKE3 of stage, shader hash and `GraphicsState::describe()`). +- **[S]** `known::note` appends the pipeline to the book when `VICTORY_PIPELINE_BOOK=1` (`play.rs` sets it). `make::early` starts it at creation only if its key is in `early-pipelines.txt`, or it is a hard-coded `scene_input` shader or a bake pixel shader (`make.rs:129`). +- **[S]** Everything else is queued on first draw: `make::ready()` starts it as `REQUESTED` and waits on the title's render thread. The wait is a shared 500 ms per frame (`VICTORY_PIPELINE_WAIT_MS`) and 10 s for screen passes (`VICTORY_SCREEN_WAIT_MS`, below the title's 30 s watchdog). Past the budget the draw is dropped and retried next frame. +- **[S]** Workers: `worker_count_for` gives `processors*2/3` clamped 2-16, or `processors*3/4` clamped 2-8 under `residency::limited_host_ram()`. The log shows 8 (limited-RAM path). They run at `THREAD_PRIORITY_LOWEST` (`make.rs:566`), below the title's loading threads. Two extra workers take only screen passes. +- **[S]** Queue order is screen, then `requested`, then `early` (FIFO in title creation order, not first-use order), then `slow`. Known-slow keys (`library::slow`) are capped at `slow_limit()` = workers/4 = 2 concurrent unless a draw promotes them. +- **[S]** `HostPipeline::new` (`host.rs:417`) does translate (disk-cached), then builds a root signature per pipeline (no cache), then `library::pipeline` (load, else create then `StorePipeline`). Library file name = BLAKE3 of root-signature blob, shader code and state, so it changes with any translator change. +- **[S]** The translation cache key (`shader_cache.rs:44 build()`) includes `VICTORY_TRANSLATOR`, the BLAKE3 of the victory-shader sources, plus about 15 `VICTORY_*` env settings. Any edit to victory-shader, or changing one of those switches, means a full cold start: ~2,700 translations plus all pipelines. +- **[S]** `victory warm` (`apps/victory/src/warm.rs`, `known::make`) builds pipelines from the book in idle-priority child processes (40 at a time, 180 s hang kill, `warm-bad.txt`). It writes to the driver cache and to `slow-pipelines.txt`. Pipelines with static samplers now bypass the library there too, so warm only helps if the driver cache hits. It also has to be run by hand. +- **[S]** Emulator helper pipelines are few and separate from the title's. Examples: `indirect.rs` argument clamp, batched clamp and compare passes, `host.rs` card-work and depth-plane pipelines, `inplace.rs`, `compose.rs`, `ambient.rs`. They are HLSL compiled at first use with `D3DCompile` (FXC, `cs_5_1`) plus `CreateComputePipelineState`, with no library. Command signatures are made at first use (`draw.rs:5445`, `indirect.rs:827,2695,2882`). +- **[H]** The helper pipelines are probably tens of ms each once, not the 5-minute tail. They run on the render or submit thread at first use, so they can add single-frame hitches. They are unquantified: the release logs have no timing for them. +- **[S]** Commit `80c70b7` / PR #22 ("helper-priority") raises the submitting thread's helper threads (wide pool, landing pools, heap records) to above-normal. It is CPU thread scheduling and does not touch shaders or pipelines. + +## 4. Ranked structural opportunities + +Estimates are for this machine. "Stall" means seconds of frames over 200 ms after world entry. + +### 1. Make static-sampler pipelines library-storable again (removes ~1,360 compiles per run) +- **Gain [H]:** eliminates the 125-280 s of compile work per run and most of the 130-150 s of 250-340 ms frames after world entry; the warm run would look like run 094655 even with a short loading screen. The library already loads 1,139 pipelines in a few seconds, so loading 1,360 more is cheap. +- **Risk:** medium-high. The reason for `7fa0e95` is real: a pipeline loaded in another process can read through the wrong static sampler (posterized colour grading on the 4070 SUPER, `crates/victory-gpu/examples/lut3d_probe.rs`). +- **Design (the shortcut note in `library.rs:282` already names it):** + 1. Persist a "static sampler registry" (sorted distinct `D3D12_STATIC_SAMPLER_DESC` values seen, at most 2,032 per the probe) next to the library. + 2. At host init, before any title pipeline, create dummy root signatures and trivial PSOs for every registry entry in sorted order. The driver's table then gets the same assignment each process. + 3. Add the registry's hash to the library file name (`library::name` input) so a registry change invalidates only the affected entries. + 4. Add a boot-time canary: a probe pipeline (point, linear, trilinear, as in `lut3d_probe`) is loaded from the library and a texel is checked against a made one. On mismatch set `STATIC_SAMPLERS` handling back to "make". + 5. A new sampler found at runtime is appended, never reordered, and its pipelines are made. + - **Files:** `pipeline/library.rs` (`pipeline()`, `with_static_samplers`, `name`), `pipeline/host.rs:576-604`, new `pipeline/samplers.rs`, the host init in `host.rs`. + - **Gate:** a visual A/B of PS_CompositeNMB (the original failure) and the lut3d probe, on NVIDIA and AMD. +- **Alternative with no driver-order assumption:** replace static samplers with a sampler descriptor table bound from a fixed sampler heap (library-safe by construction). It costs a heap binding per draw and touches the root-signature layout in `host.rs` and `draw.rs`, so it is much larger. + +### 2. Manifest-driven prebuild during loading (order by first use, all workers, higher priority) +- **Gain [H]:** 50-100% of the post-entry stall when item 1 is not done; with item 1 done it also fixes the ~54% of pipelines that need a real compile on a new translator build or driver. +- **Risk:** low. +- **Design:** + 1. **Extend the manifest.** `early-pipelines.txt` is only an unordered set. Replace it with `pipelines.manifest` (versioned, keyed by `{translator hash, driver version, adapter LUID}`). Per key store: `first_use_ms` since process start, `first_use_frame`, `phase` (loading, cutscene or world, from `draws/frame` thresholds or frame number), `compile_ms` for every pipeline (not only 1 s or more), `static_samplers` and `from_library` flags. Writer is `library::note_used` and `library::save`; reader is `library::used()`. Keep the old file readable. + 2. **Order the EARLY queue by `first_use_ms`.** `make::Queue::early` is a FIFO in the title's creation order, which is unrelated to use order. Make it a priority queue (`BinaryHeap` keyed by rank) so the first 300 ms of the world are made first and everything used only late comes last. + 3. **Lift the slow cap while loading.** `slow_limit()` = workers/4 starves 907 known-slow pipelines during loading, which is the best time to compile them. Allow all workers on `slow` until the first world frame, then drop back to `workers/4`. The frame signal is `frame::current()` or a draws/frame threshold. + 4. **Raise worker priority during loading.** `THREAD_PRIORITY_LOWEST` is right once the world runs, but while the title loads with a spare CPU budget a short `BELOW_NORMAL` or `NORMAL` window up to the first world frame costs nothing visible. Measure on a short loading screen. Use all `processors*2/3`, not the limited-RAM 8, when RAM allows. + 5. **Loading gate (optional, only if 1-4 are not enough).** At the first frame where `waiting()` is above N and draws/frame jumps (world entry), raise the shared wait budget for pipelines in the manifest's world-entry set to a one-off value (for example 15-20 s, below the 30 s watchdog) instead of 500 ms a frame. This trades ~2.5 min of 280 ms frames and dropped draws for one stall of seconds. + - **Files:** `pipeline/library.rs` (`used`, `wanted_early`, `note_used`, `save`), `pipeline/make.rs` (`Queue`, `early`, `slow_limit`, worker priority, `wait_budget`), `frame.rs`. + - **Cold run, hard case.** With a new translator or driver the 83,555-key book (item 4) is the only way to fill the library before play. + +### 3. Run `victory warm --used` automatically (launcher or `play`) +- **Gain [H]:** on a new translator or driver build, moves ~2,700 translations plus the compile of ~2,500 used pipelines (4,380 thread-seconds worst case) out of the first play session. Currently never run (`warm-done.txt` empty). +- **Risk:** low. +- **Design:** + - `apps/victory/src/play.rs` spawns `warm::run(used=true)` as an idle-priority child while the menu is up, or immediately after a fingerprint change (`known::fingerprint()`). + - The warm children must write to the library too: `known::make` runs `HostPipeline::new`, which does `StorePipeline`, but each child process holds its own empty library and `use_pipeline_cache` is not called there. Pass the library directory and merge by name, or have children store and serialise each batch. + - Until item 1 lands, warm only helps through the driver cache for static-sampler pipelines. + +### 4. Instrument release builds so the above can be measured +- **Risk:** none; it is a prerequisite for deciding between items 1 and 2. +- **Add to `library::pipeline()` / `make.rs`:** + - `pipelines made: N, loaded: N, static_sampler_made: N, driver_ms_p50/p90/p99` once a minute. + - Per frame, the pipeline wait (today `copystat::C::PipelineWaitUs` exists only with `diagnostics`). + - A log line when a worker starts or finishes a pipeline of 1 s or more. +- This tells whether the driver cache hits for static-sampler pipelines (the central unknown, see section 2). + +### 5. Lower the render-thread wait, or make it adaptive +- **Gain [H]:** when many pipelines are being made, a shared 500 ms wait per frame is most of a 285 ms frame. +- **Quick experiment, no code:** `VICTORY_PIPELINE_WAIT_MS=50` against 500 on a short-loading start; compare ms/frame and dropped draws for the first 2 minutes. Dropped draws show as pop-in or missing lighting; the code comments say screen passes need their own budget (`VICTORY_SCREEN_WAIT_MS`). +- **Design:** adaptive budget = `min(500 ms, f(waiting()))` and zero for non-screen pipelines in `ready()` once `waiting()` > 200. + +### 6. Cache root signatures and avoid per-pipeline serialisation work +- **Gain [H]:** small. `host.rs:595 root_signature()` is built and serialised per pipeline, so ~1,360 times per run during the tail. Key by the `params + samplers` bytes and share the `ID3D12RootSignature`. +- **Risk:** low. +- **Constraint:** it must not change the library name, which uses the blob bytes; they would stay identical. + +### 7. Reduce unnecessary compiles in the title's own set +- **Gain [H]:** unknown, per-feature. + - `left_out()` already skips ~1,000 `CS_RaytracingResolve` shaders without BVH, plus the two water-light shaders and the decal defrag. Extending the same mechanism to pipelines that never produce visible output on this profile (list from the manifest: created but never drawn in N runs, never `used`) shrinks the 2,500 early set. + - 83,555 known vs ~2,500 used (3%) also means `early()` already prunes well; the remaining waste is the unused slow ones queued before used ones (item 2.2). + +### 8. Check the unimplemented pipeline creation slots (`0x1c8`, `0x218`) +- **Fact [M]:** every run logs `a pipeline creation method that is not implemented: the title goes without this pipeline`. Slot `0x1c8` reached at least 8,192 calls and `0x218` at least 8 (counts are logged at powers of two, so 8,192-16,383 actual calls) (`device.rs:349-400`). +- **[S]:** the description holds six `(pointer, size)` pairs of 0xb0-0x1c0 bytes; it is not a plain DXIL container. +- **[H]:** this could be real content the title never gets (extended pipelines or PSOs built from raw hardware state). It is a correctness question first; if it is the source of the ~300-460 draws dropped per frame in steady state, it matters for FPS too. Cheap first step: dump a few of those descriptions and run them through the shader parser. + +### 9. Smaller points +- **FXC helpers.** The emulator's own compute and pixel helpers use `D3DCompile` on first use and no persistent cache. Pre-compile them at host init (a thread at startup) or store the DXBC beside the library keyed by source hash. Likely tens of ms each on the render thread; **[H]** and unquantified. +- **ExecuteIndirect command signatures.** Made at first use. They are cheap, but creating the common ones at init keeps their `CreateCommandSignature` off the first draw. +- **Cold-start cost.** Any edit to victory-shader changes `VICTORY_TRANSLATOR` and forces a ~5 min cold start (the 093037 run). Caching by container hash is already good; cache the translator-independent front-end (IR) separately, or keep the old translation as a fallback while the new one is built, if development builds matter. + +## 5. Suggested order + +1. Item 4 (a day or less): instrumentation, then re-run one short-loading session. +2. Item 2 steps 2-4 (priority queue by first use, slow cap lifted during loading, worker priority) plus item 5's `VICTORY_PIPELINE_WAIT_MS` experiment: no correctness risk. +3. Item 3: hook `warm` into play. +4. Item 1 with the canary: the big win, needs the visual gate on NVIDIA and AMD. + +## 6. Open questions + +- Does the NVIDIA driver cache hit for the 1,362 static-sampler pipelines? If yes, the tail is mostly CPU contention with the title's loading; if no, only item 1 removes it. +- What are the `0x1c8` and `0x218` creations? +- What is the real per-frame pipeline wait in release (instrumentation, item 4)? +- Why are 5,539 early keys listed but only ~2,500 created early per run? Probably the rest are created only in other areas. diff --git a/docs/performance/AGENT_REPORTS/05-streaming-preload.md b/docs/performance/AGENT_REPORTS/05-streaming-preload.md new file mode 100644 index 000000000..8b35c3149 --- /dev/null +++ b/docs/performance/AGENT_REPORTS/05-streaming-preload.md @@ -0,0 +1,168 @@ +# 05 - Asset streaming and preloading: why the world keeps loading for minutes + +Scope: DirectStorage emulation, file reads, BCPack/zlib, texture creation, detiling, uploads, loading +detection, preload design. Read-only investigation, no source edited. +Evidence tags: **[static]** read in code, **[measured]** read from logs, **[hypothesis]** inferred. +Main log: `%LOCALAPPDATA%\victory\logs\play-20261127-094655-17644.log` (world entry 09:48:45, when the title opens +`core_restofworld.rpf`). Cross-checks: `play-...093037-23504.log`, `play-...094254-19348.log`, +`runs\20261126-123718-...\victory.log` (has the debug dstorage lines). + +## 1. Root cause in one paragraph + +DirectStorage is **not** the late-loading thread. It is cheap and keeps pace with the title (measured in the 11-26 run: +3-400 MB/s, `bcpack_workers` 0.1-1.5 of 16, reading workers under 1). What runs for minutes is the **GPU-side adoption of the +title's textures**. After entering the world the title writes about 1.8M placed-texture descriptor slots +(`texture slots written so far: 1821737 placed`) and fills the pages itself. Each slot goes into a queue worked by +`heap_textures` (`crates/victory-gpu/src/draw.rs`) **on the frame-recording thread, once per frame**: create host texture, detile the +title's tiled memory, upload, flip the slot from the neutral texture to the real one. That pass is throttled **per frame, by a +16 ms time slice, with catch-up disabled** (launcher overrides), while frames run at 3-13 fps. The drain rate is therefore +frames/s x 16 ms, about 80-200 ms of pass time per wall second, for 26,000 queued slots. The same minutes also have a slow frame +(4,400 draws, preparing thread 34-66 ms, ~2,800 pipeline first-binds at 09:49:15-26), which shrinks the budget further. + +## 2. Measured timeline (play-094655) + +| Time | Event | Evidence | +|---|---|---| +| 09:47:00-09:48:44 | Menu / loading screen: 4-8 ms/frame, 1-11 draws/frame, **0 slots queued** | fps lines, queue line | +| 09:48:45 | World entry: `pack\core_restofworld`, `shared_minigame000_bvh4`, `story000_script` .rpf opened | dstorage `file opened` | +| 09:48:49 | First slots queued (99); 1,713 at 09:49:04; 18,489 at 09:49:20; **peak 26,414 at 09:49:52** | `textures picked by index, the queue` | +| 09:49:14 | 36,453 slots served "at their first look" in 5 s, 2.5 frames late (up to 37 frames) | `served for the first time` | +| 09:49:15-26 | ~2,800 first binds; 4,085 shadow host-copy lines in the minute | counts | +| 09:49:20-09:50:23 | **4.8-13.7 fps**, 50-208 ms/frame, preparing 50-66 ms, copies 18-30 ms, 40-97 MB/frame | fps lines | +| 09:50:02-08 | Due backlog gone (520 due, oldest 533 frames old) | queue line | +| 09:50:29 | Second wave: 19,133 first looks, 313 ms of host-copy creation per 5 s | pass line | +| 09:50:39-09:52:27 | Steady 20 fps / 46-51 ms, 4,420 draws, preparing 33 ms, copies 10-12 ms and 27 MB **every frame** | fps lines | +| 09:52:42 | Third wave (area change): +8,000 uploads / 0.9 GB, card 84 ms/frame | uploaded 74.6k -> 82.7k | + +Totals at 09:52:53: 82,658 textures, 4,962 MB uploaded. 115,000 slots shown after upload, with "the neutral texture meanwhile +in 196,984" (the same slot counted per show). Other runs agree: `093037` queue 22.7k at 09:31:54, 29.3k at 09:32:29, empty +09:34:39 (3 min at 3.5 fps); `094254` 24.7k at 09:44:06, drained 09:46:18. + +Reading it: the pure upload backlog takes about **80-100 s** at today's rate (about 700 textures/s early). The rest of the "5 +minutes" is later waves, the recheck tail (3.4), and a world that stays at 20 fps. The player sees all of it as "still loading" +because surfaces are neutral/grey and frames are slow. + +## 3. What is deferred, who runs it, what throttles it + +### 3.1 The texture pass (main deferral) [static + measured] +- `crates/victory-gpu/src/draw.rs::heap_textures` (about lines 3040-3330), called from list recording, also "early" + (`early_textures`, ~2810) and before bakes (`PASS_BUDGET`). Runs **on the recording thread** (`IN_TEXTURE_PASS`). +- Queue: `descriptor/host.rs::HostHeap::texture_slots_due_known(frame, 4096)` (65,536 when baking), most recently written + first. Only "picked by index" slots; slots read through tables are not queued. +- Per slot: `texture::fingerprint` (48 KiB), `mapped_bytes`, `resource::host_resource`, `texture/ahead.rs::take`, else record the + upload in the list. +- Throttles in effect: + 1. `apps/victory/src/play.rs` lines 56-57: **`VICTORY_TEXTURE_CATCHUP=0`**, **`VICTORY_TEXTURE_STAGE_MS=16`** + (same in `scripts/play-foxhound.ps1:71-72`). Code defaults are 250 ms and 3x bytes/time when >= 1,024 slots are due + (`draw.rs` ~3178-3188). The comment there explains the origin: 1.6-2.2 s hitches in the first frames at 192 MB. + 2. Bytes: `staging_budget_per_frame` (`draw.rs:5853`): 384 MB at >= 20 GB VRAM budget, capped to 128 MB if `limited_host_ram()`. + Not binding here (4-5 GB over 3 min), time is. + 3. `residency::prefetch_limit` (`residency.rs:151`): 64 MB/frame under pressure, 16 MB when commit is critical. + 4. `resource::room` (`resource.rs:1803`): no new textures when the card has no room (80 % line, `VICTORY_TEXTURE_ROOM_PERCENT`). Not hit. + 5. One pass per frame: the budget is in **frame** units while frames take 100-300 ms at the peak. +- Cost of the pass: 540-1,130 ms per 5 s (11-22 % of wall). Only 20-140 ms is staging; **450-600 ms is "the rest"** (queue locking, + `Tells`, slot records, bookkeeping). Most of the budget goes to per-slot overhead, not moving bytes. [measured] + +### 3.2 Uploads ahead (copy queue) [static] +`crates/victory-gpu/src/texture/ahead.rs`: 2 threads ("uploads ahead N"), `MOST` = 96 MB of title memory in flight (**32 MB if +`limited_host_ram()`, i.e. total RAM <= 32 GB**, `residency.rs:93`), batch 16 MB / 64 textures. `claim` turns textures down for many +reasons (not fresh, tiled copy, grown, aliased, host-written...); a turned-down texture is uploaded inside the frame's list instead. +The turned-down count is logged only every 5,000 uploads and the line appeared once in this run (n == 1), so the fraction that +bypasses the frame thread is **unmeasured**. Right design, small capacity versus a 26k backlog on 16 cores. + +### 3.3 Neutral-texture placeholder [static + measured] +`descriptor/host.rs` ~332-400 (`VICTORY_SHOW_AFTER=1`, `VICTORY_SHOW_NEW_LATER=1`): a slot shows the neutral texture until its upload's +submission finished (fix for the ~16-minute device loss in findings.md). Mean delay 0.2-1.4 frames, but frames are 100-300 ms at the +peak, so grey surfaces last seconds. Not the cause of minutes; it is what the player sees. + +### 3.4 Rechecks counted in frames [static + measured] +`draw.rs:842 RECHECK_FRAMES = [4, 12, 40, 120, 400]`: a slot uploaded whole is fingerprinted again after 4, 12, 40, 120, 400 **frames** +(the title may fill pages after writing the view). At 3-10 fps the 400-frame stage is 40-130 s. The log shows 12-17k "uploaded whole +and waiting to be looked at again" at 09:49:36-09:50:08, 7.6k at 09:50:39-54, and a queue of ~1,000 for the rest of the session. +Costs 5-110 ms per 5 s and makes "queue length" look like unfinished loading. + +### 3.5 Title memory residency [static] +DirectStorage writes into pages the title mapped (`xmem.rs`; `VICTORY_MAP_LEAN`, `lift_thread` for `VICTORY_STREAM_PRIORITY`, +`VICTORY_MAP_THREADS=1`). `14,163 passed over unmapped`: textures not mapped yet are skipped and retried (`Told::Later`). That is the +title's own streaming order and cannot be advanced without its requests. + +### 3.6 DirectStorage emulation [static + measured] +`crates/victory-hle/src/modules/dstorage.rs`: one scheduler, workers = `available_parallelism` (16), staging floor 256 MB +(`VICTORY_DSTORAGE_STAGING_MB`, in `set_staging_buffer_size`), weighted round-robin lanes, handle per worker (`Io::Handles`), zlib + +BCPack (`victory-formats/src/bcpack.rs`), statuses completed in queue order. Page-mapping calls cost 200-400 us per page in the world +(xmem comment) and throttle the **title's** streaming thread, not our workers. Not the bottleneck. + +### 3.7 Pipelines [measured; shared with other reports] +`pipeline/make.rs`: workers = 2/3 of logical processors (8 here) at lowest priority. Pipeline book exists +(`pipeline/known.rs`, `VICTORY_PIPELINE_BOOK=1`, `victory warm`). ~2,800 first binds / translations at 09:49:15-26 coincide with the +4.8 fps trough. `dropped 260 draws/frame without a host pipeline (0 being made)` is steady afterwards (6 % of 4,420), not a loading effect. + +## 4. Not the cause +- Nothing is prepared during the loading screen because the title only creates texture views when streaming into the world: the queue is + empty for the 95 s before entry. "Preload at the end of the loading screen" is impossible without knowing what the world will need (section 6.3). +- The card is not limiting during the drain (0-13 ms of 50-200 ms), nor VRAM (4.9 of 24 GB), nor DirectStorage. + +## 5. Ranked opportunities + +| # | Change | Expected effect | Risk | Where | +|---|---|---|---|---| +| 1 | Wall-clock, adaptive pass budget: catch-up back on in play, slice 60-120 ms **only while the gate says Loading/Settling**, 16 ms in Gameplay | drain 3-6x faster [hypothesis]: ~90 s -> 15-30 s | hitches while settling (hidden by overlay) | `play.rs` 56-57, `draw.rs` ~3178-3200 | +| 2 | Move the per-slot pass (decision, `host_resource`, staging) off the recording thread onto a pool; frame thread only flips | frees 11-22 % of frame time permanently, removes fps dependence | medium: lock order with lists, `show_after`, `ahead::drain` | `draw.rs::heap_textures`, `texture/ahead.rs` | +| 3 | Scale `ahead`: workers ~cores/4, `MOST` 512 MB when RAM > 32 GB (128 MB otherwise), log turned-down counts every 5 s | more textures bypass the frame list | RAM on 32 GB | `texture/ahead.rs` consts and `workers()`, `residency.rs` | +| 4 | Recheck schedule in ms, not frames; skip rechecks for pages written by a completed DS batch | less pass time, honest queue length | small | `draw.rs:842`, `Told::Recheck` | +| 5 | LoadGate (6.1) plus "Preparing the world" overlay | user sees progress instead of a grey, 5 fps world | medium (heuristics) | new `gate.rs` in victory-gpu, `host/menu.rs`/`panel.rs` | +| 6 | Persistent texture book: per scene record DS source ranges and texture layouts; next run pre-read ranges into the OS cache and cache decoded BCPack | removes real I/O + decode from the burst [hypothesis, moderate: I/O is not the bottleneck today] | policy: hashes/offsets only, in `cache_dir` | `dstorage.rs`, `victory-pipeline/src/cache.rs`, book beside `pipeline/known.rs` | +| 7 | Pre-create host textures + staging from the book during Loading, so first-look cost (`host copies` 313 ms, `staging uploads` 223 ms per 5 s in the second wave) leaves the burst | cuts waves 2 and 3 | needs a per-run identity (DS destination size + layout hash + first-level hash) | `texture.rs::staging`, `resource::host_resource` | +| 8 | Steady 27 MB/frame "copies" (10-12 ms) after the drain | better "after" fps | other report (preparing thread) | `host.rs` | +| 9 | Auto-warm from the pipeline book at start | removes the 09:49:15-26 trough | small | `apps/victory/src/translate.rs::warm`, `pipeline/known.rs` | + +## 6. Design: LoadGate + texture book + +### 6.1 Detecting loading and scene transitions +Evaluate once per presented frame (the 5-second stats in `host.rs` already read most of these): + +| Signal | Source | Meaning | +|---|---|---| +| draws per frame | host frame stats (1-11 menu/loading, 600-6,900 world) | menu vs world | +| DS bytes in flight + queue depth | `dstorage.rs` `Lanes` (add an atomic like `READING`) | title streaming | +| `pack\*.rpf` opened | `dstorage.rs::open_file` (`core_restofworld`, `story000`...) | scene transition marker | +| texture queue due count + oldest age | `texture_slots_due_known`, `texture_slots_waiting` | adoption backlog | +| pipelines being made | `pipeline::make` queue (the `(N being made)` figure) | shader stalls pending | +| uploads ahead in flight | `ahead::IN_FLIGHT` | copy backlog | + +States: `Menu` (draws < 50) -> `WorldEntry` (draws jump > 500, or a `pack\*.rpf` opens) -> `Settling` while any of (due > 256, ahead in +flight > 0, pipelines making > 0, DS bytes in flight > 0) -> `Gameplay` after **3 s** all quiet (hysteresis). A new `pack\*.rpf`, or a +draw-count collapse, re-enters Loading/Settling (fast travel, missions, cutscenes). + +### 6.2 What the gate does +- `Settling`: pass slice 120 ms with catch-up; `ahead` uncapped within the RAM rule; pipeline workers at normal priority + (`VICTORY_PIPELINE_LOWEST` off); rechecks suspended; one progress log line a second (due, ahead in flight, pipelines making, MB uploaded). +- Overlay fade "Preparing the world n %" (progress = 1 - due/peak_due) with a 90 s timeout so a miscount never blocks. The title is + not paused (unsafe); the player just stands still behind the overlay for 15-30 s instead of 3-5 minutes. +- `Gameplay`: restore the 16 ms slice, rechecks on. +- Memory bounds, no blind loading: only slots the title **names** are uploaded (4-5 GB measured), under `resource::room` (80 % of the + VRAM budget) and `prefetch_limit`; staging capped at 60 % of free host RAM. + +### 6.3 Texture book (persistent, offline) +- Record during play (like `VICTORY_PIPELINE_BOOK`): per scene (set of `pack\*.rpf` open), each DS request as + `(file id, offset, source size, destination size, options)` and each texture the pass uploads as + `(layout hash, first-level bytes, mapped bytes)`. File: `cache_dir\texture-book\<build id>.bin`. Offsets and hashes only, no asset + bytes (asset-policy rule 1; `ensure_outside_repo`). +- Use on the next run: when a scene pack opens, a low-priority thread reads the recorded ranges in file order so the OS cache holds them + before the title asks; decoded BCPack output can be cached content-addressed via `victory-pipeline` cache; host textures are + pre-created from layouts into the pool (`VICTORY_TEXTURE_POOL=1`) so a slot write only needs staging. +- Bounds: only items seen in that scene on this machine; same VRAM/RAM caps; evict entries unused for 5 runs. + +### 6.4 Rollout +1. Wall-clock slice + catch-up under the gate (opportunities 1, 4) with the 1 s progress log; target: due backlog < 30 s. +2. Gate state machine + overlay (5). +3. `ahead` scaling and turned-down logging (3), then pass off the frame thread (2). +4. Book recording (no behavior change), then cache warming (6), then pre-created textures (7). + +## 7. Measure first (cheap, confirms the diagnosis) +1. Run with `VICTORY_TEXTURE_CATCHUP=1 VICTORY_TEXTURE_STAGE_MS=120`: compare time from `core_restofworld.rpf` open to `queue < 500 + slots`, and the longest frame. A drop to ~30 s confirms it. +2. Log `ahead` STATS (sent vs turned down) every 5 s. +3. If the player has 32 GB RAM, `limited_host_ram()` (`<= 32 GB`) is true: `ahead` is capped at 32 MB and the pass at 128 MB/frame. + Log it once at start; the logs here do not say which RAM class they came from. +4. Time `texture::detile` and `refresh` per MB on fast vs slow cores (`cores.rs` pins only the helpers). diff --git a/docs/performance/AGENT_REPORTS/06-cpu-threading.md b/docs/performance/AGENT_REPORTS/06-cpu-threading.md new file mode 100644 index 000000000..7274c6681 --- /dev/null +++ b/docs/performance/AGENT_REPORTS/06-cpu-threading.md @@ -0,0 +1,186 @@ +# 06 - CPU runtime and threading + +Scope: crates/victory-gpu (cores.rs, queue/behind.rs, list/thin.rs, shadow.rs `wide`, host.rs submit/settle), +crates/victory-hle (runtime.rs, kernel.rs, xasync.rs, dstorage.rs), crates/victory-loader (console_insn.rs). +Read-only review; nothing was edited. Tags: [M] measured from logs, [S] static (code read), [H] hypothesis, needs an experiment. + +## 0. Caveats about the data + +- [M] The logs in `%LOCALAPPDATA%\victory\logs` and `runs\*\frametime.csv` come from an **AMD Ryzen 7 5700X (8C/16T, no hybrid cores) + RTX 4070**, + not the i9-12900K. Evidence: the `frametime.csv` header (`# cpu: AMD Ryzen 7 5700X ... 16 logical`), `dstorage: workers=16`, `land ... 4 threads` + (= logical/4), and no "kept on the fast cores" line anywhere (cores.rs stays silent when all cores are alike). + So everything in `cores.rs` (P/E handling) is unexercised in these logs. Findings in section 4 about hybrid CPUs are static only. +- [M] Thread counts scale with logical CPUs: on the 12900K (24) dstorage runs 24 workers, land 6, `wide` 6 (clamp), pipeline workers more. + The fixed ones (thin = 8) do not scale. +- The per-frame lines are diagnostics-build averages over 5 s; "per frame" means per present. Scenes differ between windows. + +## 1. What the logs say (play-20261127-094655-17644.log, the most useful one) + +Two regimes appear in the same session. + +**Regime A, about 20 fps, 48-50 ms/frame (log lines 22554-22640).** [M] +- `victory-submit` thread "worked 47.3 / 48.0 / 47.9 ms" of a 49 ms frame: **98 % occupied**, with only 1.9-3.3 ms waiting for flights. +- Its 44 ms ("preparing per frame, the submitting thread"): write-watch asking 3.6, title bytes put under flights' writes 9.7, + lists' steps 13.3 (refreshes 8.5), copies in the card's memory 6.7, planning steps done on the card 6.0, waiting for flights 1.9-3.3, + heaps' records 1.6, sending 1.0. +- Title threads waited 14.8-19.6 ms per frame at presents (the line is full, `VICTORY_SUBMIT_FRAMES=1`); no wait for room in the line. + So the title's recording is not the wall; the single submit thread is. +- The card is "86-90 % busy by this count", but the submit thread holds the whole preparing chain in series with the card (frame is about + 34 prep + 5 card + 11 copy back, from the frame line). +- thin: 38.9 k calls, 207 ms of thread time over 202 lists = 5.3 us per call. At 20.4 fps this is 4.2 logical CPUs permanently busy + (of 16 logical, 8 physical). Total demand (thin 4.2 + submit 1.0 + land/wide/refresh helpers + title threads + spinners, see 3.5) is close to + saturating 8 physical cores. + +**Regime B, 12-15 fps, 65-84 ms/frame (lines 26060-26118, 25423).** [M] +- Submit thread worked 72-84 ms, of which **43.0 / 59.1 ms "waiting for flights"** and "settles" = 0.8-1.0 per frame, all of them for + "title memory read ... a fill of upload memory" (0.8-1.0 of 0.8-1.0 settles). + One settle per frame costs a whole drain of the card: 43-59 ms. The frame equals prep + GPU + copy back in series + (26.6 + 34.7 + 6.0 = 67.3 of 69.7 ms). +- The relay (landing) thread "waited 62-77 ms for the card with nothing to land". +- Card steps: 4,300-5,000 small fills per frame, 1.9-2.3 MB total (about 450 bytes each, the title's 480-byte constants ring). + +**Per-call thin cost has regressed.** [M]+[S] list/thin.rs docs say 3.5 us per call (45-60 k calls, 160-190 ms). Now 4.5-5.3 us in normal windows and +7.3 us in a stall window (58 k calls in 424 ms, log 095317). Either per-draw work was added (descriptor tables, early textures, indirect merge), +or the 8 threads contend (shared atomics, SMT siblings, oversubscription). Not decidable from logs; needs per-op timing (section 5). + +**Stalls.** [M] frame lines of 100-500 ms: 5 of 46 gameplay windows (log 094655), 19 of 35 (093851), 24 of 78 (093037). findings.md attributes +270-660 s per session of >200 ms frames to pipeline creation. Not CPU-thread caused as far as the logs show, but see 3.4 (dstorage). + +## 2. Ranked opportunities + +| # | Change | Gain (est.) | Risk | Evidence | +|---|---|---|---|---| +| 1 | Remove the one-per-frame full drain for fills of upload memory (declare writes tighter / `VICTORY_FILL_TITLE=1` experiment) | regime B: up to 40-55 ms of a 70-84 ms frame; none in regime A | medium (stale constants) | [M] | +| 2 | Split `victory-submit` work into two pipelined stages (prep vs send) | regime A: 48 -> about 30-35 ms (20 -> 28-30 fps) if half the 44 ms moves | high | [M]+[S] | +| 3 | Cut total CPU of thin translation (per-call 5.3 us) and spinning waits so the critical threads get cores | 5-15 % of frame through less contention [H] | low-medium | [M]+[H] | +| 4 | `wide()` fork-join wake latency: try `VICTORY_WIDE_SPIN` or a gang that stays awake during a submission | up to about 4-5 ms of the 48 [H] | low | [S] | +| 5 | Title wait loops (`mwaitx` patched to `pause`) busy-spin whole logical CPUs | [H] frees up to N logical CPUs | medium | [S] | +| 6 | dstorage workers: priority/QoS and count | stutter during streaming [H] | low-medium | [S] | +| 7 | cores.rs: SMT-sibling and E-core awareness on the 12900K | [H], unmeasurable on logs here | low | [S] | + +### 2.1 (1) The fill-of-upload-memory settle (regime B) [M]/[S] + +What happens: `Host::submit` (host.rs about 5640) calls `late_blocked(runs)` -> `blocked_by(&line.written, ...)` +(host.rs about 3060-3110). A `Step::Fill(_, src, len, _)` of upload memory (the title's 480-byte constant fill) that touches any range a flight's +shaders may write returns `WHY_READ`; the submit thread then `relay_wait`s / `settle`s until the flights that may write it have landed. +Cause stated in the code comment at `fill_is_titles` (host.rs about 2902): the title's 174 MB heap is declared written as a whole (a root view has no size), +and the constants ring lives inside it, so each frame's fill collides with the declared range. +The mitigation `VICTORY_FILL_TITLE=1` exists and is **off by default and not in the switches of the analysed run** (header of log 094655 lists all switches; +FILL_TITLE is absent). Its author measured "30 ms of a 130 ms frame" for this wait (run blame1). + +Design, in order of preference: +1. Run one A/B with `VICTORY_FILL_TITLE=1` (and `VICTORY_AB` if the diagnostics build is used). Record: "waiting for flights" ms, settles, fps, and watch for + constant corruption (flicker, wrong lighting) because the heuristic can read a constant a flight really writes. +2. Real fix, no heuristic: give root views a size. At the place that declares writes for a root UAV/SRV with unknown size + (`shadow::declare`/`wide_write` path in draw.rs `bind`, see `writes`/`stores` handling near draw.rs 1990), clamp the declared range to what the shader's stores + can reach (translator knows buffer bounds only for descriptor tables; for root views use the pipeline's recorded store extents, or the resource's width + from the title's own `CreateCommittedResource` record if the address is inside a registered buffer: `shadow::register` keeps (start, len)). + Then the 480-byte ring at a fresh offset no longer touches a declared-written range. +3. Fallback structural change: perform the constants fill on the card ("steps done on the card", `card_steps`) when it is blocked; `VICTORY_CARD_STEPS=2` already does + this for 4,300-5,000 fills but "0.8-1.0 submissions refused and waited" per frame remain (log line `steps done on the card ... 0.79 submissions refused and waited`). + Find what makes that one submission refused (`card_steps::copied_read`, host.rs `late_blocked` second condition) and let it through. + +Files: crates/victory-gpu/src/host.rs (`late_blocked`, `blocked_by`, `read_blocked`, `fill_is_titles`, `settle`, `relay_wait`), +crates/victory-gpu/src/host/card_steps.rs, crates/victory-gpu/src/draw.rs (declaration of writes in `bind`). + +### 2.2 (2) The submit thread is a serial wall (regime A) [M]/[S] + +`queue/behind.rs` `Lane::serve` -> `step` -> `Job::go` runs one submission at a time on `victory-submit`, and `Host::submit` holds `self.submitted` +(the submission lock) "from preparation to copy-back". Inside, everything is sequential: ask watch, plan card steps, `late_blocked`, refresh (wide-spread +internally), put title bytes under flights, send. Parallelism exists only inside steps (`shadow::wide`), at 95 fork/joins per frame. + +Already known (findings.md "What is next" 1). Concrete design with the least coupling: + +- Stage A (new thread `victory-prep`, per submission k+1 while stage B sends k): everything that depends only on title memory and the write watch, not on + the landing of flights: `watch::ask_once` ranges (3.6 ms), planning of card steps (`card_steps(runs)`, 6.0 ms), the heaps' record sync + (`begin_sync_heaps`, already begun early with `VICTORY_HEAP_SYNC_FIRST`), pre-computing refresh plans (`defer_refresh` lists) and the "known to copy + nothing" skip (8,887 of 10,094 flush entries are no-ops; make them cost zero by having the watch say "no dirty page in range" before the list is queued). +- Stage B (existing `victory-submit`): `late_blocked`/`stale_under_flights` (need the live `line.written`), refresh copies that touch ranges flights may write, + `ExecuteCommandLists`, landing bookkeeping. +- Hazard: stage A for k+1 reads title memory that flights of k may still write back (landing). Only ranges not in `line.written` of flights up to k + can be prepared early; the rest is deferred to B. This is exactly the existing `blocked_by` classification, so A can reuse it with a "will be in written after k" + conservative set (`written` plus k's declared writes). +- Expected: moves the 3.6 + 6.0 + part of 8.5 (refresh scan) = roughly 15-18 ms off the critical thread; frame about 48 -> 32-35 ms, i.e. about 20 -> 28-30 fps in regime A. +- Cost/risk: high (ordering, lost writes were the hardest bugs in bug-journal). Prototype behind a switch and use the existing stress test for lost writes. + +Smaller first step (low risk): "title bytes put under flights' writes" 9.7 ms for **29,806 changed runs per frame with 0.76 MB** (about 26 bytes per run; +host.rs line about 3830 stat, from `shadow::merged_stats`). Per-run overhead dominates. Coalesce runs with a gap tolerance (merge runs closer than 32-64 bytes +and copy the gap too, or compare in 64-byte blocks and copy whole blocks): fewer, larger copies. Needs the code in shadow.rs `merge`/`put_in_under` (search `merged_stats`). +Expected 9.7 -> 3-5 ms. Safe only if the gap bytes are the same in both copies or are not being written by a flight (they are checked against `written`). + +### 2.3 (3) Total CPU: thin translation [M]/[H] + +- 37-43 k calls/frame, about 9 calls per draw (4.1 k indirect executions, 2.9-4.5 k draws). State calls are already lazy (`with_binding`), so the cost sits in + `State::draw/draw_indexed/dispatch/execute_indirect` -> `prepare_for` -> `bind` -> `tables`, `shadow::find_any` per vertex slot, `shadow.refresh` -> + `list.defer_refresh`, `ensure_state` per target, `crate::pipeline::host_pipeline` up to 4 times per draw (each goes through `make::ready`, two relaxed atomics on `p.used`), + and the D3D12 calls themselves. +- [S] Cache-line ping-pong from process-wide atomics touched by all 8 translators on every draw: `DRAWN`, `DROPPED` (draw.rs 4760-4800), `DRAWS` (`count_draw` in list.rs), + `STATS[..]` in thin.rs, `make::ready` `used` flag, `shadow` `used`, `BUFFERS_CHANGED` SeqCst load per find. Each is individually cheap (about 50-150 ns when contended), + together plausibly 5-10 ms of the 200 ms. Fix: thread-local counters flushed at the 5 s line (the `FOUND` thread-local in shadow.rs shows the codebase already does this elsewhere). +- [H] Per-op timing is missing. The `diagnostics` feature has `copystat::recorded` per `with_state_on`, but nothing aggregates per op type. Add (diagnostics only) + per-op-code `Instant` accumulation in `thin::translate` (the `match op` at thin.rs 699-800), emitted in the thin line. That decides between "D3D12 runtime cost" (inherent, + needs fewer calls: dedupe identical `SetGraphicsRootDescriptorTable`/constants between draws) and "our bookkeeping" (fix per above). +- Load balance: parallelism is per recording (one thread runs a recording's chunks in order, `scheduled` flag). 202 lists but 319 pieces; if a few lists carry most calls, + 8 threads idle. Log `pieces`/`lists` shows 1.6 chunks per list on average; per-list sizes are not logged. Add a histogram. +- Do not raise `VICTORY_THIN_THREADS` above 8 on a machine at saturation (section 1 demand estimate). + +### 2.4 (4) `wide()` fork-join latency [S] + +shadow.rs `wide` (about 1500-1650): Mutex+Condvar queue; helpers sleep in `Condvar::wait`; code comment at `spin` says "asleep, a thread is woken in 50 us and more, 95 times a frame". +95 x 50 us = 4.75 ms of the submit thread's 44 ms in pure wake latency, in the critical path. `VICTORY_WIDE_SPIN` (default 0) is a bounded spin before sleeping; it is not in any switch file, doc, or +log header, so it has probably never been measured. Experiment: `VICTORY_WIDE_SPIN=100`, `=300`; measure submit "worked" ms and thin us/call (spinning helpers use logical CPUs which regime-A demand +suggests are scarce, so check both). If it helps: spin only while the submission lock is held (arm a global flag in `Host::submit`, clear at the end) so helpers sleep otherwise. +Also `notify_one` x N vs `notify_all`: the code already limits; fine. Alternative: a `wide_each`-style persistent job where the submit thread publishes a counter (atomic next index) and helpers claim indices without a Mutex (replace `workers.jobs` Mutex hand-off with an atomic ticket). + +### 2.5 (5) Title wait loops spin [S]/[H] + +victory-loader/src/console_insn.rs `wait_patch` replaces the title's `monitorx` with a 3-byte NOP and `mwaitx` with `pause; nop`, "no lighter a wait for it" (their comment). On the console `mwaitx` +sleeps the core until the monitored line is written or a timeout; here each such wait loop becomes a hot `pause` spin that never yields the logical processor. Every idle title worker therefore +holds a logical CPU at 100 %. On the 5700X 16 logical, on the 12900K it also holds an SMT sibling of a core our critical threads want (P-core placement is the scheduler's choice for unpinned threads). +Nothing in logs counts them. Measurement (cheap): sample `GetThreadTimes`/`QueryThreadCycleTime` per title thread over 5 s while at the title screen or paused; threads with about 100 % CPU and no frame work are spinners. +Design if confirmed: patch `monitorx; mwaitx` (adjacent, 6 bytes) as `call stub; nop` with a stub in the existing near-code arena (`console_insn::near`, like `clzero_stub`): stub saves the address from `rax`, spins about 20-50 us +with `pause` checking the dword, then `SwitchToThread()` (not Sleep: no added latency when nothing else wants the CPU, but yields to our critical threads), and returns. Do not use a timed sleep (job pick-up latency would raise frame time). +Risk: medium (patching title code; the `clzero` patch precedent exists). + +### 2.6 (6) dstorage and background workers [S] + +dstorage.rs 326 and 632: `workers = available_parallelism()` (16 here, 24 on the 12900K), threads named `dstorage N`, **no priority, no QoS, no affinity**. BCPack decode and decompression run on them (`bcpack_workers` is logged +only at debug level). The title's streaming thread is deliberately lowered (kernel.rs `title_priority`), yet our own dstorage pool at normal priority is as wide as the machine and competes with `victory-submit` (above normal, 1 thread), thin (normal, 8), +title render threads. Pipeline workers (make.rs 571) set a priority; check which. Suggestions: cap dstorage at `n/2`, `THREAD_PRIORITY_BELOW_NORMAL` during gameplay (keep normal while loading, signalled by `crate::frame`/loading state), +and on hybrid CPUs `SetThreadInformation(ThreadPowerThrottling)` (EcoQoS) so Windows 11 places them on E-cores. Stutter symptom is frames of 100-500 ms in streaming areas; verify with a run at `workers=4`. +Also `Sleep(1)` retry loops in dstorage 1582/1672/1728/1876 are fine now (1 ms timer is on). + +### 2.7 (7) cores.rs on hybrid hardware [S] + +`cpu_sets()` uses only `EfficiencyClass`. `SYSTEM_CPU_SET_INFORMATION_CPU_SET` also gives `CoreIndex`/`LogicalProcessorIndex`; nothing uses SMT-sibling information. +On the 12900K: the submit thread is pinned to the 16 P logical CPUs (stage 1) and shares physical cores with 4-6 land/wide helpers (stage 2) and unpinned thin/title threads. Experiments that need no code: `VICTORY_FAST_CORES=1/2/3`, +`VICTORY_HELPER_PRIORITY`, and record "submit worked ms" + thin us/call. Possible code change: choose one logical CPU of one P core for `victory-submit` and keep the sibling free from thin workers (set their CPU sets to the other P cores' logical CPUs + E cores), +so the critical thread never shares a core with 4 busy list translators. Stage 3 (thin pinned to P) currently only on `VICTORY_FAST_CORES=3`. No logs support any ranking here; do not ship without an A/B on the 12900K. +Note the 12900K default of `keep_helper_on_fast_cores` is correct for the helpers; the translating threads default to unpinned, which on Windows 11 means Thread Director may place them on E-cores (IPC about 0.6 of P). + +## 3. Reviewed and found fine (static) + +- Timer resolution: `runtime.rs use_console_timers` does `timeBeginPeriod(1)` + `PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION` + execution-speed throttling off + above-normal process class. Sleep(1) granularity is correct; `NtSetTimerResolution(5000)` (0.5 ms) would only help the title's audio mixer 4 ms sleeps marginally. +- Sync API emulation: WaitForSingleObject, SRW, condvars, critical sections, Sleep are the host's own (kernel32 pass-through, HostPolicy). No per-call emulation overhead. Import thunks are direct bound addresses; the generated stub path is only for unimplemented imports (thunks.rs). The HLE modules that matter (xasync, dstorage, audio) are not on the 20 fps critical path. +- xasync.rs: test-only `yield_now`/`sleep`; real work is on pool threads. audio capture thread `Sleep(1)` poll is small. +- `queue/behind.rs Lane::serve`: 1 ms `wait_timeout` poll only while items stand at a CPU-writable wait; `step` scans <= 38 items under the lock per step, allocating a `heads` Vec per step (minor). +- No `spin_loop` outside rare paths: `watch.rs change_done/change_over` (bounded 2 ms / 1 s with Sleep(0/1) fallback), `shadow::spin` (off), test code. No global spin locks found in the hot path. +- Frame limiter (`frame.rs` sleeps) is off (`VICTORY_FRAME_INTERVAL_US=1000`). +- Global locks on the hot path: `BUFFERS` RwLock is bypassed by the thread-local `FOUND` cache (shadow.rs 5014); `READY`/`WORK` in thin.rs is touched about 320 times per frame; `List.state` Mutex is per list; `Host.submitted` is the only process-wide serialization and it is the submit chain by design. + +## 4. Instrumentation to add first (cheap, makes the rest decidable) + +1. Per-thread CPU time (`QueryThreadCycleTime`) for every named thread group, in the 5 s frame line: `victory-submit`, `victory-list-*`, `victory-wide-*`, `land*`, relay thread, `dstorage *`, pipeline workers, plus the title's main/render/job threads. Shows total CPU demand vs 8 physical cores, spinners, and who competes. +2. Per-op microseconds in `thin::translate` (diagnostics) and a histogram of calls per recording. +3. Count of `monitorx`/`mwaitx` patches and a periodic "percent CPU of title threads in pause loops". +4. Log which submissions are refused card steps and why (`card_steps::copied_read`), per frame. +5. Print the CPU brand and logical count in the main log (the frametime.csv has it, the play log does not), so logs from other machines are not mistaken for the 12900K. + +## 5. Experiment order + +1. `VICTORY_FILL_TITLE=1` A/B (log regime B: expect "waiting for flights" 43-59 -> under 10 ms). +2. `VICTORY_WIDE_SPIN=100/300` A/B. +3. Add instrumentation (section 4), rerun, rank thin costs. +4. dstorage cap/priority; spinner patch (2.5) if the per-thread CPU shows spinners. +5. Coalesce changed runs under flights (2.2 small step). +6. Only then the two-stage submit pipeline (2.2 big), the largest and riskiest item. diff --git a/docs/performance/AGENT_REPORTS/07-profiling.md b/docs/performance/AGENT_REPORTS/07-profiling.md new file mode 100644 index 000000000..a88b685fd --- /dev/null +++ b/docs/performance/AGENT_REPORTS/07-profiling.md @@ -0,0 +1,160 @@ +# 07 Profiling and experimental validation + +Scope: scripts and docs only; no `.rs` edited, nothing built, no game run. Numbers: `docs/performance/BASELINE.md`. + +## 1. Tool delivered + +`scripts/perf/summarize_run.py` (Python 3 standard library only). + + python scripts/perf/summarize_run.py <run dir | victory.log | play-*.log | frametime.csv> [...] [--out DIR] [--label TEXT] + python scripts/perf/summarize_run.py --compare <A> <B> # run dirs or *.summary.json, prints a delta table + python scripts/perf/summarize_run.py --latest 3 # newest runs under %LOCALAPPDATA%\victory\runs + options: --stall-ms 200 --stall-rel 3 --heavy-draws 1000 --warmup-s 30 + +It writes `<run>.summary.json` and `.md` (and `index.md` for several inputs, with median/min/max rows). It emits: fps mean, +mean/median/P90/P99 frame ms, 1% low (two definitions), worst frame, stall windows (threshold and lower-bound duration), +watchdog stalls grouped by cause, phases (pipelines done, scene start, heavy-scene entry, "stabilised"), frame-weighted CSV +columns (CPU prepare, GPU, draws, MB copied/textured/copied back/sent/fetched, RAM, CPU %), log subsystem means after world +entry (submission preparing, frame activity, descriptor sync and slots, card clock/busy %, relay, sent-ahead, buffer refresh, +card copies, GPU spans, DirectStorage MB/s), submissions per presented frame, and run labels. The `definitions` list inside +every summary says exactly how each figure is computed. Without a CSV (play logs) it rebuilds windows from the 5 s frame line +and says that tail figures are unavailable. + +Labels it fills from the files: console profile, build profile (launcher line), DLSS mode, frame-gen factor, native-1440p switch, +panel on/off, `VICTORY_AUTO_A`, shader-translation cache cold/warm (`shaders from the cache and translated so far hits= misses=`), +final pass/graphics-method switch state, hardware header. `--label` stores free text (scenario, A press time, cold/warm). +Not derivable from any file today: scenario/route, A-press time, commit, driver pipeline-cache state (see section 4). + +## 2. Findings that change how the data may be used + +1. **The recorded runs are not from this branch's instrumentation.** `VICTORY_FRAMETIME_DUMP`, `VICTORY_AUTO_A`, + `VICTORY_GPU_SPANS`, the `stall:` watchdog, `passswitch`/`gfxswitch`, "submission preparing per frame", "frame activity" are + absent from the source (`grep`, `git log --all -S`) and from the strings of `target\release\victory.exe` and + `Extracted\victory.exe`. They live in a fork victory.exe driven by `C:\Users\mathe\orca\workspaces\AnyXboxX\squirrelfish` + (`--auto-a` = `VICTORY_AUTO_A=150`, `--frametime-dump`, `--override KEY=VALUE`, `--diag`, `--warm`). On this branch a + run produces only `logs\play-*.log` with one frame line per 5 s plus the in-tree per-frame lines. Consequence: after a change + to the branch you cannot reproduce the CSV-based baseline until the writer is ported (proposal P1). +2. `build` is `unknown` and the CSV `game:` is `unknown` in every file; no commit is recorded anywhere. Runs cannot be tied to + code state, so "before" in an A/B must be re-measured, not taken from history. +3. CSV `gpu_ms`/`gpu_pct` are ~0 while the log's card clock says 41 % busy: do not use the CSV GPU columns. +4. `victory-settings.txt` (F1 menu, `%LOCALAPPDATA%\victory`) is applied over launcher settings at every start. It currently holds + `VICTORY_MENU_DLSS=balanced`, `VICTORY_MENU_FRAMEGEN=2`, `VICTORY_PANEL=1`, `VICTORY_PORT_CONSTANTS=` (unset), + `VICTORY_MENU_CONSOLE=series-x`. The panel (`VICTORY_PANEL=1`) "costs some" (`docs/findings.md`). A run is only comparable if this + file is identical or deleted; copy it next to the run. +5. Some Nov 26 evening runs have core passes switched off from the F1 menu (descriptors, heap_buffers, heap_textures, + buffer_refresh, texture_refresh). The `passes off at end` column flags them. Never mix them into a baseline. +6. Heavy scene is only reached after 64-324 s (median 137 s) because of boot, the A press and the title's loading; and A-to-stable + takes a median 76 s more. Sessions shorter than about 6 minutes give few steady windows (median 136 heavy windows over 36 runs). + +## 3. Inventory of instrumentation in this tree (what exists, how to use it) + +Measuring and recording + +| switch / facility | what it gives | cost / notes | +|---|---|---| +| frame-rate line (always, every ~5 s, `host.rs` ~9406) | fps, ms/frame, preparing, copies/textures ms+MB, GPU ms, copy-back, draws, dropped, pipelines being made | in `logs\play-*.log`; the only per-run time series on this branch | +| `VICTORY_FPS_LINE=0/1` | fps shown at the top of the picture | F1 menu | +| `VICTORY_PANEL=1`, F3 | on-screen numbers (updates twice a second); in screenshots | costs a little; keep off for A/B | +| per-frame log lines (`host.rs`, `descriptor`, `queue`) | card clock/busy, relay, submissions sent ahead, shader cache hits/misses, copies in card memory, buffer refresh | in-tree subset only | +| `VICTORY_LOG`, `VICTORY_LOG_FILE` | log filter / path | | +| `VICTORY_TIMELINE=<file>` (+ `_AT` s, `_FRAMES`), diag build | Chrome/Perfetto trace of N frames: spans, waits and who woke them, card timestamps, text chain of work behind each present | `--features diagnostics`; the best stall-attribution tool, but manual and triggered by time, not by a bad frame | +| `VICTORY_GPU_TIMING` (diag) | each list timed on its own, slow ones logged | disables `VICTORY_LATE_WAIT` (changes behaviour) | +| `VICTORY_TIMER_LOG=1` | frame timer statistics | | +| `VICTORY_MEMORY_MAP` | memory listing (on unless 0) | | +| `VICTORY_RECORD=<folder>` (+`_AT`, `_FRAMES`, `go` file) and `victory replay <folder> [--loops N] [--timing detailed] [--compare ...]` | one captured frame replayed without the title: card-side times per submission/command, structural experiments in seconds (`--skip-hash-passes`, `--no-barriers`, `--buffers vram`, `--skip-shader`, `--shaders`, ...) | diag build; capture stands still ~5 s and is GBs; cannot test watch/guard/landing logic or multi-frame state (`docs/replay.md`, review 08) | +| `VICTORY_DSTORAGE_LOG/_TRACE`, `VICTORY_STREAMLINE_LOG`, `VICTORY_D3D12_DRED` | streaming, DLSS, device-removed traces | | +| `VICTORY_UPCOPY_CHECK`, `faultbook`, `scripts/faultbook.py` | correctness checks and fault catalogue | | + +Ablation and A/B + +| mechanism | use | limits | +|---|---|---| +| process-level env switches | `play-foxhound.ps1 -More @{VICTORY_X='0'}`; `victory play` settings; squirrelfish `--override KEY=VALUE` (repeatable) | ~340 behaviour switches (review 08), six default idioms; the effective value is not logged | +| `VICTORY_AB=<seconds>,<SWITCH>[,<SWITCH>...]` (diag build) | alternates up to 8 switches on/off inside one run every N seconds and logs each phase's frame times (first second dropped); all 2^n combinations in turn | only switches read through `toggled!` (10 today: GUARD_REST, HELPER_PRIORITY, LAND_ECHO, LIST_VIEWS, OPEN_ONE_VIEW, QUICK_FIND, READY_ONCE, SAME_RECORDS, TAKE_PARTS, UNDER_WIDE); scene must be static, so it measures steady state only, not loading | +| F1 menu | live toggles of DLSS, frame-gen, fps cap, panel, ambient, WC_NO_BACK, RELAY, CARD_STEPS, INDIRECT_BATCH, CARD_BUFFERS_MIN_KB, LEAVE_OUT, SOFT_VIEWS, TEXTURE_NO_WAIT, EARLY_DEPTH ... | changes persist into `victory-settings.txt` (confounder) | +| `VICTORY_LEAVE_OUT=<hashes>`, `VICTORY_SKIP_PIPELINES=<hashes>` | leave out shader programs | picture changes | +| structural ablations known from docs | `VICTORY_THIN=0`, `RELAY=0/1/2`, `LATE_WAIT=0/1/2`, `ASYNC_SUBMIT=0`, `WC_NO_BACK`, `TEXTURE_BACK=0`, `JOIN_COPIES`, `CARD_STEPS`, `CARD_BUFFERS_MIN_KB`, `INDIRECT_REST`, `LEVELS_ON_DEMAND`, `PIPELINE_WAIT_MS`, `TEXTURE_BACKLOG_MS`, `SHADER_OPT` | each is described where read; the audit (`ARCHITECTURE_AUDIT.md` section 6, C1-C9) lists which are real invariants | +| pass-level switch (`passswitch`/`gfxswitch`, `VICTORY_GFX`, `gfx.txt`) | turns whole emulator passes (descriptors, heap_buffers, heap_textures, buffer_refresh, texture_refresh) and graphics methods off at run time | **fork build only**; exists in dataset A logs, not here. Valuable for "how much of the frame is pass X" (lower bound of its cost, picture may break) | + +### How to run a structural ablation (process level) + +1. Fix everything else (section 5), pick arm A (current) and arm B (one switch changed; never two). +2. `scripts\play-foxhound.ps1 -Exe '<Extracted\game_scarlett_master.exe>' -Dlss off -More @{VICTORY_RELAY='1'}` for B; plain for A. + (or `victory play ... ` with the same settings file; or squirrelfish `--auto-a --frametime-dump --override VICTORY_RELAY=1`.) +3. Interleave A B A B A B (3 each minimum). Summarize each (`--out docs\performance\runs\<tag>`, `--label "A, cold=no"`), then + `--compare` the median-ish runs, and compare the **per-run heavy medians across arms** rather than one pair. +4. Expect each run to spend 2-5 minutes in boot/load, so for steady-state-only questions use `VICTORY_AB` in one run, or record + a frame and use `victory replay --compare` (card-side only). + +## 4. What is missing, and the minimal additions proposed (not implemented; `.rs` is out of scope) + +| # | gap | evidence | minimal addition | +|---|---|---|---| +| P1 | per-run time series on this branch | frametime.csv writer, stall watchdog, GPU spans not in tree; branch logs are 5 s averages | port the fork's CSV writer (1 row/s: frames, avg, max, cpu_prepare, draws, MB columns, ram, cpu %) behind `VICTORY_FRAMETIME_DUMP`; same file format, so `summarize_run.py` works unchanged | +| P2 | true per-frame times | CSV keeps one max per second; P99 and 1% low are reconstructed | ring buffer of present-to-present microseconds (u32 per frame, ~10 MB per hour), dumped at exit as `frames.bin/csv`; summarize_run would use it when present | +| P3 | load-phase timeline | "time to heavy scene" can only be inferred from `draws`; A press and loading screen end are unknown | one `phase:` log line (epoch ms) at: process start, device ready, first present, first A/button input seen by GameInput, first frame with draws >= 1000, texture backlog empty (`HEAP_TEXTURES_WAITING == 0`), pipelines being made == 0, DirectStorage idle. Also add `tex_waiting`, `making`, `dstorage_mb_s` columns to the CSV so the drain curve is visible | +| P4 | stall attribution | watchdog fires only on "frame has not advanced" >= 400 ms; 1096 of ~1600 stalls say "no section of ours" and give no cause | (a) on any present delta over a threshold (e.g. 250 ms) log the threads' current spans/waits (data the timeline already has); (b) auto-trigger `VICTORY_TIMELINE` on the first frame over 500 ms, once per minute; (c) tag waits in the title's imports (file open, `CreateGraphicsPipelineState`, DirectStorage, fence) with a counter per frame | +| P5 | GPU time | CSV gpu columns ~0; `VICTORY_GPU_TIMING` is diag-only and alters behaviour | two timestamp queries per present around the title's submissions (first list start, last list end) resolved a frame later: GPU busy ms and idle gap ms per frame, always on, in the CSV | +| P6 | run manifest | `build unknown`, `game unknown`, no commit, no resolved switch list (the CSV lists only env-set ones) | first log line: git describe + dirty flag, exe hash, profile, **all effective `VICTORY_*` values after defaults and `victory-settings.txt`** (this is also the "resolved config dump" of review 08), driver, adapter, window size | +| P7 | scenario markers | no way to say "route started/ended" | hotkey (e.g. F9) writing `mark:` line with epoch ms into the log/CSV; summarize_run would split spans on marks | +| P8 | A press | manual and untimed; `VICTORY_AUTO_A=150` exists only in the fork | port `VICTORY_AUTO_A` (tap A for N s) so runs are reproducible, and log the first accepted press | +| P9 | cold/warm of the driver pipeline cache | only the shader translation cache is reported | log whether `cache\pipelines` held a library at start and its size; count driver pipeline compiles after world entry (ROOT_CAUSES item 2) with ms | +| P10 | frame-gen aware metrics | frame line fps is rendered fps | also log presented fps and frame-gen factor so DLSS-FG runs compare | + +Priority for validating the planned work: P1, P6, P3 (cheap, unlock every comparison), then P4 and P8, then P2, P5. + +## 5. Manual protocol for comparable runs (the user follows this exactly) + +Fixed conditions +1. Reboot, or at least close browsers, launchers, overlays, capture software and anything GPU-heavy. Same power plan (high + performance), same driver (621.01 recorded), same monitor/window size, controller connected before launch, no alt-tab, no + screenshots, no recording software during the run. +2. Settings file: decide once. For A/B delete `%LOCALAPPDATA%\victory\victory-settings.txt` (or keep it identical for all runs and + copy it to the run folder). Keep `VICTORY_PANEL` off and the F1 menu closed after the start. +3. Same build for both arms except the one change under test. Write down the commit (`git rev-parse --short HEAD`, `git status`) + and the exe path/timestamp; the files do not record it. +4. Same arguments every time: record the exact command line. Series X, one DLSS mode, one frame-gen setting; do not change + them mid-session. +5. Do not start another run within 2 minutes of the last one ending (let the system settle); never run two at once. + +Cold and warm +6. **Warm** = shader and pipeline caches populated by a previous run of the same build. **Cold** = point `VICTORY_CACHE_DIR` at an + empty folder (the shader and pipeline caches live under `cache\`), or `victory warm` before for a deliberately warmed state. + Run order for any new build: 1 discarded warm-up run (label `warmup`, excluded), then measured runs. Report cold and warm + separately; never mix them in one median. The summary prints the shader-translation cache state; the driver cache state is not + logged yet (P9), so write "warm"/"cold" in `--label`. + +Per run (about 8 minutes) +7. Start the game with the fixed command. Note the wall-clock time. +8. **When the title reaches its start screen/menu, press A on the controller once to leave it** (the game does not proceed + until A is pressed; the same press may be needed again on the next screens). Press it as soon as the screen is up, and note the + wall-clock time of the press. If a second prompt appears, press A at once again and note it. Do not touch any other + input until the world is loaded. +9. Wait for the world to load without input. When the first controllable frame appears, start a stopwatch (this is "entry"). +10. Do exactly the same scenario every run. Suggested minimum, scenario S1 (no input): stand still for 3 minutes after entry, + camera untouched. Optional scenario S2: after S1, follow one fixed route of 2 minutes (same path, same speed, same + time of day). Do not fight, drive or trigger cutscenes unless the scenario says so. +11. Quit by the same route each time (Alt+F4 or the menu) after exactly 3 min (S1) or 5 min (S1+S2) from entry; the run must + be at least 6 minutes of heavy scene to give 100+ steady windows (the median past run had 136). +12. Immediately copy `%LOCALAPPDATA%\victory\runs\<newest>\` (frametime.csv, victory.log) or `logs\play-<newest>.log`, plus + `victory-settings.txt`, into `docs\performance\runs\<tag>\<arm>-<n>\` and write a one-line `notes.txt`: commit, command, + cold/warm, A press time, entry time, scenario, anything odd (loading hang, crash, popup). + +Repeats and analysis +13. At least 3 measured runs per arm per condition, order interleaved (A B A B A B), same time of day if possible. Five if the + expected effect is under 10 %. +14. Summarize each: `python scripts\perf\summarize_run.py <run> --out docs\performance\runs\<tag> --label "<arm> warm S1 A@14s"`. + Compare medians of per-run steady-state frame ms and P99, stall windows, time from entry to stabilised, and the log + subsystem means; use `--compare` for a single pair only when explaining a mechanism. +15. Accept a difference only if it exceeds the A-to-A spread of your own repeats and is above ~5 % (`docs/findings.md`). + The existing dataset shows ordinary spread is large: consecutive runs `20261126-210725` and `-211141` differ 24 % in heavy fps + (and the second had passes off), and eras of the day differ 2x. A result that is not outside the repeat spread is a null result. +16. Discard and label (do not average) runs with a device loss, a crash, a visible hang over 10 s that was not in the other + arm's runs, or a different loading path. + +## 6. Open items for the owner + +- Decide where the CSV writer comes from (port from the fork, P1) before any perf commit is validated with numbers on this branch. +- Confirm which victory.exe the runs of Nov 26 used (`VICTORY_REPO=...\VIctory`); its commit is the real "before" for those numbers. +- The generated `docs/performance/baseline-data/` (105 files, about 1 MB) can be dropped from version control if unwanted; it is + reproducible from the logs with the command at the top of `BASELINE.md`. diff --git a/docs/performance/AGENT_REPORTS/08-review.md b/docs/performance/AGENT_REPORTS/08-review.md new file mode 100644 index 000000000..e719f9f36 --- /dev/null +++ b/docs/performance/AGENT_REPORTS/08-review.md @@ -0,0 +1,25 @@ +# 08 Architecture review (read-only) + +Full audit: `docs/performance/ARCHITECTURE_AUDIT.md`. Nothing was built or run; no `.rs` edited. + +- 425 distinct `VICTORY_*` names, about 340 behaviour switches. No single default table: code defaults (six idioms), + `Play-VIctory.cmd` (~21 overrides), `host/menu.rs`. The shipped config differs from code defaults (`THIN`, `SHOW_AFTER`, + `CARD_STEPS`, `JOIN_COPIES`, `INDIRECT_WINDOW`, `RELAY=2` are on only via the launcher). +- Real invariants: shader writes the title CPU reads land in title memory in order before any fence/present/wait that observes + them (ocean maps via `texback.rs`, culling/skinning lists, bakes); stale shader output never overwrites newer title bytes; + aliased views clean only if all read-only; slots never name unuploaded/freed textures; raw loads past a view return zeros; + indirect args bounded; wave/helper-lane semantics; dynamic slots returned on GPU completion. +- Incidental: page/block sizes, card hash passes as the detector, per-slot mirroring cadence, which thread lands, ambient values. +- Workarounds on workarounds: five title-write detectors (guards, dirty bits, texture hash, hot-hash, recheck) plus diagnostic + checks; slot-hiding chain (`SHOW_AFTER`/`KEEP_VIEWS`/`neutral()`/bake publication); relay x late-wait x join stack; + `INDIRECT_REST`; hand-tuned pressure constants. +- Doc drift: relay "off by default" comment vs on in code; `WAVE_WIDE` "kept off" in journal vs enabled in + `emit/mod.rs:747` (verify before translator work). +- Replay proves card-side equivalence for a recorded frame; it cannot prove watch/guard/landing logic, landing order, + multi-frame state, races or TDR. Its integration test is synthetic (128x128). +- Missing enablers: resolved-config dump, golden-scene image/buffer diff, title-memory digest per present (catches landing + reorder that pictures miss), soak harness, process-level A/B covering all switch idioms. +- Per-refactor checklists C1-C9 (config table, detector unification, declared writes, relay collapse, slot lifetime, budget + model, dead-switch removal, translator, async) are in section 6 of the audit. +- Order: config table + dump -> harness -> slot lifetime/budget -> detectors -> relay. +- Limits: Appendix A default classes are heuristic; confirm at the read site. diff --git a/docs/performance/ARCHITECTURE_AUDIT.md b/docs/performance/ARCHITECTURE_AUDIT.md new file mode 100644 index 000000000..3bb0520c1 --- /dev/null +++ b/docs/performance/ARCHITECTURE_AUDIT.md @@ -0,0 +1,434 @@ +# Architecture audit: the VICTORY_* mechanism stack + +Scope: read-only review of branch `perf/radical-refactor`. Sources: `docs/findings.md`, `docs/bug-journal.md`, +`docs/architecture.md`, `docs/replay.md`, `crates/victory-gpu/src/switch.rs`, module headers of the host layer, a grep of +every `VICTORY_*` name in `crates/` and `apps/`, and `Play-VIctory.cmd`. Nothing was built or run; no `.rs` file was edited. +The aim is to make deep refactors safe to attempt, not to argue against them. + +## 0. Size of the problem + +- 201k lines of Rust, 1,118 `#[test]`s. In `victory-gpu`: `host.rs` 11.5k lines, `descriptor/host.rs` 7.0k, `draw.rs` 6.0k, + `shadow.rs` 5.9k, `watch.rs` 5.3k, `resource.rs` 4.9k, `indirect.rs` 4.1k. +- **425 distinct `VICTORY_*` names** appear in code. About 60 are paths, counts or diagnostics output; roughly 340 are + behaviour switches of the host layer. By a heuristic read of the default idiom: about 130 default-on (`=0` disables), about + 100 default-off (`=1` enables), the rest numbers, modes, paths. +- **There is no single default table.** Defaults live in four places and they disagree: + 1. the code default at each read site, in at least six idioms (`toggled!`, `asked_for!`, `is_none_or(v != "0")`, + `is_some_and(v == "1")`, `map_or(...)`, `match` on strings). Only two idioms use the macros in `switch.rs`, which are also + the only ones `VICTORY_AB` can flip live; + 2. `Play-VIctory.cmd`, which sets about 21 further variables before launch: `RELAY=2`, `THIN=1`, `SHOW_AFTER=1`, + `CARD_STEPS=2`, `INDIRECT_BATCH=2`, `INDIRECT_WINDOW=1`, `JOIN_COPIES=1`, `JOIN_PARTS=8`, `RELAY_COPY=1`, `WIDE_BACK=1`, + `CARD_REHASH_RUNS=1`, `UPLOAD_AHEAD=1`, `LEVELS_ON_DEMAND=1`, `CARD_BUFFERS_MIN_KB=64`, `TEXTURE_NO_WAIT=1`, + `MAP_THREADS=1`, `CARD_AWAKE=1`, `AMBIENT=0.8`, `AMBIENT_AIR=1.5`; + 3. `host/menu.rs` (in-game launcher menu; first value of each item is what the launcher starts with); + 4. other scripts under `scripts/`. + A reader of the code sees `THIN`, `SHOW_AFTER`, `CARD_STEPS`, `JOIN_COPIES`, `INDIRECT_WINDOW` as off; the shipped + configuration has them on. **Refactors must be validated against the launcher configuration, not the code default.** +- Documentation drift found: + - `host.rs` calls relay stage 1 "off by default", but `shadow::relay()` is `!cfg!(test)` unless `VICTORY_RELAY` is set, + i.e. on; `LATE_WAIT` unset derives stage 3 from it. + - `findings.md` lists `VICTORY_THIN` as a gain without saying it is off in code and on only in the launcher; likewise + `SHOW_AFTER` as the device-loss fix while its code default is off. + - The bug journal says `VICTORY_WAVE_WIDE` is "intentionally kept off", but `victory-shader/src/emit/mod.rs:747` enables the + widening path unless `=0` (the `wide_option` read at :624 is policy-gated differently). **Needs verification** before any + translator refactor. + - `findings.md` calls `INDIRECT_REST=0` "the experiment"; the journal (2026-11-25 21:30) made 0 the default. +- Shader translations are cached. `translation_fingerprint()` (`victory-shader/src/emit/mod.rs:365`) hashes the source hash, + every switch named in the build-time `VICTORY_SHADER_SWITCHES`, and wave/RDNA/view-limit/raw-view values; `gpu/shader_cache.rs` + also lists the `WAVE_*` switches. A new shader-affecting switch not added there leaves stale translations in + `cache-pareto` and an A/B compares the same cached shaders. + +## 1. Inventory by subsystem + +"Protects against" is the failure the mechanism exists to prevent. The full name list per subsystem, split by detected +default, is in Appendix A (auto-extracted; the default class is a heuristic from the line that reads the variable and is +wrong in places; confirm at the read site). + +### 1.1 The core: title memory vs. card memory + +The one idea (findings.md): console CPU and GPU share memory; here they do not. Whatever one writes and the other reads must +be noticed and moved. Costs: noticing title writes, noticing shader writes, moving, waiting. + +| Mechanism (module) | Key switches (default) | Protects against | +|---|---|---| +| Write watch + read-only guards on physical-page views (`watch.rs`) | `VIEW_GUARD`, `OPEN_ONE_VIEW`, `PAGE_PARTS`, `TAKE_PARTS`, `GUARD_HOLES`, `GUARD_REST`, `KNOWN_HOLES`, `LIGHT_REFRESH`, `ASK_ONCE` (on); `GUARD_ASK`, `FAULT_UNLOCKED` (off) | Stale host copies: title writes a page a copy already took; one physical page mapped at several addresses (a write through any alias must open all) | +| Host copies of title buffers, "shadow" (`shadow.rs`, `host/send.rs`, `host/spans.rs`) | `CARD_BUFFERS` (on), `CARD_BUFFERS_MIN_KB` (64 in launcher), `EXACT_BACK`, `WIDE_BACK`, `UNDER_WIDE`, `UNDER_WORDS`, `SEND_OWN`, `LAND_ECHO` (on); `KEEP_SNAPSHOTS`, `WINDOWS_OWN`, `WC_NO_BACK`, `WC_BAR`, `CARD_ALL`, `CARD_SPANS` (off) | Card cannot read title memory: give draws/dispatches a coherent copy; merge shader output without overwriting newer title bytes (`merge_under_writes`) | +| Landing shader writes into title memory (`land.rs`, relay worker in `host.rs`) | `LAND`, `LAND_BESIDE`, `LAND_ANYTIME`, `LAND_TAKEN` (on); `LAND_SKIP` (off) | Title CPU code reading what shaders computed (culling lists, skinning, ocean heights) sees old data | +| Relay: a thread lands flights while the submitter prepares the next (`host.rs`, `queue/behind.rs`, `heap_marks.rs`) | `RELAY` (on; stage 2 in launcher), `LATE_WAIT*`, `RELAY_COPY` (launcher), `SPLIT_WAITS`, `CUT_WAITS`, `WAIT_FORCE`, `LATE_WAIT_WRITES`, `SUBMIT_DEPTH`, `SUBMIT_FRAMES` | Latency (serial prepare/run/land was ~220 ms of a frame); and ordering: anything observing title memory, a fence or a present must see earlier flights merged | +| Texture read-back (`texback.rs`) | `TEXTURE_BACK` (on; four water formats) | **Ocean height/displacement maps never reaching title memory: boats sink, sea plane drops** | +| Picked-view writes (`picked.rs`) | `PICKED_WRITES` (off) | Shader writes through views chosen by computed heap index never landing (4.6 MB/frame in one compute shader) | +| In-place title memory as heap (`inplace.rs`) | `INPLACE`, `INPLACE_PROBE` (off) | Experiment to remove copies; constrained by driver rules in the file header | +| Title-side write interception (`titlewrite.rs`, `safecopy.rs`) | `COPY_BESIDE`, `STORE_BESIDE` (off); `SAFE_COPY`, `SAME_RECORDS` (on) | Cost of protection flips per write fault (590 faults/frame measured); emulate `memcpy`/stores without opening blocks | +| xmem page pool / views (`victory-hle/modules/xmem.rs`) | `MAP_LEAN`, `SECTION_WINDOW`, `STREAM_NOTICE` (on); `SOFT_VIEWS`, `LAZY_VIEWS`, `MAP_RUNS` (off); `MAP_THREADS` (launcher 1) | Remapping cost; keeps guard state consistent when views are mapped/unmapped | + +### 1.2 Descriptors and views (`descriptor.rs`, `descriptor/host.rs`; 27 names) + +Console descriptors are plain bytes in title memory, mutated by the CPU and read by shaders by index. The host layer mirrors +them, builds a raw twin of every buffer view, and keeps "dynamic slots" (262k pool on NVIDIA). +On: `HEAP_SYNC`, `HEAP_SYNC_ASIDE`, `RAW_VIEWS`, `RAW_VIEW_CLAMP`, `VIEW_INLINE`, `VIEW_EXTENT`, `VIEW_BYTES`, `KEEP_VIEWS`, +`LIST_VIEWS`, `QUICK_MIRROR`, `QUEUE_MARKS`, `QUEUE_HOST_TEXTURES`, `TABLED_TEXTURES`, `SLOT_HOLDS`, `LENT_HEAP`. Off: +`SHOW_AFTER` (launcher on), `SHOW_NEW_LATER`, `HEAP_SYNC_AT_SUBMIT`, `SYNC_FINE`, `SYNC_IN_PLACE`, `SPANS_QUICK`, `TABLED_REREAD`. +Protects against: shaders reading a slot whose texture is not uploaded (device loss about every 16 minutes); out-of-bounds raw +loads (console returns zeros past a view, PC does not); dynamic slot exhaustion (journal 21:30: completed submissions pinned +slots across `bury_lag()`). + +### 1.3 Textures, residency, upload (`texture.rs`, `resource.rs`, `pool.rs`, `tiles.rs`, `residency.rs`, `texture/ahead.rs`; ~31 names) + +On: `LAZY_TEXTURES`, `TEXTURE_POOL`, `TEXTURE_GUARD`, `TEXTURE_HOT`, `TEXTURE_SAME`, `TEXTURE_ONCE`, `TEXTURE_FILL`, +`TEXTURE_SWEEP`, `HELD_LEVELS`, `DEPTH_TWINS`, `POOL_SMALL`, `UPLOAD_LOW`. Off (first three launcher-on): `UPLOAD_AHEAD`, +`LEVELS_ON_DEMAND`, `TEXTURE_NO_WAIT`, `PRELUDE_UPLOADS`, `TEXTURE_COPY`, `MAPPED_BY_PAGE`. Plus budgets (`TEXTURE_ROOM_PERCENT`, +`TEXTURE_BUDGET_MB`, `CARD_ROOM_FOR_*`) and, per the journal, a commit-headroom state machine: mild pressure vs +`critical_commit()` (< 1536 MiB), pressure entry 3 GiB RAM / 4 GiB commit, recovery 5/6 GiB, staging caps 16/32/64 MiB per +frame, `REST = 2500 ms` growth gate, 500 ms creation backoff, bake-specific reserves and a synchronous bake upload list. +Protects against: 40+ GB private memory, `E_OUTOFMEMORY` storms, texture starvation and flicker, pop-in, bake passes +(ped/decoration) needing exact title bytes at that moment. + +### 1.4 Draws and indirect execution (`draw.rs`, `indirect.rs`; ~40 names) + +`INDIRECT_BATCH` (launcher 2), `INDIRECT_WINDOW` (launcher 1), `INDIRECT_MERGE`, `INDIRECT_REST` (off), `INDIRECT_WIDE`, +`INDIRECT_CARD_BUDGET`, `THREAD_DIMENSIONS`, `WRITE_SKIP`, `BAKE_EXACT`, `BAKE_SOURCES`, `FULL_CARD_PASS`, `HEAP_RECHECK`, +`HEAP_SPREAD`, `READY_ONCE`, `RECHECK_SOON`, `QUEUE_BATCH`. Protects against: console ExecuteIndirect semantics on +GPU-produced arguments (counts clamped to buffer size and a per-list budget so a garbage record cannot hang the card), dispatch +groups over 65,535 (blocky patches), the ray dispatch "counts are threads" flag ("every ray missed"). In-tree `BENCH_*` +measurement hooks. + +### 1.5 Submission and lists (`list.rs`, `list/thin.rs`, `host.rs`, `queue.rs`; ~60 names) + +`THIN`/`THIN_THREADS` (lists written down, translated by eight threads), `JOIN_COPIES`, `JOIN_PARTS`, `JOIN_LISTS`, +`REFRESH_AHEAD`, `REFRESH_FRONT`, `WIDE_FILLS`, `WIDE_TEXTURES`, `WIDE_MERGE`, `LAZY_PRELUDE`, `FRESH_OPEN`, `LIST_POOL`, +`SCRATCH_POOL`, `CARD_STEPS` (do title-buffer copies and fills on the card), `ASYNC_SUBMIT`/`ASYNC_QUEUE` (measured not worth +it), `FAST_CORES`, `HELPER_PRIORITY`. Throughput mechanisms; all could in principle be replaced if the plain path stays as the +oracle. + +### 1.6 Pipelines and shader translation (`pipeline/*`, `victory-shader`; ~41 names) + +Pipeline workers, early (unordered) pipelines, `PIPELINE_LOWEST`, `PIPELINE_WAIT_*`, `SKIP_PIPELINES`, library mapping +(`LIBRARY_MAP/HANDLE/TRIM`), BVH builder (`BVH_BOUNDS`, `BVH_FENCES` on; `BVH_BUILDER`, `BVH_QUARANTINE` off). Output-affecting +translator knobs (cache-fingerprinted): `WAVE_WIDE`, `WAVE_LOCAL`, `WAVE_DEEP_SKIPS`, `WAVE_OWN_BITS`, `HELPER_OWN`, +`FIRST_HALF`, `FIRSTLANE_OWN`, `F16_NEAREST`, `FILTER_3D`, `STRICT_JOINS`, `MESH_OUTPUT_STRICT`, `SHADER_OPT`, +`SHADER_LOOP_LIMIT`, `RDNA_FLOAT`, `EARLY_DEPTH`, `RAW_VIEWS`, `VIEW_LIMIT`. Protects against: wave semantics mismatch (wave64 +vs wave32, helper lanes in quad reads, loop-widening TDR), DXIL `Log` base, normalized codes, shadow artefacts. + +### 1.7 Presentation and approximations (`streamline.rs`, `dxgi.rs`, `compose.rs`, `ambient.rs`) + +`DLSS*`, `FRAMEGEN*`, `STREAMLINE_*`, `DISPLAY_*` are optional features. `AMBIENT*` is a stand-in for a missing +probe/lighting contribution, an explicit fidelity approximation; `AMBIENT_AIR=1.5` was added "to clear milky indoor haze", +a tuning knob on a workaround. + +### 1.8 HLE, loader, formats (55 names) + +Mostly debug, path and test hooks (`KEYS`, `SAVE_*`, `STACKS`, `XMA_*`, `BCPACK_*`, `DSTORAGE_*`). Real behaviour: `PATCH_WAITS` +(monitorx/mwaitx), `PATCH_CLZERO`, `CLZERO_ASK`, `ONE_PAD`, `SKIP_BINK`, `FRAME_INTERVAL_*`. These emulate console-only +instructions and are fidelity-required, not optimisations. + +### 1.9 Diagnostics (replay, capture, book, timeline, pop-watch, fault-book, panel; ~37 names) + +Mostly `diagnostics`-feature only. Not a refactor risk except as the **validation toolbox** (section 5). + +## 2. Compatibility invariants + +### 2.1 REAL invariants (violating one produces visible or physical wrongness) + +- **R1. Shader-written data the title CPU reads reaches title memory in order, before the CPU can observe it** through a fence, + present or memory wait. Instances: ocean height/displacement maps (`texback.rs`, tiled back in console layout), culling and + skinning lists (`land.rs`), BVH sizes, ped/decoration bakes (`BAKE_EXACT`). Enforced by one landing thread, flights landed + in `LINE` order, a landing completed whole before the title is told anything (`Host::relay_land`). +- **R2. Title writes are never overwritten by stale shader results or older copies.** A merge never stores into memory the card + may still be writing, and bytes the title wrote after a flight was prepared survive (`merge_under_writes`, `SEND_OWN`, + numbered sends). Failure seen: "rare lost write", 6 of 200 stress runs, fixed (0 in 603). +- **R3. A page shown at several addresses is clean only while every view is read-only** (`watch.rs` `cover`/`open`); a write + through any alias invalidates all; a later-mapped view re-checks the others (`views_mapped`). Exempt: pages shown in more + than `MANY_VIEWS` places. +- **R4. A descriptor slot never names a texture whose upload has not run, nor freed card memory** (`SHOW_AFTER`, `KEEP_VIEWS`, + bake slot publication, `KEEP_FREED`, `release_tables`). Failure: device loss. +- **R5. Raw/structured loads past a view's end return zeros** (shaders rely on it): raw twins, `ROOT_SRV_DIRECT`, + `RAW_VIEW_CLAMP`; the translator's `RAW_VIEWS`/`VIEW_LIMIT` must match the host's heap layout. +- **R6. Indirect execution is bounded** so one garbage record cannot lose the device, without zeroing every later draw + (`INDIRECT_REST=0`). +- **R7. Wave and lane semantics:** helper lanes in quads (`HELPER_OWN`), wave ops with inactive lanes (`WAVE_OWN_BITS`), + waterfall loops, dual-source blend, dead-lane join edges (journal 21:30). Translator passes must be exact. +- **R8. Dynamic descriptor capacity returns on GPU completion**, not 16 submissions later (NVIDIA 262k pool). +- **R9. Console-only instructions are emulated** (clzero, monitorx/mwaitx, TLS redirection) and the title's `memcpy` family is + safe on guarded pages. +- **R10. Memory admission never fails hard:** backoff on `E_OUTOFMEMORY`, a split between mild and critical pressure. + +### 2.2 INCIDENTAL invariants (true of today's implementation, not needed by the title) + +- I1. Which thread lands (relay worker, `land` pool). Only the ordering in R1/R2 matters. +- I2. Granularity: 64 KiB blocks, 4 KiB kernel dirty bits, 32-byte compare units, 8-snapshot pool. Contract is "no stale byte + survives" (R2); `PAGE_PARTS`, `UNDER_WORDS`, `CARD_HASH_LEN` are tunings. +- I3. Card-side hash passes as the way to find shader writes. The requirement is "know what shaders wrote"; alternatives: + declared writes from descriptor analysis (as `PICKED_WRITES` does for one class), or in-place heaps if the driver permits. +- I4. Preparing every host list on the submit path (`THIN`, `ASYNC_QUEUE=plan`, `JOIN_*`, `REFRESH_FRONT` all rearrange it). +- I5. Per-slot descriptor mirroring and the sixteenth-pass re-look cadence (`HEAP_SPREAD`, `RECHECK_SOON`, `READY_ONCE`); + partial ports of a journal (`HEAP_SYNC_AT_SUBMIT`, Belobug port 7) already exist. +- I6. `AMBIENT=0.8`, `AMBIENT_AIR=1.5` values (tuned visually). +- I7. Pool/block sizes: ripe blocks 12, staging block 64 MiB, `SNAPSHOT_POOL=8`. +- I8. Env-var configuration itself (read once per process in `OnceLock`s). + +## 3. Workarounds on workarounds and over-conservative areas + +1. **"Did the title write this?" has five detectors:** kernel dirty bits, read-only guards plus fault handler, a hash of + textures "when the guard saw no write although the hash found one" (`TEXTURE_HOT`, an admission the guards miss writes), + re-looking at slots every 16th pass (`HEAP_SPREAD`, `RECHECK_SOON`), and diagnostic checks (`REFRESH_CHECK`, `FETCH_CHECK`, + `UPCOPY_CHECK`) that exist because the rest are not fully trusted. The cleanest simplification is one title-write + notification contract with an oracle (V3, C2). +2. **Hide or delay a bad slot rather than make it correct:** `SHOW_AFTER`, `SHOW_NEW_LATER`, `KEEP_VIEWS`, `KEEP_SHOWN`, + `neutral()`, bake slot publication, `STALE_TEXTURES`, `KEEP_FREED`. Each fixes the previous one's corner (journal 21:30: + bake slots overwritten with `neutral()`). Underlying cause: slot lifetime not tied to upload and submission lifetime. One + "slot publishes at upload-fence completion, releases at GPU completion" rule would subsume most. +3. **Pressure throttling** (`residency.rs`, `pool.rs`, `texture/ahead.rs`): about ten hand-tuned constants from two machines + (32 GiB and 64 GiB RAM). Over-conservative on big hosts, fragile on small. Candidate: one budget model with pressure + sources as inputs. +4. **Indirect clamps:** `INDIRECT_BATCH/WINDOW/MERGE/REST/CARD_BUDGET/WIDE`. `INDIRECT_REST` is the clearest + workaround-on-workaround: the budget bounds garbage, then its leftover mode emptied all later records (suspected outdoor + flicker), fixed by turning the leftover mode off. Replay `--skip-clamps`/`--batch-clamps` measure time; correctness cost is + measured less precisely. +5. **Relay stack:** `RELAY` 1/2, `LATE_WAIT` 0..3, `SPLIT_WAITS`, `CUT_WAITS`, `WAIT_FORCE`, `LATE_WAIT_WRITES`, + `SUBMIT_DEPTH/FRAMES`, `HEAP_SYNC_FIRST/AT_SUBMIT/ASIDE/EARLY`, `REFRESH_AHEAD/FRONT`, `JOIN_*`: four interacting + pipelining levels, each with an "as before" off switch. Only the launcher corner is exercised in practice; other + combinations are likely broken. The code comment that walls of the first room were "drawn in every run with this set and in + fewer than half without it" shows these switches carry correctness, not only speed. +6. **Texture read-back by kind, not by texture** (`texback.rs`): any matching compute-written texture is copied back (~1 MB per + list). Cheap and correct; keep until a title-read tracker exists (`READ_WATCH=1` is the instrument that found it). +7. **Where does a buffer's copy live:** `CARD_BUFFERS`, `CARD_ALL`, `CARD_SPANS`, `WINDOWS_OWN`, `WC_BAR`, `WC_NO_BACK`, + `COPIES_IN_PLACE`: a design space explored one switch at a time; several are dead experiments kept with their code. +8. **Shader translation is already exact and best-tested** (`valu_tests.rs` 2.4k lines, differential tests against console + `dxc`); findings say under 1 ms left there. Little to gain, little to fear. +9. **Measurement/dead switches in production paths:** `BENCH_*`, `BLOCK_WAY`, `MESH_TEST`, `SCISSOR_TEST`, `BARRIER_TEST`, + `COPY_MODE`, `COPY_OVER_TITLE`, `TILES_TEST_CARD`, `WAIT_ASK`, `CUT_WRITES`, `FILL_TITLE`, `SEND_CHANGED`. Each is a branch + a reader must prove dead. + +## 4. Risks of deep refactors + +### 4.1 Concurrency, lifetime, ownership + +- **Threads (from module headers):** title threads (write faults arrive in the vectored handler, first in the process, shared + with `safecopy`); the submitting thread holding the submission lock; THIN translate threads; the relay/landing thread plus + the `land` pool; the heap-sync thread (and ASIDE); pipeline workers; raised-priority helpers (`FAST_CORES`, + `HELPER_PRIORITY`); settle/sweep timer; DirectStorage threads. Cross-thread state is mostly `OnceLock` statics and global + `Mutex`es in `watch.rs`, `shadow.rs`, `descriptor/host.rs`; ordering rules are in prose and enforced by convention. +- **Fault-handler context.** The handler and `safecopy` run inside faults of any title thread and of our own copies; they must + not take a lock the faulting thread may hold, nor allocate. Moving state across a lock hierarchy can deadlock only under + specific title behaviour (the lost-write race needed ~200 runs to show). +- **Descriptor lifetime.** `Detached._state`, dynamic slots released on GPU completion, stride buffers held by the list, + `bury_lag=16`. Changing who owns a list or slot table changes when slots return. Guard: the "dropped draw: exhausted dynamic + descriptor slots" log line must stay at 0. +- **Flights and declared ranges.** `shadow::relay` proves merge safety from declared ranges per flight. Changing what is + declared (`WRITE_SKIP`, `PICKED_WRITES`, `CARD_STEPS`) changes that proof. +- **Slow-burn failures.** The 16-minute device loss and the 1-in-30 lost write do not appear in a 5 minute check. A soak run is + part of validation. +- **`OnceLock` switches** cannot vary inside a process; two configurations need two processes (or `VICTORY_AB` for the two macro + idioms in a diagnostics build). +- **Cache poisoning:** translations and pipeline libraries persist on disk; a translator behaviour change must change the + fingerprint. + +### 4.2 Fidelity-regression risks and what catches them + +| Failure | Looks like | Caught by | +|---|---|---| +| Ocean maps not read back | boats sink, sea plane under (minutes) | boat mission run; `READ_WATCH=1` counts of CPU reads of water kinds | +| Lost title write (merge race) | rare world corruption | repeated stress test (603 clean runs was the bar) | +| Stale buffer/texture copy | flicker, pop-in, wrong materials | `REFRESH_CHECK`, `UPCOPY_CHECK`, `FETCH_CHECK`, `POP_WATCH` | +| Slot names unready texture | device loss in ~16 min | 30+ min soak, `book`, `SLOT_CHECK=1` | +| Wrong indirect clamp | outdoor flicker, empty draws | frame-line counters of clamped/empty records; replay compare | +| Translator regression | one shader black or blocky | `translate --validate --pipelines` (43/43 graphics, 96/111 compute baseline), differential tests | +| Landing order/timing changed | physics/AI drift (boat jitter) with identical pictures | not visible in pictures: needs title-memory digest (V4) | +| Ambient stand-in | haze or light level | screenshot compare only | + +The last two rows are the dangerous ones: a refactor that reorders landing relative to title reads can pass every picture +test and still change simulation. + +## 5. What validation exists, and what it proves + +**Replay** (`replay/`, `docs/replay.md`, `tests/replay.rs`, `tests/replay_big.rs` ignored): records one frame of host D3D12 +work and the memory it reads; replays without the title. Tools: `--compare`, `--images`, `--pixel`, `--diverge`, +`--check-written`, `--upcopies`, `--watch`, `--flow`, `--slots`, `--retranslate`, `--shaders`/`--shaders-b`, `--skip-*`, +`--no-barriers`, `--wait-all`, `--debug-layer`. The integration test runs a small synthetic program (clears, indirect draws of +textures picked from a heap, compute, buffers changed between submissions, descriptors replaced, aliased textures) with and +without the recorder, replays one frame, and requires every picture and buffer to match byte for byte. + +It **proves**: a change to what is sent to the card (translator output, barriers, clamps, buffer residence, card-side hash +passes, PSO choice) gives the same picture and card memory for a recorded frame (up to the intrinsic non-determinism of atomics: +use `--diverge`/`--no-merge` to separate). + +It **cannot prove**: +- anything on the CPU side of the host layer: write watch, guards, landing, descriptor sync, and the timing/ordering of landings + (the replay re-injects recorded CPU writes between submissions; the logic that decided what to send is bypassed); +- multi-frame state (read-back chains, ocean, streaming, residency, pressure); +- real-time behaviour: races, TDR, stalls (the title stands still while recording); +- what `notes.txt` lists as not recorded: reserved resources, bundles, ray tracing, predication, stream output, + `ClearUnorderedAccessView`, newer creation methods; addresses in indirect arguments are not rewritten. + +The synthetic test is 128x128 and covers the record/replay path more than title regression. Other existing instruments: +`VICTORY_AB`, `VICTORY_TIMELINE`, `GPU_TIMING`, `POP_WATCH`/`POP_FOLDER`, `FAULT_BOOK`, `BOOK`/`SLOT_CHECK`, `REFRESH_CHECK`, +`UPCOPY_CHECK`, `FETCH_CHECK`, `READ_WATCH`, `WALLS_TRACE`, frame-line counters, `victory translate --validate --pipelines`, +differential translator tests (need `VICTORY_CONSOLE_DXC`, skipped otherwise). Capture screenshots with Windows Graphics +Capture (GDI returns white). + +## 6. Validation checklist per candidate deep refactor + +**Common baseline (once).** Golden configuration = `Play-VIctory.cmd` environment. Fixed save, a fresh copy per run, same cache. +`VICTORY_RECORD` captures of 3-4 named scenes (street, indoor, boat on the ocean, vehicle chase). Per run keep the log's +frame lines and counters: lost-write, dropped draws (descriptor slots), `E_OUTOFMEMORY`, device-lost. Land each refactor +behind a new default-off switch, pass the checklist, flip the default, delete the old path in a separate commit. + +**C1. One default table (config-only).** Generate (name, default, owner, launcher override) and route all reads through it. +Proof: log the resolved value of all 425 names in old and new builds under the launcher env and under an empty env; diff must +be empty. Shader cache fingerprint identical; `translate` on the 154-shader set byte-identical. + +**C2. Replace the guard/hash/recheck detector stack with one title-write notification layer.** +- Differential detector in one diagnostics process: the set of pages "written since last look" by old and new for every + refresh; any page old marks and new misses fails. `REFRESH_CHECK`/`UPCOPY_CHECK` are the byte-level oracle. +- Stress: lost-write test, at least 600 runs (previous bar); aliased-views test (one physical page at N addresses; a thread + writing a guarded alias while a submission prepares). +- 60 minute soak with `FAULT_BOOK` and `SLOT_CHECK=1`: zero device-lost, no increase in `POP_WATCH` blips. +- Handler audit: no allocation or new lock in the fault path. + +**C3. Declared shader writes instead of card hash compare (extend `PICKED_WRITES`).** +- Keep the compare running in a diagnostics build and assert declared is a superset of compare-found for every frame of a + 10 minute drive (`--check-written`; `--upcopies` second view: "pieces shaders wrote that were not declared"). +- Replay `--images` identical on all scenes; boat floats a full mission; V4 digest unchanged. + +**C4. Collapse relay/late-wait/pipelining into one pipeline.** +- Characterise first: run relay x late-wait x launcher combinations 5 minutes each logging `WALLS_TRACE`, dropped draws, pops; + find which are equivalent. +- Ordering test (new, needs a title-thread stand-in): a deterministic compute writes known words per flight; a CPU observer + reads title memory at a fence, a present and a memory wait; it never sees flight N+1 before N and always sees N after the + fence. `tests/replay.rs` already has the GPU program. +- Stress at `SUBMIT_DEPTH=1` and `64`, `QUEUE_BATCH=0`. +- Perf: median of at least 15 intervals with at least 1,000 draws/frame (journal method) vs baseline; stalls over 200 ms + counted; differences under 5 % are noise (findings). + +**C5. Descriptor slot lifetime (publish at upload completion, release at GPU completion).** +- Peak dynamic slots in use and dropped draws must be 0; remove `bury_lag` as a test case. +- 30+ minute soak plus a texture-heavy flythrough; no black/neutral textures (screenshots, `POP_WATCH`); on NVIDIA (262k pool) + and AMD. +- Replay `--slots` and `--flow` before/after: heap slot to resource mapping identical. + +**C6. Texture/upload budget model.** +- Reproduce the `E_OUTOFMEMORY` storm with the failing-allocator test from the journal (8 upload sizes) and a job-object memory + limit at 16/24/32/64 GiB equivalents. +- Zero `E_OUTOFMEMORY`/aborts, peak commit not above prior, pending-upload count and median ms/frame not worse. + +**C7. Delete dead/measurement switches and "as before" branches.** +- Resolved-config diff (C1); replay `--compare` picture identical on one capture; `cargo test -p victory-gpu --features + diagnostics` and workspace tests (journal reference: 335 passed, 34 ignored). Delete by subsystem to allow bisect. + +**C8. Translator changes (wave/helper/join).** +- `translate --validate --pipelines` on the VFX/particle/eye set (43/43 graphics, 96/111 compute; the 15 must not grow), + `victory-shader` suite (281), console-dxc differential tests, replay `--retranslate` + `--compare --shaders-b` on all scenes, + screenshots of shadow edges, cubemaps, transmission. Confirm the fingerprint changes. + +**C9. Multi-queue / async.** +- D3D12 debug layer and GBV (`D3D12_DEBUG`, `D3D12_GBV`, `REPLAY_GBV`, `VICTORY_TEST_D3D_DEBUG=1`); replay `--wait-all` / + `--wait-lists`. Previously measured not worth it on the RX 7900 XTX; require a measured NVIDIA win first. + +### Validation tooling gaps (cheapest enablers) + +- **V1. Resolved-config dump:** one startup log line with every switch's value and source. Without it runs are unattributable. +- **V2. Golden scene set:** stored `--images` outputs and buffer digests plus a diff script; include an ocean scene. +- **V3. Title-write notification oracle:** at each submission re-read pages claimed unchanged and flag missed writes (extend + `REFRESH_CHECK` across all consumers). +- **V4. Title-memory digest per present:** hash fixed regions (water maps, entity transforms, culling lists) on a deterministic + scripted input (`VICTORY_KEYS=<seconds>:<key>` exists); compare across builds. Catches landing-order changes pictures miss. +- **V5. Soak harness:** 60 minute scripted drive with fault-book and slot-check; summary of device-lost, dropped draws, pops, + stalls over 200 ms. +- **V6. Process-level A/B:** launch configs A and B on the same save and compare frame-line stats and blips; extend `VICTORY_AB` + to all switch idioms. + +## 7. Suggested order + +1. V1, C1, C7 (clearly dead switches): no behavioural risk, makes every later comparison attributable. +2. V2, V4, V5: the harness that makes C2-C5 safe. +3. C5 (slot lifetime), C6 (budget): where most journal bugs live, most contained. +4. C2/C3 (detectors) behind a new switch, old detectors kept as the diagnostic oracle. +5. C4 last: the relay stack is the throughput core and R1/R2 are hardest to test. + +## Appendix A. Switch names by subsystem (auto-extracted) + +Default class is a heuristic from the reading line (`is_none_or(v != "0")` read as on, `is_some_and` as off); `mode` = unclear. +Treat as a map, not truth; launcher overrides in section 0 apply. Known misreads: `WAVE_WIDE` listed on (see section 0), +`UPLOAD_AHEAD` and `KEEP_SHOWN` are off/launcher-driven. + +**Shader translator (victory-shader)** (18) + +- default off (needs `=1`/set): CONSOLE_DXC, DIFF_ONLY, EARLY_DEPTH, WARP +- value/number/path: RDNA_FLOAT, REF_PS, REF_VS, SHADER_LOOP_LIMIT, SHADER_OPT +- mode or unclear from the read site: DESC_WHY, DXIL, EMIT_DUMP, GROUP_SYNC, PROBE, SHADER_CENSUS, SHADER_SOURCE_HASH, SHADER_SWITCHES, WAVE_WHY + +**Formats/audio/input/HLE (non-GPU)** (55) + +- default on (unset = on, `=0` disables): CLZERO_ASK, MAP_LEAN, ONE_PAD, PATCH_CLZERO, PATCH_WAITS, SECTION_WINDOW, STREAM_NOTICE, STREAM_PRIORITY +- default off (needs `=1`/set): DSTORAGE_HALF, EFFICIENCY_MODE, LAZY_VIEWS, MAP_RUNS, MOUSE_WARP, PROCESS_PRIORITY, SOFT_VIEWS, TITLE_PRIORITIES +- value/number/path: AUDIO_CAPTURE, BCPACK_CASES, BCPACK_TABLES, CACHE_DIR, DATA_DIR, DSTORAGE_RETRIES, DSTORAGE_STAGING_MB, DSTORAGE_TRACE, FULLSCREEN_RES, KEYS, LOG_FILE, MAP_THREADS, MOUSE_CAPTURE, SKIP_BINK, WINDOW_MAX +- mode or unclear from the read site: AUDIO_CAPTURE_OF, CONFIG, DSTORAGE_IO, DSTORAGE_LOG, DUALSENSE, EXIT_CHILD, FULLSCREEN, GAME_DIR, HOST_LOCK_CHILD, IMAGE_WATCH, IME_ENGLISH, KEYS_FILE, LOG, PROFILE, RELAUNCHED_FROM, SAVE_CHILD, SAVE_OP, SAVE_STOP, STACKS, TEST_TITLES, TRAP_LOG, XMA_DUMP, XMA_REFERENCE, XMA_STREAMS + +**Replay / capture / diagnostics** (37) + +- default on (unset = on, `=0` disables): BOOK, MEMORY_MAP +- default off (needs `=1`/set): DUMP_TARGETS, FETCH_CHECK, LATE_WAITS, PANEL, POP_ALL, RECORD_ALWAYS, SLOT_CHECK, TIMER_LOG, UPCOPY_CHECK +- value/number/path: A, AB, B, CAPTURE_FRAMES, CAPTURE_WORLD_ALSO, FAULT_BOOK, FAULT_BOOK_AT, FRAME_INTERVAL_MS, FRAME_INTERVAL_US, KEEP_SHOWN, POP_WATCH, RECORD, RECORD_AT, RECORD_FRAMES, TIMELINE, TIMELINE_AT, TIMELINE_FRAMES, UPLOAD_AHEAD +- mode or unclear from the read site: BARRIER_TEST, CAPTURE, CAPTURE_WORLD, COPY_MODE, NONE_SUCH, POP_FOLDER, REPLAY_GBV, REPLAY_PEEK + +**Streamline/DLSS/framegen/display** (22) + +- default on (unset = on, `=0` disables): DLSS_JITTER, DLSS_MV, DLSS_REACTIVE, FRAMEGEN_HUDLESS, STREAMLINE_LOG +- default off (needs `=1`/set): AMBIENT_ONCE, CHECK_TEARDOWN, DLSS, FRAMEGEN, STREAMLINE_PRESENT, THIN +- value/number/path: AMBIENT, AMBIENT_AIR, AMBIENT_SHADE, AMBIENT_SPECULAR, DISPLAY_MODE, DISPLAY_REFRESH, FRAMEGEN_CYCLE, FRAMEGEN_X, STREAMLINE_DIR +- mode or unclear from the read site: DLSS_MODE, DLSS_PRESET + +**Pipeline creation** (23) + +- default on (unset = on, `=0` disables): ACTIVATE_RAYS, LIBRARY_HANDLE, LIBRARY_MAP, LIBRARY_TRIM, PIPELINE_LOWEST, PIPELINE_WAIT_SHARED, RT_RESOLVE +- default off (needs `=1`/set): BVH_BUILDER, BVH_QUARANTINE, EARLY_ALL, LIBRARY_LOCK, LIBRARY_STATIC_SAMPLERS, PIPELINE_BOOK, PIPELINE_SLOW, WATER_LIGHT +- value/number/path: LEAVE_OUT, PIPELINE_WAIT_MS, PIPELINE_WORKERS, SCREEN_WAIT_MS, SKIP_PIPELINES +- mode or unclear from the read site: PC_DXC, ROOT_SRV_DIRECT, SHADER_SAVE + +**Indirect/draw/bind** (40) + +- default on (unset = on, `=0` disables): BAKE_EXACT, BAKE_SOURCES, FULL_CARD_PASS, HEAP_RECHECK, HEAP_SPREAD, HEAP_TEXTURES, INDIRECT_WIDE, QUEUE_BATCH, READY_ONCE, RECHECK_SOON, REUPLOAD_WHEN_FULL, TEXTURE_CATCHUP, THREAD_DIMENSIONS, WRITE_SKIP +- default off (needs `=1`/set): AMBIENT_SPECULAR_ALPHA, BENCH_WARP, CARD_ACCOUNTING, INDIRECT_MERGE, INDIRECT_REST, INDIRECT_WINDOW +- value/number/path: BENCH_CS, BENCH_N, BENCH_S, BENCH_THREADS, BIND_CACHE, LIST_SLOTS, MESH_TEST, PICKED_MB, ROOT_UAV_MB, ROOT_VIEW_MB, TEXTURE_STAGE_MB, TEXTURE_STAGE_MS, UNWATCHED_FRAMES +- mode or unclear from the read site: BAKE_TEXTURES_MS, BLOCK_WAY, EARLY_TEXTURES_MS, INDIRECT_BATCH, NATIVE_1440P, PICKED_WRITES, SCISSOR_TEST + +**Descriptors/heaps/views** (27) + +- default on (unset = on, `=0` disables): HEAP_SYNC, HEAP_SYNC_ASIDE, KEEP_VIEWS, LENT_HEAP, LIST_VIEWS, QUEUE_HOST_TEXTURES, QUEUE_MARKS, QUICK_MIRROR, RAW_VIEWS, RAW_VIEW_CLAMP, SLOT_HOLDS, TABLED_TEXTURES, VIEW_BYTES, VIEW_EXTENT, VIEW_INLINE +- default off (needs `=1`/set): HEAP_SYNC_AT_SUBMIT, SHOW_AFTER, SHOW_NEW_LATER, SPANS_QUICK, SYNC_FINE, SYNC_IN_PLACE, TABLED_REREAD, VIEW_COPY +- value/number/path: DYNAMIC_SLOTS, HEAP_SYNC_EARLY, TEXTURE_AWAY_MS +- mode or unclear from the read site: STALE_TEXTURES + +**Textures/residency/pools** (31) + +- default on (unset = on, `=0` disables): ALIAS_COPY, DEPTH_TWINS, EXACT_NO_WAIT, HELD_LEVELS, LAZY_TEXTURES, MAPPED_BY_VIEWS, POOL_SMALL, TEXTURE_FILL, TEXTURE_GUARD, TEXTURE_HOT, TEXTURE_ONCE, TEXTURE_POOL, TEXTURE_SAME, TEXTURE_SWEEP, UPLOAD_LOW +- default off (needs `=1`/set): COMMITTED_QUERY, LEVELS_ON_DEMAND, MAPPED_BY_PAGE, PLACED_FILLER, PRELUDE_UPLOADS, STAGED_ASK_ALL, TEXTURE_COPY, TEXTURE_NO_WAIT, TILES_TEST_CARD +- value/number/path: CARD_ROOM_FOR_TARGETS_MB, CARD_ROOM_FOR_TARGETS_SETTLE_MS, LEVELS_MIN_KB, RIPE_BLOCKS, TEXTURE_BUDGET_MB, TEXTURE_ROOM_PERCENT +- mode or unclear from the read site: BENCH_FILE + +**Write-watch/guards/landing/title writes** (31) + +- default on (unset = on, `=0` disables): ASK_ONCE, GUARD_HOLES, GUARD_REST, KNOWN_HOLES, LAND, LAND_ANYTIME, LAND_BESIDE, LAND_TAKEN, LIGHT_REFRESH, OPEN_ONE_VIEW, PAGE_PARTS, SAFE_COPY, SAME_RECORDS, TAKE_PARTS, VIEW_GUARD +- default off (needs `=1`/set): COPY_BESIDE, FAULT_UNLOCKED, GUARD_ASK, LAND_SKIP, STORE_BESIDE +- value/number/path: ASK_EARLY, GUARD_HOT, INPLACE, INPLACE_MB, INPLACE_PROBE, INPLACE_PROBE_MB, LAND_THREADS, UNDER_THREADS, VIEW_THREADS +- mode or unclear from the read site: PAGE_WRITES, WRITE_SITES + +**Host copies/card buffers (shadow)** (34) + +- default on (unset = on, `=0` disables): CARD_BUFFERS, CARD_HASH_LEN, CARD_ROOM_FOR_BUFFERS, COPIES_IN_PLACE, EXACT_BACK, HEAP_PASS_ASIDE, LAND_ECHO, QUICK_FIND, SEND_OWN, UNDER_WIDE, UNDER_WORDS, WIDE_BACK +- default off (needs `=1`/set): CARD_ALL, CARD_SPANS, KEEP_SNAPSHOTS, PLACED_ORDER, REFRESH_CHECK, SEND_BAR, WC_BAR, WC_NO_BACK, WINDOWS_OWN, WINDOW_TAILS +- value/number/path: CARD_BUFFERS_MIN_KB, CARD_WINDOWS_MB, KEEP_SNAPSHOTS_MB, MEMORY_CARD_MB, SNAPSHOT_POOL, WC_NO_BACK_MIN_KB, WIDE_SPIN, WINDOWS_BAR_MB, WINDOW_KB +- mode or unclear from the read site: CARD_BUFFERS_MB, CARD_BUFFERS_MIN_MB, CARD_STEPS + +**Queue/submission/relay/lists** (61) + +- default on (unset = on, `=0` disables): BENCH_HOLES, CUT_WAITS, DIRECT_WRITES, FRESH_OPEN, INDIRECT_CARD_BUDGET, KEEP_FREED, LATE_WAIT_WRITES, LAZY_PRELUDE, LIST_POOL, QUEUE_WAIT, READ_BACK, REFRESH_AHEAD, RELAY, SCRATCH_POOL, SPLIT_WAITS, SWEEP, TEXTURE_KEEP, TRAIL, WAIT_FORCE, WAIT_RESIDENT, WIDE_FILLS, WIDE_TEXTURES +- default off (needs `=1`/set): ASYNC_SUBMIT, BVH_SIZES_WAIT, BVH_TRACE, CARD_REHASH_RUNS, COPY_ASK, CUT_WRITES, D3D12_BACKGROUND, D3D12_DEBUG, D3D12_DRED, D3D12_GBV, D3D12_WARP, FILL_TITLE, GPU_TIMING, HEAP_SYNC_FIRST, JOIN_COPIES, REFRESH_FRONT, RELAY_COPY, SEND_CHANGED, WAIT_ASK, WALLS_TRACE, WIDE_MERGE +- value/number/path: BURY_LAG, DECLARE_ONCE, FAST_CORES, GPU_LOAD_MS, HELPER_PRIORITY, JOIN_LISTS, JOIN_PARTS, LATE_WAIT_LISTS, SUBMIT_DEPTH, SUBMIT_FRAMES, TEST_ROUNDS, THIN_THREADS +- mode or unclear from the read site: ASYNC_QUEUE, CARD_AWAKE, COPY_OVER_TITLE, LATE_WAIT, MEMORY_DUMP, WIDE_REFRESH + +**Other** (16) + +- default on (unset = on, `=0` disables): BVH_BOUNDS, BVH_FENCES, FIRST_HALF, HELPER_OWN, WAVE_DEEP_SKIPS, WAVE_LOCAL, WAVE_OWN_BITS, WAVE_WIDE +- default off (needs `=1`/set): F16_NEAREST, FILTER_3D, FIRSTLANE_OWN, PORT_CONSTANTS +- mode or unclear from the read site: MESH_OUTPUT_STRICT, STRICT_JOINS, TEXTURE_BACK, TRANSLATOR \ No newline at end of file diff --git a/docs/performance/BASELINE.md b/docs/performance/BASELINE.md new file mode 100644 index 000000000..efdf63291 --- /dev/null +++ b/docs/performance/BASELINE.md @@ -0,0 +1,153 @@ +# Baseline from the sessions already recorded + +Every number below was computed by `scripts/perf/summarize_run.py` from files on this PC; nothing is estimated. +Per-run output: `docs/performance/baseline-data/<run>.summary.{md,json}`, one-row-per-run table: +`docs/performance/baseline-data/index.md`. Regenerate with + + python scripts/perf/summarize_run.py "%LOCALAPPDATA%\victory\runs\2026*" "%LOCALAPPDATA%\victory\logs\play-*.log" ^ + "%LOCALAPPDATA%\victory\cache\frametime.csv" --out docs\performance\baseline-data + +Times in the files are UTC; the PC is UTC-3 (run folder names are local time). + +## Read this first: what these sessions are, and are not + +- **There is no controlled baseline.** No two sessions are labelled as the same scenario, the build/commit is not + recorded (`build unknown` in every log, `game: unknown` in every CSV header), and the route after world entry is not + recorded. Treat the figures as a survey of what the user's machine did, not as a reference build. +- **Two different builds produced the data.** + - Dataset A, 46 run folders `%LOCALAPPDATA%\victory\runs\20261126-123718 ... 20261126-211141` (Nov 26, 12:37 to 21:17 + local) plus `cache\frametime.csv`. These have `frametime.csv` (1 s windows) and a rich `victory.log`. They came from a + victory.exe with instrumentation that is **not in this branch**: `VICTORY_FRAMETIME_DUMP`, `VICTORY_AUTO_A`, + `VICTORY_GPU_SPANS`, the `stall:` watchdog, the `passswitch`/`gfxswitch` lines, "submission preparing per frame" and + "frame activity" lines exist neither in the source tree (`git log --all -S` finds none) nor in the strings of + `target\release\victory.exe` or `Extracted\victory.exe`. The launcher that sets them is the sibling project + `C:\Users\mathe\orca\workspaces\AnyXboxX\squirrelfish` (`--auto-a`, `--frametime-dump`, `--override KEY=VALUE`). + - Dataset B, 5 logs `%LOCALAPPDATA%\victory\logs\play-20261127-*.log` (Nov 27, 06:30 to 06:57 local), from the + `victory play` build of this lineage. No CSV; only the frame-rate line every ~5 s and the in-tree per-frame lines. + Tail figures (P99, 1% low, stall windows) therefore cannot be computed for B; its "P99" is the P99 of 5 s averages. +- Hardware (CSV headers of dataset A; Streamline lines of B agree on the GPU): AMD Ryzen 7 5700X (16 logical), NVIDIA + GeForce RTX 4070 12 GB, driver 621.01, 32 GB RAM, Windows 11 25H2 (build 26200), window 1707x1067. This is **not** the + machine of `docs/findings.md` (i9-12900K, RX 7900 XTX); its numbers are not comparable. +- The game dump is `C:\Users\mathe\Downloads\GTA 6\Extracted` (`game_scarlett_master.exe`). +- Labels the files do give: console profile (`# console=` line / log `console` line), DLSS mode and frame-gen (B only, + from the switch list), the first-window switch list (`# switches:` in the CSV, which lists only variables set in the + environment), shader-translation cache hits/misses (log), and ablations switched while running (A only, `passswitch` + lines). What they do **not** give: cold/warm for the driver's pipeline cache (D3DSCache), which route was played, when A + was pressed, whether `victory-settings.txt` (F1 menu choices, applied over the launcher at every start) held overrides. + +## Definitions used + +| term | meaning | +|---|---| +| window | one CSV row (~1 s) or one log frame line (~5 s in B) | +| heavy scene | windows whose mean draws/frame is 1000 or more. Boot and menus sit at 0-13 draws; the title's loading screen at about 300 in some runs. "World entry" = three such windows in a row | +| frame time percentiles (A) | reconstructed per window from its mean and its **max** (one frame at the max, the rest at the remaining mean): exact in frame count, total time and max, a model in between. P99 and "1% low" (= 1000 / P99 ms) are therefore indicative | +| stall window (A) | a window whose slowest frame is at least max(200 ms, 3 x the span's median ms/frame). The stalled time sums the maxima, a lower bound | +| watchdog stall (A) | `stall: the frame has not advanced` lines (first fires at 400 ms), grouped by frame number; length = largest `stalled_ms`; cause = the `inside:` text | +| stabilised | first window at least 30 s after world entry whose next 10 windows are all within +-25 % of the second-half median of the heavy windows | +| per-subsystem ms | summed over all threads (they can exceed the frame time); mean over the log lines at or after world entry | + +## Dataset A, 46 runs: where a frame goes (medians over runs; min-max in brackets; n = runs that have the figure) + +36 of the 46 runs reached the heavy scene (the others were quit in boot or loading). + +| metric | median | range | n | source | +|---|---|---|---|---| +| heavy scene, mean fps | 6.25 | 1.7 - 18.3 | 36 | CSV `frames`, `ms_per_frame` | +| heavy scene, median frame ms | 122 | 49 - 480 | 36 | CSV (reconstructed) | +| heavy scene, P90 frame ms | 219 | 63 - 1107 | 36 | CSV (reconstructed) | +| heavy scene, P99 frame ms | 833 | 116 - 1744 | 36 | CSV (reconstructed) | +| heavy scene, 1% low fps (1000/P99) | 1.2 | 0.6 - 8.6 | 36 | CSV (reconstructed) | +| heavy scene, stall windows per run | 35 | 0 - 142 | 36 | CSV `frame_ms_max` | +| session length | 322 s | 66 - 857 s | 46 | CSV | +| seconds from log start to heavy scene | 137 | 64 - 324 | 34 | CSV `draws` (includes the wait for A and the title's loading) | +| seconds from entry to "stabilised" | 76 | 30 - 433 | 27 | CSV; 9 of 36 heavy runs never met the rule | +| seconds until `making` (pipelines being made) reaches 0 for good | 43 | 28 - 685 | 46 | CSV `making` | +| CPU prepare ms/frame (the "preparing" figure) | 84 | 11 - 181 | 36 | CSV `cpu_prepare_ms` | +| draws per frame | 4331 | 1085 - 5808 | 36 | CSV `draws` | +| title copies MB/frame | 159 | 4.7 - 268 | 36 | CSV `copies_mb` | +| textures MB/frame | 14.6 | 0 - 156 | 36 | CSV `textures_mb` | +| copy-back MB/frame | 40.6 | 0 - 50.8 | 36 | CSV `copyback_mb` | +| card sent-up MB/frame | 57.3 | 7.3 - 103 | 36 | CSV `card_sent_mb` | +| card fetched MB/frame | 61.4 | 0 - 101 | 36 | CSV `card_fetched_mb` | +| RAM max (process, MB) | 20692 | 14008 - 24108 | 36 | CSV `ram_mb` | +| submissions per presented frame | 25.8 | 2.6 - 29.7 | 46 | log `frame activity` counters | +| descriptor slots looked at per frame | 205,872 | 7,028 - 406,781 | 40 | log `descriptor records ...` | +| descriptor slots mirrored per frame | 9,238 | 352 - 34,410 | 40 | same | +| card busy % ("by this count") | 41 | 4.7 - 67 | 46 | log `the card's clock per frame` | +| card title-list time ms/frame (GPU timestamps) | 32.3 | 2.1 - 231 | 42 | log `gpuspan` | +| prep: before the steps (write watch etc.) ms | 12.7 | 0 - 38 | 46 | log `submission preparing` | +| prep: card copies ms | 16.4 | 0 - 126 | 46 | same | +| relay ms (thread sum) | 37.0 | 0.2 - 111 | 46 | log `frame activity` | +| present ms (thread sum, includes waits) | 21.8 | 1.9 - 114 | 46 | same | +| watchdog stalls per run | 31.5 | 8 - 136 | 46 | log `stall:` | +| watchdog stalled ms per run | 34,020 | 7,656 - 75,587 | 46 | same | + +Notes on these figures: + +- `gpu_ms` / `gpu_pct` in the CSV are near zero in every run (median 0.13 ms, 0.07 %), while the log says the card was + 41 % busy by count and 32 ms of title lists ran per frame. The CSV GPU columns are **not usable**; use the log lines. +- GPU is not the limit in the last run: its heavy-scene mean of the log's "card idle" figure is 154 ms per frame against a + 193.8 ms mean frame (`the card's clock per frame` line, run `20261126-211141`). The pattern (CPU-side noticing and moving memory) matches + `docs/performance/ROOT_CAUSES.md`. +- Thread-summed subsystem times do not add to the frame; use them to rank, not to subtract. +- Different eras of the day differ more than run noise (heavy-scene mean fps, from `index.md`): 12:37-14:56 runs 5.2-7.6, + 15:33-17:22 runs 3.0-3.8, 17:53-18:32 runs 6.1-7.5. Code changed during the day and the build is not recorded, so the + cause is unknown. +- Late runs have ablations on (`passswitch` lines): 20:11-21:11 runs switch passes such as `buffer_refresh`, + `heap_textures`, `texture_refresh`, `descriptors`, `heap_buffers` off from the F1 menu. The run's final state is the + `passes off at end` column in `index.md`. Two runs finished with everything on: `20261126-201209-588-...` (heavy 9.6 fps, + only 22 heavy windows) and `20261126-210725-018-...` (6.8 fps, 35 heavy windows). + +### Stall causes (watchdog, summed over the 46 runs) + +| inside (what the threads stood in) | stalls | total ms | +|---|---|---| +| no section of ours (the title or the system is the wait) | 1096 | 739,697 | +| heap pass: buffers + mirror loop | 36 | 324,434 | +| heap pass: buffers + mirror loop + descriptor heap sync | 14 | 124,222 | +| relay: landing flights | 289 | 117,868 | +| flush of refreshes | 90 | 86,148 | +| present | 79 | 70,504 | +| settle (wait for the card) + write-watch dependencies | 2 | 38,107 | +| card copies (card_before) | 26 | 17,789 | + +Of the "no section of ours" stalls, the watchdog's own text says the title or the system is waiting; nothing in the log +says on what (file, pipeline creation, DirectStorage). The 5-8 s heap-pass stalls are a single bad frame each. + +### One latest run in full (`20261126-211141-508-15168-6d931aa6`, series-x, no DLSS, passes off at end: heap_textures, buffer_refresh, texture_refresh) + +| span | fps | ms mean | ms median | P90 | P99 | worst | +|---|---|---|---|---|---|---| +| whole session, 322 s | 11.5 | 87.0 | 68.2 | 187 | 280 | 6790 | +| heavy scene, 110 s | 5.16 | 193.8 | 189.3 | 209 | 280 | 724 | +| entry + 30 s onward, 79 s | 5.35 | 187.0 | 186.0 | 197 | 213 | 240 | + +Time to heavy scene 214 s, stabilised 31 s after entry. CPU prepare 180.9 ms/frame, 27 submissions/frame, 2797 draws/frame. +Do **not** use this run as "the baseline": three core passes were off, which changes what it measures. + +## Dataset B, 5 sessions of Nov 27 (`play-*.log`, frame line every ~5 s, rendered fps) + +| log | profile | DLSS | frame-gen | shader cache | heavy windows | heavy fps | heavy ms mean | P99 of 5 s means | s to heavy | warn lines | +|---|---|---|---|---|---|---|---|---|---|---| +| play-20261127-093037-23504 | series-x, native 1440p | quality | off (ready) | cold (2717 translated) | 77 | 12.35 | 81.0 | 314.9 | 69.5 | 414 | +| play-20261127-093851-14116 | series-x, native 1440p | quality | off (ready) | warm (1 miss) | 33 | 8.48 | 117.9 | 380.3 | 70.9 | 392 | +| play-20261127-094254-19348 | series-s | balanced | x2 | warm (5 misses) | 26 | 7.97 | 125.5 | 529.6 | 50.4 | 335 | +| play-20261127-094655-17644 | series-s | balanced | x2 | warm (0 misses) | 44 | 16.76 | 59.7 | 125.8 | 141.9 | 319 | +| play-20261127-095317-11396 | series-x, native 1440p | balanced | x2 | warm (0 misses) | 50 | 8.25 | 121.2 | 594.1 | 87.9 | 259 | + +Frame-line means from world entry (same logs): GPU ms/frame 12-21, copies 35-48 MB/frame, textures 25-43 MB/frame, +copy-back 0.4-0.8 MB/frame, draws 3109-6062/frame, dropped draws 440-763/frame, card busy 48-79 % by count. +Only the series-s run 094655 got above 15 fps heavy. `fps` here is rendered fps (the panel multiplies by the frame-gen +factor). The cold-cache log (093037) ran 12.35 fps heavy and still needed 129 s after entry to stabilise, so a cold +shader-translation cache is not what dominated it; the driver pipeline cache state is unknown for all five. + +## What can and cannot be claimed from this + +- Heavy-scene frame time on this PC is 100-200 ms (5-10 fps) in the typical run, with a median P99 of 833 ms (range + 116-1744 ms) across runs; the in-world frame is CPU/submission-bound (card idle about four fifths of the frame in the latest run). +- World entry to steady frame rate takes about 30-430 s (median 76 s, 27 runs), consistent with "late loading after + world entry" in `ROOT_CAUSES.md`; the first ~64-324 s of each session is boot, menu and the title's own loading. +- Run-to-run spread is wider than any single optimisation is expected to give. Any A/B needs the protocol in + `docs/performance/AGENT_REPORTS/07-profiling.md`, section 5: same scenario, at least 3 interleaved runs per + arm, compare medians, and treat differences under about 5 % as noise (`docs/findings.md`). diff --git a/docs/performance/EXPERIMENTS.md b/docs/performance/EXPERIMENTS.md new file mode 100644 index 000000000..8b7711133 --- /dev/null +++ b/docs/performance/EXPERIMENTS.md @@ -0,0 +1,421 @@ +# Performance experiments + +## perf/pipeline-order: early queue by first use, loading boost, make-time log (UNMEASURED IN-GAME) + +Status: implemented, builds, unit tests pass. **Not run in the game. No frame-time or load-time result exists yet.** Opportunity #2 of `AGENT_REPORTS/04-shader-pipeline.md` plus item 4 (instrumentation). Touches `pipeline/{make,library}.rs` only; victory-shader and the static-sampler library bypass are unchanged (no translator hash change, no cold start). + +What changed +- New `pipeline-order.txt` (cache folder): `key ms` per line, first-used first; line number is the rank. Written with the library/early-list save. `early-pipelines.txt` and `slow-pipelines.txt` keep their formats (the early file is now written in first-use order, still readable as a set by older builds). A missing file means no order (creation order, as before). +- EARLY and slow queues are binary heaps by recorded rank; unranked pipelines go last in creation order. `VICTORY_PIPELINE_ORDER=0` restores FIFO. +- Boost: when 32 or more pipelines wait, workers (not the screen workers) go from LOWEST to BELOW_NORMAL (`VICTORY_PIPELINE_BOOST=normal` for NORMAL, `0` to disable) and the slow cap (workers/4) rises to workers-1. Cleared when the queue drains ("all made"). +- Release log: `host pipelines {loaded from the library | made | made, static samplers (never in the library)}` with count, p50/p90/p99/max ms, total_s. Emitted at "all made" and at most once a minute with saves. The static-sampler line answers whether the driver cache makes those compiles quick. + +How to measure (to do) +1. Run once to write `pipeline-order.txt` (the first run only records; ordering applies from the second). +2. Short-loading start, compare frames over 200 ms after world entry and `mk` at world entry against run 095317 (250-340 ms frames for ~2.5 min). +3. Read the new `made, static samplers` p50/p99 lines. p50 in the low ms means the driver cache hits. +4. A/B `VICTORY_PIPELINE_BOOST=0` and `VICTORY_PIPELINE_ORDER=0`. + +Risks: BELOW_NORMAL workers may take CPU from the title's loading threads (unmeasured); a worker keeps its priority until its current pipeline ends; with the cap lifted all but one worker can sit in 10-58 s compiles. +# Experiments log + +Status words: MEASURED (in-game numbers), UNMEASURED (built and unit-tested, not run in-game), NOT DONE (reason given). + +## perf/descriptor-sync: report 03 item C (gate and coalesce heap rounds, skip ring pages) + +### Step 0: counters (UNMEASURED in-game) +Added, logged with the existing "descriptor records ..." frame line (`descriptor.rs` `sync_line`): +- "the heaps' records, rounds per frame": rounds run, rounds with no changed page, kernel write-watch asks + (`Tracked::take`, one per heap per round), ms in asks that found nothing vs found pages (E4, as far as + `descriptor.rs` can see: the kernel call and the journal work inside `watch::writes` are not separable + without editing `watch.rs`, which this branch does not touch), ring pages (more than 90% of the changed + records on the page were "of draws' tables"), MB read on them, records changed on them (E5). +- "view creation per frame": buffer views and raw twins created in `buffer_srv` with their time in + `CreateShaderResourceView` (E2; `VICTORY_DESCRIPTOR_TIMING=0` counts without timing; clock read about 25 ns + twice per view, so about 1 ms thread time a frame at 17k twins; unmeasured). +- E1 (switch gating the heap buffer pass) and E3 (picked bitmap) need `draw.rs` / shader emit: not done here. +What to read: ring MB vs total MB read ("MB read" in the records line) says how much of the 16.5-17.8 MB a frame +step 1 could skip; "no changed page" rounds say how many of the 17 rounds a frame are pure overhead. + +### Step 1, skip ring pages: NOT DONE (not behaviour-preserving without the picked bitmap) +A new record on a ring page that no draw has read yet is indistinguishable from one a shader will pick by +computed index; `copied_tabled` is only stamped after a draw reads the slot, i.e. after the round that would +have mirrored it. Skipping the page's read/compare leaves a bindless-picked slot with a stale or null host +descriptor, which violates R4 (a slot must not show a texture that is not uploaded, or freed memory; +ARCHITECTURE_AUDIT.md 2.1). The report itself lists this as the medium-risk step and makes it depend on +opportunity A (GPU-written picked bitmap) or a periodic sweep, and a sweep changes when picked slots update, +which is not provably identical. Needs the in-game ring-page counter above first. + +### Step 2, rounds only for submissions with pick-by-index draws: NOT DONE (needs draw.rs) +The signal ("a list recorded a draw whose shader has SLOT_STRIDES / SLOT_TABLE_STRIDES, or uses `lent_heap`") +exists only in `draw.rs` (`heap_buffers`, `heap_strides`, around draw.rs:2046-2080, and 1878). Setting a flag +there is out of this branch's scope. Without it, gating on anything else (frame, page counts) would skip +rounds that other readers need: draws read their tables directly, but compute and `lent_heap` dispatches +read heap slots by index, and a descriptor the title copies after its last API call is mirrored only by a +round. Suggested follow-up: a `crate::heap_marks::note_pick()` thread-local set from `heap_buffers`, +`heap_strides` and the lent-heap path, read by `host.rs submit` to choose `begin_sync_heaps_after(mark)` or +reuse the previous round (dirty ranges accumulate in `Tracked::seen`, so one later round still sees all +writes). Keep the invariant that a round is never skipped for a submission whose lists have the flag. + +### Step 3, coalesce write-watch asks: NOT DONE (would corrupt shared journal state) +The existing coalescing tool, `watch::ask_ahead`, writes the global journal's `ahead` set and +`ask_ahead_done` clears it. That state belongs to the submitting thread's refresh groups; the heap-sync +thread runs concurrently and would clobber it (and `journal().kept` makes it a no-op while a submission's +`ask_once` stands). A coalesced ask across both heaps needs a new entry in `watch.rs` (and a flat per-page +`seen` instead of the `BTreeMap` mutex), which is out of scope. Expected gain is also small: a round is +one kernel call per heap (usually one or two shader-visible heaps), not one per page. + +### Invariants kept +No behaviour changed: descriptor slots, dynamic-slot release on GPU completion and upload-before-show are +untouched; only atomics and clock reads were added. + +## Branch perf/memory-footprint (report 02: measurement, R4, R3) + +All three items are UNMEASURED in-game. Build: `cargo build --release -p victory` ok; `cargo test -p victory-gpu` +415 pass, 2 fail (`indirect::tests::host_list_budget_starts_empty_at_each_submission`, `warp_batch_charges_every_execution`), +both fail identically on the base branch. + +### 1. Footprint counters (measurement only) - `copystat_footprint.rs` +Per host copy, distinct 64 KiB blocks (since the copy was made): written by shaders (bytes that landed in title +memory: `land_card` / `land_back`, merged > 0), changed by the title's CPU after shaders had written them +(`Shadow::take` runs, `take_landed` non-echo, `copy`), and written by the title while pending +(`merge_under_writes` runs). Logged every ~10 s from the frame-line block in `host.rs` (not diagnostics-gated): +one total line and the top 8 copies. `VICTORY_FOOTPRINT=0` turns it off. Cost: one global mutex per event +(hundreds per frame), 1 bit per block. +Read it for: shader-written % of the 174 MB heap's 2,784 blocks (report 02 R1 decision: under ~20 % means a learned +footprint pays), and `pending title` vs `also shaders'` (pending-and-never-shader blocks are the false sharing behind +the 9.6 ms of merge-under-writes). +Caveats: "then title" is an upper bound where a refresh copies whole pages (`copy()`), and for copies in PC memory a +landing's own write shows as a title write (the card path filters those with the echo compare, the PC path does not). + +### 2. R4, batched write-watch ask: mostly already there; one small change +Per-submission batching exists and is on by default (`VICTORY_ASK_ONCE`: `watch::ask_once` -> `ask_ahead` merges +ranges within 8 MiB, `ask_rest` takes what is left). Report 02's many asks therefore come from asks that miss the +standing journal (after `ask_once_end`, `merge_under_writes` -> `writes`, flights' late merges), not from the +submission's own refresh groups. Done: `ask_rest` sorts ranges by start, widest first, so a range contained in one +just asked is answered by it (before, refresh order could ask the small range and then the big one holding it). +Same pages found, same journal, never more kernel calls than before. Expected gain: small, unmeasured. +Not done: one ask per region per FRAME. A title write between two submissions of a frame would then be seen a frame +late by the later submission's refresh (stale bytes on the card), which breaks "title writes reach the copy before +the submission that reads them". A real gain needs the miss counts first (diagnostics build: `copystat` watches per +frame, split by caller). + +### 3. R3, per-copy write epoch so `defer_refresh` is one compare: NOT DONE +`defer_refresh` only records a `Step::Refresh` (which also keeps the copy alive until the list is reset); the work +(`nothing_new`, `update`) runs at submission. Skipping the step at record time on an epoch compare would read the +copy's state before the title's later writes in the same frame: a write between recording and submission would be +missed (audit invariant R2). Doing the compare at submission instead needs a per-copy epoch bumped on every journal +`note()` for pages of that copy, i.e. a page -> copy map on the fault/ask path (`watch.rs on_write`, `Journal::note`); +a global epoch is useless since the title writes every frame. That is a new structure on the hottest path and needs +the step 1 counters and a diagnostics run first. + +## perf/submit-thread: R8 sweep without drain, R3 joined card-step copies (UNMEASURED IN-GAME), R3 gather and R7 not done + +Status: implemented, `cargo test -p victory-gpu` passes except the 2 known indirect failures. **Not run in the game.** + +R8 (`host.rs`, submit's sweep): the forced `settle(WHY_SYNC)` every 1.5 s behind flights is gone. The sweep only drops what no list or slot names (`strong_count == 1`, COM refcount 1) and does it through `retire()`, which holds objects until every submission started so far has finished (submission numbers are the fence values; `bury_lag` adds 16/64 on top). A flight's lists keep their objects counted until landed. `VICTORY_SWEEP_SETTLE=1` restores the drain (also kept when the up-check is on). Measure: the 10-30 ms spike every 1.5 s in frame times, and `a synchronous submission or present` in the late line. Risk: a missed holder is a freed-memory fault (device loss); soak with `SLOT_CHECK`. + +R3 (`card_steps.rs::record`): not a gather kernel. Reading the code shows the report's premise is too high: a fill that goes to a descriptor slot (`To::Slot`, stage 1) records no command at all; reads are deduplicated per place (a few hundred, "2,800 fills of a few hundred places"), only copies and stage-2 buffer fills write. With `VICTORY_FILL_TITLE` on by default the small ring fills are mostly no longer taken here. The 4.6-8.6 ms "planning" is CPU planning (`does_of`, `plan`, `holder`, `mapped` page-table probes, 5.4k `constant_slot` writes), which a kernel would not touch. A real gather also needs a new PSO, a mapped upload table per `Own`, and a per-source/per-destination state scheme (NON_PIXEL_SHADER_RESOURCE/UAV instead of COPY_SOURCE/DEST, with the "both" case), and the scatter kernel in `send.rs` is one destination UAV per dispatch, so it is not reusable as is. Not done until a capture shows the command count. Done instead: runs touching in both buffers (reads may cross equal under-256-byte padding) go in one `CopyBufferRegion`; `VICTORY_JOIN_STEPS=0` restores one each. Measure with `--timing detailed` on the card-steps list. + +R7 not done. Present cannot simply move: the next `present_planes` reads `GetCurrentBackBufferIndex` and records into that buffer, so it must come after the previous `Present` call, which makes the move a hand-off with a wait; Streamline's `present_begins/called/returned/ends` and the tags belong to one thread per frame (frame-gen semantics); and the resize path settles and calls `ResizeBuffers` under the presenter lock. What would be left to overlap is ~1.5 ms/frame (`Present`) plus `panel/menu/meter.frame`, which are bookkeeping (a once-a-second log). Not worth the ordering risk without an in-game Streamline test. + +## perf/read-wait: unnamed "title memory read" settles (UNMEASURED, NOT COMPILED) + +Status: written and read through only; the user compiles. Log play-20261127-101425-23388.log (VICTORY_CARD_STEPS=2, relay on): 0.5 settles/frame for WHY_READ, ~30 ms each, while the three named counters (copy, fill, texture) are 0. So the wait comes from a `Some(WHY_READ)` that is not counted: `place::read_by` (host.rs, end of `blocked_by`) or `card_steps::copied_read` (`late_blocked`). `asked_sizes` (host.rs send_late) is off unless `VICTORY_BVH_SIZES_WAIT=1`. Both waits end in `relay_wait` until `line.written` no longer touches the read, and `written` includes the title's 174 MB heap while a skinning flight is in the air, so the wait drains those flights (tens of ms). + +Change 1 (counters): the frame line now names two more sources inside "title memory read": `a step that reads where a copy at its place writes` (LATE_STATS 18) and `a refresh or host read of where a copy done on the card writes` (19). Read the next log to see which dominates. + +Change 2 (fix for the first): `place::read_by` asked whether ANY step of the submission reads the destination of a copy at its place whose flights are in the air, wherever the step stands. Submission runs steps in list order (`run_deferred`), and a copy at its place is not put into title memory when flights may write it (`Placed::prepare(free=false)`). A step that stands before the copy reads the old bytes with or without the wait, so waiting for it changes nothing. `blocked_by` now checks each step against the destinations of the copies at their place ahead of it only (`place::reads`). Invariants kept: a reader behind the copy still waits; the readers' own source checks against `written` are unchanged. + +Not changed: `copied_read`. A refresh of another host copy over a card-copy destination really needs the landed bytes (the draw reads that host copy), so the wait is correct until the copy also writes that other host copy or the refresh is given a card-side order; that needs the landing to be ordered on the queue and is a larger change. If the next log shows counter 19 dominating, that is the next work item. +## perf/tight-writes: learned footprint for root UAV declarations (UNCOMPILED, UNMEASURED; default OFF) + +`VICTORY_TIGHT_WRITES=1` enables `tight.rs`. Root UAVs (`Draw::root_uav`) have no size; they declared the rest of the +title's buffer as shader-written. Now, per (pipeline, root parameter), the footprint relative to the root address is +learned from what lands (hook in `copystat_footprint::gpu_wrote`, which `land_card`/`land_back` already call). Learn: +full declaration, noted per copy for 400 ms, landings inside widen the footprint. After 8 landings and 32 +declarations: tight, footprint +-256 KiB in 64 KiB blocks. Tight keys declare the footprint only, except every 16th +declaration (`VICTORY_TIGHT_VERIFY`) which is full and noted; a landing outside the footprint in a noted full +declaration makes the key wide for good (warn log). Keys that never saw a landing never tighten. +Not done: table UAV views in `readable` (sized, no pipeline identity there), persistence across runs, static shader +analysis. The view and `refresh` stay wide; only `gpu_writes` is narrowed. +Why default OFF: a write outside the footprint between two verifications is not declared, so it stays on the card +until the next declared write of its 64 KiB or verification; that violates "must reach title memory before the title +is told" for that frame. An exact fallback needs a card-side whole-range compare declared as compare-and-land (host.rs +card steps, not touched here) or a shader-side bounds flag. Attribution is a superset (any noted declaration of the +copy overlapping a landing), so errors widen, never narrow. Measure: log of `footprint of 64 KiB blocks`, and +shadow/flight lines with the switch on vs off. Code was not compiled or tested (instruction); unit tests in tight.rs. + +## perf/prewarm-pipelines: earlier runs' pipelines made from process start, not at the title's creation (NOT COMPILED, UNMEASURED) + +Status: written by reading only; **not compiled, not run**. Targets root cause 2 of `ROOT_CAUSES.md` (about 1,360 pipelines compiled after world entry) and the idle loading screen (~30 s of static images in which nothing was prepared). Based on `perf/radical-refactor`; builds on the pipeline-order entry above. victory-shader untouched (translator hash unchanged, no cold start). + +What changed +- `known::prewarm()` (called from `apps/victory/src/run.rs` right after `use_shader_cache`, only with `--execute`, so not by `victory warm`/`translate`): a thread reads `pipeline-order.txt` + `early-pipelines.txt` (`library::plan()`, first-use order), looks each key up in `known-pipelines.bin`/`known-shaders.bin`, rebuilds the `Pending` (same key, checked) and queues it as EARLY on the existing workers (translation, library load or compile, `note_time`). It runs before the title image is even loaded, so the menu and the loading screen are the time used. First run (no order/early file or no book): logs "nothing recorded" and does nothing. +- `make::adopt` (one line in `pipeline.rs::hand_out`): the title's CreatePipelineState gets the prewarmed `Arc<Pending>` for its key (made, or in the queue; a draw promotes it to REQUESTED as before). This matters for the static-sampler pipelines (54%, never in the library): they were recompiled every run, and a made `HostPipeline` is now kept and handed out instead of thrown away. If the title creates one first, its own is used and the prewarm skips the key. +- `LOADING` phase from the prewarm's start: workers other than worker 0 at NORMAL priority (usual: LOWEST), known-slow cap raised from workers/4 to workers-1, and the early and slow heaps are drained together in first-use order (slow ones were behind all others). The loader counts as one waiting pipeline so "all made" does not fire between its entries. +- Loading over (priority back to usual, one log line): a world's frame (300 or more draws and dispatches, twice in a row; menu and loading screens draw 1 to 11) or everything queued made, or nothing to make. Constants only, no env switches added (existing ones still apply: `VICTORY_PIPELINE_ORDER=0`, `VICTORY_PIPELINE_SLOW=0`, `VICTORY_PIPELINE_WORKERS`). +- `victory warm --used` now makes the pipelines in first-use order too (reads `pipeline-order.txt`). + +What to look for in the log (release) +- `pipeline prewarm: pipelines of earlier runs queued, first used first` : planned / queued / not_in_the_books / unreadable / key_changed (must be 0: the rebuilt key differs from the recorded one) / created_by_the_title_first / ms. +- `pipeline prewarm: loading over ...` : why ("the title draws a world", "everything queued is made", "nothing to make ahead"), seconds, made, found_by_the_title (hand-outs that found a prewarmed one), asked_before_made (draws that asked before it was made: the remaining stall), waiting. +- At world entry: `waiting`/`mk` near 0, the existing `host pipelines made` lines (count made after entry vs the 1,360 baseline), frames over 200 ms after entry, `a pass over the screen was waited for`. +- How to test: run twice (the first only records; needs `VICTORY_PIPELINE_BOOK=1`, set by `play.rs`); compare the second against run 095317 (250-340 ms frames for ~2.5 min). A/B a changed translator (cold driver cache) to see how much of the compile fits in the loading screen. + +Risks +- Normal-priority workers compete with the title's loading threads (unmeasured); a worker keeps its priority until its current pipeline ends (up to 58 s for the worst). +- The host D3D12 device is created on the prewarm thread at process start (after Streamline init, before the title's device creation); the title's `D3D12XboxCreateDevice` finds it. If something in the title's device setup must precede `host()`, this is where it shows (not found by reading). +- Two title pipelines with one key now share one `Pending` (and `host` Arc); builder pipelines may be listed twice in `BUILDER.pipelines`. Prewarmed pipelines the title never creates stay alive (bounded by the recorded set, about 5,500). +- Compiler crash/hang now costs the process, not a child; but these are the same pipelines the title queued at creation before, so no new class of crash. +- The world threshold (300 draws) is a guess from report 05's numbers; if a menu draws more, loading ends early and the prewarm continues at the usual low priority. +## perf/texture-book: textures delivered as the title's DirectStorage requests land (UNCOMPILED, UNMEASURED; on by default) + +Problem (report 05): the texture queue is empty for the ~95 s loading screen, then 26k slots / 82k textures / 5 GB are +made, detiled and uploaded on the frame-recording thread at 4-13 fps for ~3 min. + +Principle: watch what the title requests and deliver it translated, in real time; nothing the title did not ask for. + +1. Live, request-driven (`texture/ledger.rs`, re-exported as `victory_gpu::texture_book`). `dstorage.rs::work` calls + `landed` after every successful request: the destination address (a plain address, or for page destinations the one + run of title addresses `xmem::shown_at` returns for the written pages) and the request key go to + `request_done`. If the description of the texture at that address is known and the request covers its bytes, the + "texture book" thread (after 120 ms, and only if no other request overwrote that memory since) checks card room + (`resource::room`), host commit (`admit_texture_pass`) and that the memory is mapped, makes the placed resource + (`resource::texture_at`) and hands the upload to `texture/ahead.rs` (copy queue, detile on its workers). When the + title later names the slot, `texture::unchanged` finds the host copy holding exactly the memory's bytes and the pass + adopts it with no upload (outcome SAME; `adopted_by_slots` in the book line). + Which case holds for the metadata (evidence): the streamed textures are views of memory without a resource object. + Their description arrives only with the descriptor write: `descriptor.rs:1659 create_placed_srv` (device 0x230, + `device.rs:457`) records `View::Placed(false, resource_desc, view_desc)`; `resource.rs:3269 texture_at` makes the + resource lazily "the first time a draw reads one". Only `resource.rs:3129 create_at_address` (device 0x428) gives a + description at creation, for resources the title makes as objects. So at request completion the format/size/mips/ + tiling are usually NOT known yet on the first fill of an address; they are known when (a) a view named that address + earlier in the run (`ledger::desc_known` from `texture_at`, `ledger::named` from the pass), which is the common case + for memory the title streams out and back in, or (b) the book on disk recorded that this very request (file, offset, + sizes, options) filled a texture a slot named and kept, in an earlier run. (b) only fills in metadata for a request + the title has just made; it never starts a load. Without either, nothing is done for that request. +2. Book on disk: `<cache>/textures/book.bin` ("VTB2", run number, entries of request key -> 14 resource words, first + level, use count, last run). An entry is written only when a slot named the texture whole and resident; entries whose + memory was seen overwritten by another request or streamed out (and not named again) are dropped at save; entries + unused for 6 runs age out; at most 150,000, most used first. Saved every 30 s by a thread once 256 textures were + named in the session. Offsets, hashes and layout words only (asset policy). +3. Converted-asset cache, write-through (`texture/converted.rs`, `victory_gpu::converted_cache`): in + `dstorage.rs::execute`, a BCPack request (or zlib from 1 MiB) from a file with an output of 64 KiB or more is looked + up by key; the entry is checked against a digest of the source bytes read (so a changed pack misses); a hit is read + straight into the destination (no zlib, no BCPack); a miss decodes as before and queues the output to a writer + thread (at most 512 MB waiting). Disk bound 24 GiB, trimmed to 90 % by least recent use (file time, touched on each + hit). Folder `<cache>/textures/converted/<xx>/<hex>`, beside the shader cache (`d3d12x::use_shader_cache` sets it + from the checked cache root), never in the repo or game folder. + Entry format: `"VCV1"`, u32 version 1, u64 file (FNV-1a of the lower-cased opened path), u64 offset, u32 source + size, u32 destination size, u64 options, u128 source digest (`texture::digest`), u64 output bytes, then the bytes + exactly as written to the destination. File name: 32 hex digits of `texture::digest` over the 32 key bytes. + What is cached is the decoded (still tiled) output, not the detiled texture: the detile now runs on the copy-queue + workers off the frame thread, and reading a detiled file is not cheaper than detiling RAM-resident memory; the + decode is what costs. +4. Loading gate from the request stream: `ledger::tick` (from the pass and from finished requests, twice a second): + requests completing (>= 4 or >= 4 MB in the half second, or a `.rpf` opened in the last 8 s) while under 200 draws a + frame (or no frame) -> loading, held 3 s after the last sign. While loading the pass gets 4x bytes and a slice of + at least 120 ms; the copy queue may have half of free RAM in flight (a third otherwise). +5. Budgets from the real working set: `residency::textures_limited_by_ram` (< 24 GB installed) replaces + `limited_host_ram` (<= 32 GB) for the texture pass byte cap and prefetch limit, so a 32 GB machine is no longer + capped at 128 MB/frame and 32 MB in flight. `residency::staging_ceiling`: uploads in flight = free RAM / 3 (/ 2 while + loading), 96 MB to 6 GiB; 32 MB on < 24 GB machines, <= 64 MB under pressure. Ahead workers: cores/4, 2 to 4; + batch 32 MB / 128 textures. VRAM line: the launcher no longer sets `VICTORY_TEXTURE_ROOM_PERCENT` 80/86; + `resource::room_line` uses constants: 88 % of the budget with frame generation on, 90 % ready but off, + `line_for` (>= 90 %) without it; the render-target reserve (`targets_room_kept`) is unchanged on top. +6. Rechecks in time: `RECHECK_MS = [200, 600, 2000, 6000, 20000]`; the wait is the shorter of the frame count and the + time at the measured frame rate (so 400 frames at 5 fps is 100 frames, 20 s). + +Not done: moving the per-slot pass itself off the recording thread (the make-ready work and detiles now are); an +overlay. No env switches added. Log lines to check: +- `texture book: read what earlier runs kept` (entries, run) at start; +- `texture book: loading screen seen in the request stream; staging budgets raised` / `... is over` (seconds); +- every 5 s `texture book: the title's requests since the start`: `requests_done`, `texture_known`, `made_ready`, + `adopted_by_slots` (the goal: most of `made_ready`), `unnamed_mb`, `no_room`, `no_host_ram`, `not_mapped`, + `not_taken`, `overwritten`; +- every 30 s `converted cache: since the start` (hits, hit_mb, stored, evicted, on_disk_mb) and once + `converted cache: decoded DirectStorage outputs kept on disk`; +- `textures uploaded ahead of the lists` (turned down count) and the queue line `textures picked by index, the queue` + (peak should drop well under 26k on the second run), time from `core_restofworld.rpf` open to queue < 500. + +### perf/read-wait, step 2: constants behind a copy at its place read on the card (NOT COMPILED, UNMEASURED) + +Measured with step 1 (play-20261127-104020-14256.log, chase): "title memory read 0.8", all of it "a step that reads where a copy at its place writes", 18.6 ms/frame waiting. The readers really stand behind the copy. Most likely they are constant-buffer fills: the ring copy of a few hundred bytes a frame, then draws whose constants read it (`draw.rs` table CBVs -> `defer_constants`, misaligned root CBVs -> `fill_scratch`). With the copy's source or destination under flights' declared writes, `Placed::prepare(free=false)` leaves title memory alone, so a CPU fill behind it would read old bytes and must wait. + +Change (`host/place.rs`, `host.rs`): `place_copy` notes its destination (this frame and the one before). `defer_constants` and `fill_scratch` check whether the constants overlap a noted destination. If they do, `HostList::placed_constants` records at this place in the list a refresh of the range, then a copy out of the host copy that shaders write into a 256-aligned piece of a per-list buffer of ours (1 MiB, then readable as constants). It does not record a CPU fill. A root view gets that address. A table slot is pointed at it when the list is submitted (a host step, `PointSlot`), after the draw pointed it at upload memory. The read is now in queue order, after the copy and every flight ahead of it, so no step reads the destination on the CPU and `blocked_by` has nothing to wait for. The value is the card's: what the copy and every write ahead of it left there. That is the same thing every buffer view and aligned root CBV of the heap reads already. Title memory is not written; the landing is unchanged. + +Counter: "N constants read on the card behind them" on the line "title buffer copies at their place". Watch "a step that reads where a copy at its place writes" (should fall to ~0) and "title memory changed under shader writes" (WHY_STALE). The refresh of a range under declared writes can be settled there instead. + +Not covered: readers that are textures, title buffer copies done at submission, or host reads of the destination. They still wait, and the counter would stay above 0. + +## perf/coherence: refresh coherence at the root - asked-range lookup by halves, per-4 KiB part notes (NOT COMPILED, UNMEASURED) + +Status: written by reading only (instruction: no cargo). Files: `watch.rs`, `shadow.rs`, `copystat_footprint.rs`. No env switch added; nothing in `host.rs`, `draw.rs`, textures or pipelines touched. + +Evidence (logs 101425, 104020): "copies" 15-28 ms for 32-60 MB a frame in steady play; the 10:49 chase: refreshes 42.9 ms in 56 flushes of 12,800 spans, 10,977 known to copy nothing, "copies" 45.6 ms / 116 MB. + +Root causes found +1. Every question "is this range asked already?" walked the submission's asked ranges one by one (`Journal::ahead`, a Vec in ask order). `ask_rest` pushes one entry per copy span not covered by `ask_ahead`'s 8 MiB runs, so it holds hundreds to thousands of ranges, and it is walked by every `nothing_new` (12,800 a frame in the chase, on 6 threads under the journal's read lock), every `writes` (twice), every `asked`, and inside `ask_rest` itself (quadratic). The "known to copy nothing" spans were paying this, not the copy. +2. A host copy's notes (`Shadow::copied`) were per 64 KiB page and only set when a refresh held the whole page. A page held in part - at every gap beside a range flights declare written (`update` refreshes around `pending`), at range ends - kept the note of its last whole take; once the title wrote any 4 KiB of it, every later refresh of the gap took its parts again, written or not, until some refresh held it whole, which beside ranges flights keep declaring is never. `ranged` (two remembered ranges) hid this for at most two ranges per copy. The same held for `merge_under_writes` (`stale_pages_in` page-level, pages noted only if whole): pages beside the declared ranges were merged again every submission and counted as reasons to settle. + +Changes +- `watch.rs`: `ahead` is kept sorted and joined (`joined_pages`), looked up by halves (`covers`, O(log n)) in `writes`, `asked`, `nothing_new`, and `ask_rest` checks only the last joined run (ranges come sorted). Union semantics: every page of a joined range was asked under the standing number, so a range across two touching asked ranges is as asked as one inside either. +- `shadow.rs`: new `parts_taken` per copy (BTreeMap page index -> 16 stamps, locked inside `copied`). `stale_runs` (pure) decides what a refresh takes per 4 KiB part: a part's note is max(page note, part note, `ranged`), its write the journal's per-part write (`watch::part_writes`) or the page's. `stamp_taken` (pure) notes whole pages as before and, of pages held in part, each part held whole; a page all of whose parts are noted is promoted to the earliest. `copy_stale`, `nothing_new` (watch side), `stale_pages_in`/`stale_under_writes`/`merge_under_writes` use them. Without part notes the runs are exactly the old `by_parts` runs (test `runs_without_notes_of_parts_are_as_before`). +- Release log line every 10 s (from `copystat_footprint::log`): `refreshes that looked at title memory, per second: ..., MB never taken before, MB taken again ..., ends of ranges in the middle of a page ..., questions answered from the submissions' askings ..., ranges asked on average`. + +Not done, and why +- Skipping refresh spans at record time (per-copy epoch / page->copy map): a span recorded before a title write that lands before submission must still copy it (audit "title writes reach the copy before the submission that reads them"); a list may be submitted again without re-recording. The check has to run at submission, so it was made cheap there instead (cause 1). A page->copy map on the fault/journal path would also have to track 4,000 overlapping copies (heap views) and their lifetimes on the hottest path, to save a lookup that is now O(log n) plus the pages written in the range. +- Landing ("copying back" 10-12 ms for 0.7 MB): it already fetches only the pieces the card compare flagged, in one batched list and one wait per landing (`Host::relay_card_back`). Its fixed cost is the round trip per landing (11-13 a frame, ~0.4 ms each, "waits for fetches") plus building the piece list over all ~6,000 compared pieces (1-2 ms). Both live in `host.rs` (card plan/fetch), not this branch's files; the next step is a speculative copy of last landing's flagged pieces into the read-back buffer inside the flight's own list, behind its compare, so most landings need no second round trip. + +Expected (unmeasured): the chase's 10,977 known-nothing spans from ~3 us to well under 1 us each (several ms wall of the 42.9); "copies" MB down by the boundary-page re-copies (size unknown: read "MB taken again" and "ends of ranges in the middle of a page" against "copies MB" in the frame line). Also fewer "title bytes put in under flights' shader writes: pages looked at". + +Risks: a wrong part stamp is a stale host copy (old geometry/constants). The notes only ever claim a part current when it was held whole by a refresh or a merge at that asking, the same rule pages had. Lock order: `copied` -> `parts_taken` (-> journal read); `ranged` never held while `parts_taken` is taken. + +What to check in the log: the new `refreshes that looked at title memory` line; frame line "copies ms/MB"; `preparing per frame` "refreshes X in N flushes" and "asking the write watch"; "title bytes put in under flights' shader writes: pages looked at"; `settled for: title memory changed under shader writes` must not rise. With `VICTORY_REFRESH_CHECK=1` no "stale after its refresh, three times in a row" warnings. +## perf/thin-contention: per-call shared writes in list translation (NOT COMPILED, UNMEASURED; no switch) + +Measured before (log play-20261127-104020-14256, chase 10:49, Ryzen 7 5700X 8C/16T, card 25 % busy): 70,418 list +calls in 812.9 ms of thread time a frame = 11.5 us a call, against 5.3 us in plain gameplay and 3.5 us in the +`list/thin.rs` header. The cost per call doubles under load: what grows with the threads is what they share. Read +from code (line numbers before the change): every call or draw wrote lines that every translating thread writes. + +Removed (each was an atomic RMW or lock on one line for the whole process, per call/draw/lookup): +1. `list.rs:1934` `DRAWS.fetch_add` (`count_draw`, every draw, mesh dispatch and indirect execution) and + `list.rs:2013` `DISPATCHES.fetch_add`: now `crate::sharded::Counter` (one 128-byte place per thread, summed by + `take_counts` for the frame line). Same totals. +2. `draw.rs:653/1112/1124` `DRAWN`, `DROPPED`, `DISPATCHED` (`fetch_add` at draw.rs 3749-3781, 3816, 4361, 4367, + 4851, 4854, 5034, 5037, 5423, 5425: every draw/dispatch): `sharded::Counter`; `drawn()`, `dropped_now()`, + `take_dropped()`, `dispatched()` sum the places. Same totals. +3. `descriptor.rs:1173` `VIEWS: RwLock<Views>`: a read lock (an RMW on the lock word) per view look-up, i.e. per + `view_at` (descriptor.rs:1584), reached from `HostHeap::mirror`'s quick path (descriptor/host.rs:3903, every table + entry of every draw, `draw.rs:4460`), `make_listed` (descriptor/host.rs:3480) and `descriptor::view` in + `State::tables` (draw.rs:4584, 4593, 4699): tens a draw. Report 03 measured 410 ms / 5 s waiting for it. Now + `sharded::ReadMostly`: a reader takes only its own thread's lock (no shared line), a writer takes all 32 in order. + Same exclusion as the `RwLock`; lock waits still counted in `LOCK_WAITS[2..4]`. +4. `descriptor.rs:1562` `forget`: took the writer's lock (stopping every reader) for every released resource; now + looks first (reader's lock) and returns if the resource has no entry, as the old code did after the lock. +5. `host.rs:7900` `next_epoch` (one process-wide `fetch_add` per `HostList::changed_something`: state transitions + `host.rs:6741/6747`, `twins_written` 6977, `defer_copy` 7245, `defer` 7680, i.e. per draw that moves a texture): + each thread takes numbers from its own block of 1024 (`sharded::Numbers`). Epochs are only compared for equality + (draw.rs 4573/4606/4664, indirect/merge.rs, descriptor/host.rs:2882, host.rs:6597); they stay unique and never 0. +6. `pipeline.rs:442` `bound`: `p.bound.swap(true)` on every `SetPipelineState` (list.rs:1618) wrote the pipeline + object's line, which `host_pipeline` reads on every draw on every thread; now a load first, swap only the first + time. +7. `tight.rs:149` one `Mutex<State>` taken by `declare` for every root UAV a draw/dispatch writes (draw.rs:2232) on + every translating thread, and by `landed`: now 16 mutexes by key and 16 by copy; a declaration takes its key's, + then (full ones) its copy's; a landing takes its copy's, collects the hits, then each key's. Never two at once. + Same footprint state machine and order per key. + +Not changed (hot, but out of this branch's files or not exactly behaviour-preserving), in likely order of cost: +- `resource.rs:1656` `hosted()`: a per-resource `Mutex` and an `Arc` clone/drop per call, 2-4 calls per texture + per draw (`ensure_state` -> `HostList::transition` -> `host_copy`, `twin_use` -> `twin` + `host_copy`, and + `readable`'s `host_copy`, draw.rs 1861, 1865, 5668, 5681, 5691). Render targets, depth and shared textures are the + same objects on all threads: the same lines bounce. Fix: one `hosted` per texture per draw passed through + (needs `HostList::transition_made`/`twin_use_made`), or a lock-free snapshot of `made` (it is replaced by + `want_level`/`let_go_idle`, so needs an arc-swap or epoch scheme). Touches the texture let-go logic. +- `shadow.rs:5155/5175` `find`/`find_any` return `Arc<Shadow>`: a refcount RMW pair per vertex/index slot, root view + and buffer view per draw on buffers every list uses (shadow.rs is another agent's). +- `descriptor/host.rs:2249` `HostHeap::dynamic`: the heap's `Mutex` per fresh table (draw.rs:4616), one heap for all. +- `pipeline/make.rs:849` `note_draw`: `DRAW_COUNT.fetch_add` per `host_pipeline` call (2-4 a draw) while loading. + Not cached per draw: the count decides when loading ends, and calling it fewer times would move that. +- `host.rs:7228` `COPIES_JOINED` per deferred copy; `copystat::recorded` per call in diagnostics builds. +- `list/thin.rs` itself is fine: its shared counters and queues are touched per 1024-word chunk, not per call. + +Expected: unmeasured. Items 1-6 take 3-5 shared RMWs per draw and tens per draw from VIEWS off shared lines; at +7k draws and 70k calls a frame and 100-300 ns per contended RMW that is roughly 15-40 ms of the 813 ms thread time +(a few percent), more where the VIEWS lock was waited for (report 03: 6 ms a frame in waits alone). The larger +remaining shares are `hosted()` and the shadow `Arc`s above. Check: the thin line's us per call +(`list calls translated by threads of ours per frame`) in the same chase, and `LOCK_WAITS` views share in the +descriptor line. Risks: `ReadMostly` writers now take 32 locks (a new view, or the release of a resource with +entries): fine at hundreds a second, slower than before at a burst of tens of thousands; epochs are no longer in +order across threads (nothing orders them). + +## perf/raw-constants: every constant buffer read as raw bytes, in place at any title alignment (NOT COMPILED, UNMEASURED; no switch) + +Measured before (log play-20261127-111731-14036): ~14 fps in every scene; the submitting thread works 71 ms of a +71.7 ms frame (title waits 29.6 ms at presents). Port #1 opened (`1 regions ... in place (185 MB)`), but per frame +only 371 constant views were read in place and 6,185 were "not in place: not 256-aligned", so "6149 fills read out +of them" still ran on the CPU every frame with their refreshes, card copies and bookkeeping (lists' steps 29.8 ms, +copies in card memory 10.9 ms). Cause: a D3D12 CBV must begin on 256 bytes; the title places constants on 16. + +Change (structural, no switch; constants in code): +1. Translator (`victory-shader`, changes its hash: one cold retranslation and pipeline rebuild on the next run). + Every constant buffer load (`s_buffer_load_dword*` through a CBV, `buffer_load_dword*` through a CBV, the + heap-picked fallback) goes through `Lower::constant_view` / `constant_dword` (emit/lower.rs): + - root constant buffers: raw loads (`rawBufferLoad`, DXIL kind 11) through a new raw root SRV `t<slot>` in + `ROOT_CBV_SPACE` (`Shader::root_constants_handle`, replaces `root_cbv_handle`); byte 0 is the title's address; + the address is masked to a dword and reads at or past `ROOT_CONSTANT_BYTES` (64 KiB, what a CBV shows) give 0 + without touching memory (a root view has no size); + - constant buffers in tables, and picked from the heap: raw loads through the raw twin of the slot + (`raw_twin`, props 11), which the host already kept for every slot (`raw_views`); the twin is sized like the CBV + (`constant_bytes`: size rounded to 256, at most 64 KiB, cut at the buffer's end), so reads past it give 0; + - without raw twins (`VICTORY_RAW_VIEWS=0` or a heap of 2x the twins refused): the CBV, as before. + Metadata: `HostShader::root_cbvs` are now raw SRVs (listed with the root SRVs, PSV kind 4). +2. Root signature (`pipeline/host.rs`): `root_cbvs` are `D3D12_ROOT_PARAMETER_TYPE_SRV` root descriptors (never + one-view tables). `draw.rs` `bind` sets them with `Set*RootShaderResourceView`. +3. Binding: `draw.rs` `root_view` asks `port::constants(address, 64 KiB, ROOT_ALIGN = 4)`; fallback binds the + host copy at any 4-byte address (the 64 KiB scratch fill is left only for an address off 4 bytes). + `draw.rs` `tables` asks `port::constants(address, size, HostHeap::constant_align())` (16 with twins, 256 + without); `HostHeap::constant_at` makes the CBV only on 256 (else a null CBV) and the twin as a raw view through + `raw_view_range` (16-byte start, cut at the buffer's end). Fallback is unchanged (scratch + `defer_constants`). +4. Title-slot mirror (`make_twinned`, `View::Constant`): the twin of a CBV slot is now a raw view of the same bytes + (was a second CBV), so heap-picked constant buffers read correctly as raw bytes; a host copy off 256 but on 16 + now gets a null CBV + a raw twin instead of a null slot. + +Residual misalignment: none is passed. A raw root SRV binds at the exact title address (4-byte granularity covers +every dword address), so a root view has no residual. A raw view in a slot needs a 16-byte start; the console's +CBVs are on 16, so a table constant buffer off 16 (should be ~0) takes the old fill path and is counted as "not +aligned". A per-slot offset table would cost every table constant load an extra dependent load for that case. + +Expected: the `renderer port 1` frame line shows thousands of "constant views read in place", "not aligned for +their raw view" ~0, "fills read out of them" ~0; the frame line's "copies ms/MB", card-step fills, list steps and +"preparing per frame ... refreshes" fall by the share the 6,149 fills had (lists' steps 29.8 ms, card copies +10.9 ms). GPU side: constants are read over PCIe from title memory (L2-cached) through raw loads; NVIDIA serves +uniform raw loads through its L1, not the constant cache: watch the card's busy % in the frame line. + +Risks: (a) a wrong DXIL/root-signature mismatch shows as "host pipeline refused" / "host root signature refused" +on the first run (check the log after retranslation); (b) a table CBV read by a shader whose host heap has no twins +for that index (index past `twins.len()`) reads zeros; (c) twins are made on every CBV slot already, so no new +descriptor traffic, but the in-place path adds one `HostList::keep` (QueryInterface/AddRef) per bound constant +buffer, ~6.5k a frame; (d) same coherence assumptions as the port (ring discipline; first shader write to a page +read before it lands), now over ~17x more views. + +## perf/raw-constants, revision: table constants as structured views of dwords (NOT COMPILED, UNMEASURED; no switch) + +Measured after the first version (merged as perf/radical-refactor f597b66; log play-20261127-114321-28084): no root +signature or pipeline refusals, but per frame only ~108 constant views read in place, 2,841-4,075 "not aligned for +their raw view (4 root, 16 table)", 2,574-3,669 fills read out of ported memory, submitting thread 69.8 ms, 13.8 fps. + +Cause, from code and log: (b), not (a). `descriptor/host.rs` `probe_view_limit` gives raw twins only when a heap of +2 x `RAW_TWINS` (2 x 2^21) descriptors can be made; NVIDIA caps shader-visible view heaps at 1,000,000 +(`PORTABLE_VIEWS`), and the log says `host view heaps hold 1000000 views ... raw_twins=false`. With no twins, +`HostHeap::constant_align` returned 256, so every table constant fell back (and the merged `make_twinned` asked for +256 without a twin too). Twins cannot be made to fit: they sit at `2^21 + index` for every title slot, and the +title's heap alone is ~1,000,000 slots. + +Fix (no twins needed, no residual offset needed): +- A constant buffer's slot (fresh table slots, `constant_at`; title slots, `make_twinned`; null ones, + `null_constant_at` / `null_for`) is a structured view (`DXGI_FORMAT_UNKNOWN`, stride 4) of the CBV's bytes + (`constant_bytes`: rounded up to 256, at most 64 KiB, cut at the buffer's end): `descriptor/host.rs` + `constant_views`. A structured view's first element is any dword, so it begins at the title's own address (any 4 + bytes): no residual exists to pass. Its raw twin (AMD, where twins fit) is still made for picked reads. +- Translator (`emit/lower.rs` `constant_view`): constants loaded through tables read element `byte / 4` with a + structured load (props 12, stride 4) of their own slot; picked ones read the raw twin where twins exist, else the + same structured slot; root ones are unchanged (raw root SRV). The CBV path is left only for descriptors neither + in a root view nor in the heap (none the host binds). +- `port::constants(address, len, Use)`: one alignment, `ALIGN` = 4 bytes, for every binder; `Use::{Root, Table, + Mirror}` splits the counts. + +Why not the per-slot residual table the request named: with structured views there is no residual (the view begins +at the exact dword); a residual table would need a root SRV in every shader that reads table constants, the host to +keep a per-slot dword up to date in both heaps' tables, and a dependent load before every constant read. + +Log line now: `renderer port 1: ... per frame: N constant views read in place (... T in tables' slots, M in title +slots, the rest root views) ... not in place: off 4 bytes R root, T' in tables' slots, M' in title slots, S on pages +shaders write, O outside the regions; on the CPU F fills read out of them`. Expected: N in the thousands, R/T'/M' +~0, F ~0 (only constants on pages shaders write, or outside the region, still fill). + +Risks: (a) structured loads of a slot that holds something else (a picked index from wrong data on a host without +twins) mismatch the descriptor kind, as the CBV reads did before; (b) mirror slots made in place hold the region +buffer until the title rewrites them; (c) translator hash changes again: one more cold retranslation. diff --git a/docs/performance/ROOT_CAUSES.md b/docs/performance/ROOT_CAUSES.md new file mode 100644 index 000000000..9949d807a --- /dev/null +++ b/docs/performance/ROOT_CAUSES.md @@ -0,0 +1,35 @@ +# Root causes (consolidated from agent reports 02-05, 08) + +Labels: [M] measured in logs, [S] static code reading, [H] hypothesis. Source: AGENT_REPORTS/. Nothing here +has been re-measured in-game after a change yet. + +## Steady-state frame (48-51 ms, ~20 fps) [M, report 02] +~42 of 48 ms is noticing and moving memory, not GPU work (GPU ~7 ms busy). +- Over-wide shader-write declarations (`draw.rs:2167`, `draw.rs:5589`: whole UAV view declared written) cause + hash/compare passes, "title bytes under flights' writes" (9.6 ms) and refreshes (9.8 ms, 89% copy nothing). [S+M] +- Landing is ~96% waste: ~18 MB fetched/frame, 0.77 MB actually changed. [M] +- Descriptor mirror scans ~280k slots/frame to find 8-10k new records (3%). [M, report 03] + +## Late loading after world entry (~3-5 min) - three overlapping causes +1. Texture adoption throttle [M+S, report 05]: `play.rs` forced `TEXTURE_CATCHUP=0`, 16 ms slice, counted per + frame while frames take 100-300 ms. Backlog of up to 26k slots. -> commit c84d5e9 (UNMEASURED in-game). +2. Pipeline compiles [M+S, report 04]: ~1,360 pipelines compiled by the driver after entry, because + static-sampler pipelines (54%) bypass the persistent library (commit 7fa0e95, posterized-light bug). + Whether this bites depends on the title's own loading-screen length (60 s: stall; 120 s: hidden). +3. Card-memory line [M, report 02]: "no room, new textures wait", 8.5 GB vs 7.9 GB line (80% of budget, + `play.rs:213`), `VICTORY_LEVELS_ON_DEMAND=0`. [H that this bounds the drain] + +## Ranked work +| # | Item | Est. | Risk | Needs in-game A/B | +|---|------|------|------|---| +| 1 | Backlog slice (done, c84d5e9) | loading | low | yes | +| 2 | Pipelines: order early queue by first use, raise worker priority while loading, record compile ms | loading | low | yes | +| 3 | Memory: measurement patch (GPU-written blocks per copy), per-copy epoch, batched write-watch ask | 3-6 ms | low | yes | +| 4 | Descriptors: ask heap rounds only for pick-by-index submissions, coalesce write-watch asks | 1-2.5 ms | low-med | yes | +| 5 | Learn/persist GPU-write footprint per copy (R1) | 10-18 ms | med | yes + soak | +| 6 | Static-sampler pipelines back in library with registry+canary | ~1,360 compiles | med-high | visual A/B | +| 7 | GPU-written slot-use bitmap (descriptors A) | 4-10 ms | med-high | yes | +| 8 | Land only CPU-read blocks (R2) | 5-11 ms | high | soak | + +Config-only experiments for the user (no code): `VICTORY_LEVELS_ON_DEMAND=1`, `VICTORY_PIPELINE_WAIT_MS=50`, +`VICTORY_TEXTURE_BACKLOG_MS=400`. Press **A** to leave the menu at start. diff --git a/docs/performance/UNIFIED_MEMORY_ARCHITECTURE.md b/docs/performance/UNIFIED_MEMORY_ARCHITECTURE.md new file mode 100644 index 000000000..00ec31df6 --- /dev/null +++ b/docs/performance/UNIFIED_MEMORY_ARCHITECTURE.md @@ -0,0 +1,228 @@ +# Unified memory architecture: placement by access pattern + +Branch `perf/unified-memory` (from `perf/radical-refactor`). Written by reading only; **not compiled, not run** (the +user compiles). File:line references are to this branch at the commit that adds this document unless a later commit +is named. + +## 0. The error, stated once + +The console has one memory. The layer keeps a second copy of every title buffer a draw touches (`shadow.rs:28` +`Shadow`; for buffers >= 64 KiB two copies: `Card::staging` in PC memory and the card-side buffer, `shadow.rs:121`, +`shadow.rs:179 cards()`), and then spends the frame keeping the copies coherent: + +| Cost | Mechanism | Evidence | +|---|---|---| +| noticing CPU writes | write watch / read-only guards + vectored handler | `watch.rs:3160 on_write`; 02-memory 1.2: 4.1 ms/frame asking, 323-1,017 re-protects | +| noticing GPU writes | card hash/compare passes over declared ranges | `host.rs:4446 card_before`; 02-memory 1.5: 150 hash + 360 compare passes/frame | +| moving bytes | refresh (`shadow.rs:4236 update`, `:4405 copy_stale`), sends, landing (`land.rs`, `host.rs:5048 relay_land`, `:5193 card_back`) | 02-memory 0: 30 MB/frame copies, ~18 MB fetched to land 0.77 MB | +| merging under flights | `shadow.rs:4041 merge_under_writes` | 02-memory 1.4: 9.6 ms/frame, 61k runs of ~36 B (constants, counters) | +| waiting | settles (`host.rs:5487 settle`), read-wait (`host.rs:2907 late_blocked`, `:3093 blocked_by`) | EXPERIMENTS "read-wait": 18.6 ms/frame "a step that reads where a copy at its place writes" | + +All of it exists because there are two homes for the same bytes and no one says which home is authoritative. The +structural fix is to give every *access* exactly one authoritative home, chosen by how the bytes are written and read, +so that for the common classes there is nothing to notice, move or wait for. + +## 1. Hard constraints that shape the design (not choices) + +1. **A heap opened on title memory cannot take tile mappings** (`inplace.rs:30-31`: "Tile mappings into such a heap + are refused and REMOVE THE DEVICE"). Therefore one GPU virtual range cannot be backed partly by title memory and + partly by VRAM through a reserved resource. *Per-64 KiB mixed backing under one view is impossible.* The split has to + be made per **access** (per bound view/root address), not per page under a single view. +2. **The 174 MB heap is mostly heavily-read static data.** Run 69: 190-330 MB of distinct ranges of it read per list + (`shadow.rs` `cards()` doc, line ~160). In PC memory those reads cross PCIe; this is exactly why port #1 with the + whole heap in place made "the GPU wait (slower overall)" (`docs/README-foxhound.md`, switch table), and why + `CARD_BUFFERS` took the BVH skinning list from 50.5 to 4.5 ms (`shadow.rs:170-176`). The heap as a whole must stay + VRAM-resident. +3. **Skinning writes through one UAV of the whole heap** (`port.rs` header; `draw.rs:2216-2235` declares "all that is + left of the title's buffer"). A UAV view needs one contiguous GPU range; with constraint 1 it must be VRAM. +4. **CBVs need 256-byte aligned addresses** on the host (`draw.rs:1145-1165` root CBVs, `descriptor/host.rs:4889-4899`); + the title aligns constants to 16. *Resolved on `perf/raw-constants` (section 10):* translated shaders no longer + read constants through CBVs but as raw bytes (raw root SRVs need 4 bytes, raw views in slots 16), so no constant + needs a copy because of its alignment. +5. **Title writes are visible to the GPU in place without any action**: the opened heap is a custom write-back L0 heap + (`inplace.rs:27-30`); the GPU snoops. This is the one place the console's model holds for free. + +## 2. Classification (per access, with a per-4 KiB-page oracle) + +| Class | What | Home | Bound how | Coherence work | +|---|---|---|---|---| +| **C1 CPU->GPU** | constants (the ring in the 174 MB heap, per-draw constant buffers) read through CBVs | **T: title memory in place** (port region, one buffer over the whole stretch) | root CBV / table CBV address = region buffer + offset | **none**: no refresh, no fill, no send, no wait, no landing | +| **C2 GPU-written** | skinning outputs, compute UAV results, title GPU copies (copies at their place) | **V: VRAM** (existing card copy) | views as today | landing of what the card compare finds (existing); C2 pages never resolve to T | +| **C3 static/heavy read** | geometry, index data, structured buffers, textures | **V: VRAM** (existing card copy, uploaded once) | views as today | write watch only to notice the rare rewrite (refresh finds "nothing new") | + +The oracle that separates C1 from C2 is per 4 KiB page and has three inputs, all facts the layer already has: + +- **Landed lately** (`watch.rs:1931 LANDED`, `watch.rs:2046 landed_lately`, window 600 frames): every page a landing + wrote into, fed by `watch::landing` (`land.rs:616`, `shadow.rs:2398`) and `watch::landed_beside` (`land.rs:528`), + aliases included. The card compare finds real writes inside declared ranges. 600 frames is the window the shipped + `fill_is_titles` default already reads title memory under (`host.rs:2944`); skinning outputs land every frame and so + never leave C2, while a ring page written once by a title copy returns to C1. +- **Copy-bound at record time** (new, `port.rs` `PAGE_MARKS` stamp, 8 frames): destinations of every title buffer copy + as it is recorded (`host.rs` `defer_copy`, `host/place.rs:61 note_placed`). Such a copy may be done on the card + (`host/card_steps.rs` stage 2, or at its place in the list) and land after the flight; the stamp covers "written on + the card, not landed yet" (the relay keeps one or two frames in the air; `placed_lately` trusts two). +- **GPU-bound for good** (new, `PAGE_MARKS` = `u32::MAX`): destinations of read-backs into title memory + (`host.rs:7338 defer_read_back`). + +An access resolves to T only if **no page it can read is marked by any of them**, the address is in an opened port +region, the CBV's rounded size fits in the region, and the host address is aligned for the view that reads it (since +`perf/raw-constants`: 4 bytes for a root constant buffer, 16 for one in a table; 256 only on a host without raw +twins). Anything else takes the old path, unchanged. + +### The mixed 174 MB buffer + +It is not split under one view (constraint 1). It has **two homes at once**: V (the card copy that every +SRV/UAV/root-SRV/vertex/index/indirect access uses, as today) and T (the port region buffer, which CBV accesses to C1 +pages use). The same title address resolves differently by access kind: + +- `draw.rs` `root_view` (root constant buffer, `srv == false`, a raw root SRV since `perf/raw-constants`): + `port::constants(address, 64 KiB, Use::Root)` first; `Shadow::find`/`gpu` and the 64 KiB refresh only on + fallback (any 4-byte address; scratch only off 4 bytes). +- `draw.rs` table CBV (`View::Constant` in `tables`): `port::constants(address, size, Use::Table)` first; the slot + is made a structured view of dwords over the region buffer (`descriptor/host.rs` `constant_at` / + `constant_views`, which holds the buffer); scratch + `defer_constants` only on fallback. +- Title slots holding a CBV (descriptor mirror, `make_twinned`): `port::constants(address, size, Use::Mirror)` first, + else the host copy (V); a structured view either way. +- Everything else keeps `shadow::find` / `Shadow::gpu` (V). + +Why that is coherent: C1 pages are by definition pages no shader writes, so V's bytes for them can only be *older* +than T's, never newer; a CBV reading T reads the newest bytes there are. V keeps being refreshed for the views that +read C1 pages (a skinning pass that reads bone matrices from the ring through its UAV), exactly as today. + +## 3. Data flow after the change + +``` +title CPU writes constants ──► title memory (= T) ──► GPU reads via CBV at execution (PCIe snoop, L2-cached) + │ (nothing noticed, sent, filled, merged or waited for) +title CPU writes geometry ───► title memory ──write watch──► refresh ──► V (once; "nothing new" afterwards) +shader writes (UAV) ─────────► V ──card compare──► land ──► title memory ──► LANDED pages (= C2 for 600 frames) +title buffer copy (any kind) ► CPU at submission, or V (card step / at its place) ──► land; stamped at record (C2 for 8 frames) +``` + +Per frame this removes, for C1 accesses: the 64 KiB `Shadow::refresh` per aligned root CBV (`draw.rs:1159`), the +`Step::Fill` + scratch per aligned table CBV (`draw.rs:4702-4709`, `host.rs:7281`), with them the card-step fills +(`host/card_steps.rs`), the write-watch asks those refreshes made, the sends of ring pages they caused into V, and the +read-wait/settle those fills triggered when a flight's declared writes covered the ring (`host.rs:3079 read_blocked`). + +## 4. What is removed, what stays, and why + +Removed in this branch: + +| Item | Where | Why it is dead | +|---|---|---| +| `VICTORY_PORT_CONSTANTS` switch and the whole-buffer port path (`port::place_for`, `wanted`, `on`) | `port.rs`, `shadow.rs` lookup and windows, `inplace::counted`, menu item, `xmem.rs:1148 port_on` | whole buffers in place is the measured-slower model (constraint 2); the port region is now T, always opened | +| `VICTORY_FILL_TITLE` switch | `host.rs:2944` | the predicate is kept as the code default (it was on by default) | +| `VICTORY_WC_NO_BACK`, `_MIN_KB` switches | `shadow.rs` `wc_no_back`, `wc_no_back_min`, `play.rs:48-49`, launcher, menu | C2 rule for write-combined memory: the title maps WC what its CPU does not read; >= 1 MiB (the launcher's measured values: smaller ones such as exposure are read back) | + +Kept, and why (honest scope): + +- **Write watch / guards (`watch.rs`)**: still needed for C3 rewrites and for every V view that reads C1 pages. Off the + hot path for C1 CBV accesses only. +- **Landing, relay, card hash/compare, `merge_under_writes`**: still the C2 path. Their volume comes from over-wide + UAV declarations (`draw.rs:2216-2235`, `draw.rs:5643-5650`), which this branch does not narrow. +- **`tight.rs` (learned footprint)**: stays OFF. Narrowing a declaration without an exact fallback lets a write + outside the footprint stay on the card past a fence (EXPERIMENTS "tight-writes", violates invariant R1). +- **read-wait step 2 (`host/place.rs:361 placed_constants`)**: still needed for constants that are destinations of + copies at their place; those are C2 pages by the oracle and are resolved before T is asked (fills keep their order). +- **Descriptor mirror CBVs (`descriptor/host.rs:4889`)**: heaps the title writes and shaders pick by index keep V + addresses; moving them to T needs the mirror to re-make slots on class change (next step, section 6). +- **`VICTORY_INPLACE` (whole private buffers in place)**: an unrelated opt-in experiment, off; left as is. + +## 5. Invariants and how each holds + +- **R1 (shader writes the CPU reads reach title memory before any fence/present/wait that observes them)**: unchanged. + C2 lives in V and lands through the existing relay; nothing about landing order was touched. +- **R2 (stale results never overwrite newer title bytes)**: T is title memory; no copy is ever written into it by this + path. V for C1 pages may be older than T, and no landing writes C1 pages (by definition no shader writes them). +- **Title writes reach the GPU before the submission that reads them**: trivially true in T (the GPU reads at + execution, which is later than the fill used to snapshot them; the console also reads at execution). +- **Freed/remapped memory**: `inplace::title_memory_freeing` -> `port::forget` drops regions; bound lists keep the + region buffer alive (`HostList::keep`, slot holds), which still maps our own view of the old pages (never unmapped), + so no GPU fault; new binds fall back. + +## 6. Risks and concrete mitigations + +| Risk | Mitigation | +|---|---| +| First-ever shader write to a page that a CBV in the same or a later in-flight list reads (not landed yet, not declared at record) | Same accepted risk, same window, as the shipped `fill_is_titles` default (`host.rs:2925-2943`, `!landed_lately(600)`), plus the record-time copy stamps. The page becomes C2 at its first landing. If it shows (a constant one frame old in cutscenes), `LANDED_FRAMES` in `port.rs` set to `u64::MAX` makes landed pages the shaders' for good. Log: "renderer port 1 ... N on pages shaders write". | +| A title copy whose flight lands more than 8 frames after it was recorded | `COPY_FRAMES` (`port.rs`); the relay keeps 1-2 frames in the air. Raise it if `VICTORY_SUBMIT_FRAMES` is raised. | +| A draw recorded *before* a title copy in the same list reads the copy's new bytes (the CPU copy runs at submission, ahead of the list) | Same write-after-read ordering the ring discipline excludes (the ring advances to a new place each time); the copy stamp is set at record and any CBV recorded after it falls back. | +| The title rewrites a ring slot while the GPU still reads it (ring discipline assumed from the console) | That is the console's own contract (its GPU reads at execution too); our fences are signalled no earlier than the GPU's completion plus landing. Port #1's header already assumed it. If constants flicker: check "constants read in place" against the frame line, then disable by making `port::constants` return `None` (one line). | +| Region cannot be opened (lazy/soft views not committed, not one stretch, host refusal) | Falls back to the old path; retried every 600 frames for uncommitted/not-a-stretch; a host refusal disables T for the run. The log line counts each reason. | +| 185 MB of PC memory locked while the region stands | Bounded by `MOST` (512 MiB); the title keeps the heap for the process lifetime. | +| GPU reads constants over PCIe instead of VRAM (aligned root CBVs used V before) | Constants are tiny and L2-cached; table CBVs were already in upload (PC) memory (`host.rs:7369 scratch_held`). Watch "the card's clock" busy % in the frame line. | +| Pages mapped lazily (`VICTORY_SOFT_VIEWS=copies` in the launcher maps pool views when first touched, `xmem.rs` `map_pages(.., lazy)`): the stretch may be uncommitted or unknown to `inplace` when first asked | `NOT_COMMITTED`/`NOT_STRETCH` are retried every 600 frames; the log line counts them. If they never clear, the region is never opened and nothing changes (old path). | +| The region is opened on whichever thread records the first CBV in it (a THIN worker): a one-off map + open + place, pages locked (tens of ms once) | Under `REGIONS`' write lock, which no other lock is held around (`watch.rs:3015-3017` calls `views_gone` then `title_memory_freeing` sequentially). | +| `xmem::arrange` now always runs for the 32-bit reservation | It only exchanges never-mapped, never-written slices (`xmem.rs:1160-1172`); it ran in all port #1 runs. Log: "pages given their section's slices in address order". | + +## 7. Next steps (designed, not in this branch) + +1. **C2 demand landing (report 02 R2).** Land only pages the CPU reads. Mechanism: after a page lands, protect it + `PAGE_NOACCESS` for a probe window; `watch.rs` `on_write`'s handler records read faults (copy id, page) into a + lock-free bitmap and unprotects; the learned read set then gates `card_back` (pieces outside it are compared but not + fetched). Exactness requires that an unlanded, unread page is protected and that a fault on it blocks the faulting + title thread until the relay lands that piece; this is a fault-handler-to-relay handshake (no locks or allocation + in the handler, `ARCHITECTURE_AUDIT.md` 4.1) and must be soaked. Ocean maps are textures (`texback.rs`), already by + kind, unaffected. +2. **Exact narrow declarations** for C2 (tight footprint with a card-side whole-range compare-and-land as the + fallback), which removes most of `merge_under_writes` and the 96 % landing waste. +3. **Mirror CBVs to T**: `descriptor/host.rs:4889` resolves through `port::constants` too, re-made on class change. +4. **C1 for small CPU-written vertex/index windows** (UI vertices outside buffers): same oracle, bound in T. + +## 8. Log lines to check (see also section 10) + +- `renderer port 1: a stretch of the title's graphics memory opened as a host heap through a view of ours` (once). +- Frame-rate block: `renderer port 1: N regions ... (M MB); per frame: X constants read in place (Y KB), fell back: a misaligned, b written by shaders, c outside the regions; ...`. +- `renderer port 1: the title's 32-bit graphics pages given their section's slices in address order` (xmem). +- Must fall: frame line "copies ms/MB", card-step fills, "title memory read" settles, "preparing per frame ... refreshes". +- Must not rise: `settled for: title memory changed under shader writes`; no constants flicker in cutscenes; boats float. + +## 9. Commits on this branch + +1. this document; +2. `port`: title-memory home (one region buffer over the 32-bit heap's stretch, `port::constants`, the per-page + oracle, `gpu_bound`), always on; whole-buffer port path and `VICTORY_PORT_CONSTANTS` removed (gpu, xmem, menu); +3. `draw`: root and table CBVs resolve to the title-memory home first; `note_placed` and `defer_read_back` mark + their pages; `VICTORY_FILL_TITLE` removed (its default kept); +4. `shadow`: write-combined copies >= 1 MiB keep shader writes on the card by default (`VICTORY_WC_NO_BACK`, + `_MIN_KB` removed from code, launcher, `play.rs` and menu); +5. `port`: the page oracle per 4 KiB page (`PAGE_MARKS`): read-backs for good, every title buffer copy for 8 frames + from its recording (`defer_copy`, `note_placed`: copies done on the card by `card_steps` or at their place land + after their flight), landings for 600 frames. + +## 10. `perf/raw-constants`: constants read as raw bytes (removes constraint 4) + +Measured on this branch's port (log play-20261127-111731-14036): the region opened (185 MB), yet per frame only 371 +constant views were read in place and 6,185 were "not 256-aligned"; 6,149 fills still ran on the CPU every frame +(lists' steps 29.8 ms, card copies 10.9 ms, submitting thread 71 of 71.7 ms, ~14 fps). The 256-byte rule is +D3D12's for CBVs; the console has none, and its constants lie on 16. + +Structure after the change (no switch; constants in code): + +| Access | Shader reads (victory-shader `emit/lower.rs` `constant_view`) | Host binds | Needs | +|---|---|---|---| +| root constant buffer | `rawBufferLoad` through root SRV `t<slot>` (`ROOT_CBV_SPACE`), zeros past 64 KiB by the code | `Set*RootShaderResourceView` at T (`port::constants(.., Use::Root)`) or the host copy | 4 bytes | +| constant buffer in a table | structured load (props 12, stride 4) of element `byte / 4` through its own slot | structured view (`DXGI_FORMAT_UNKNOWN`, stride 4, sized like the CBV: zeros past it) over T or the scratch copy | 4 bytes | +| title slot (mirror) holding a CBV | as in a table | structured view over T (`Use::Mirror`) or V | 4 bytes | +| constant buffer picked from the heap by a computed index | with raw twins: `rawBufferLoad` through the twin (null raw view if off 16); without: as in a table | twin: raw view of the same bytes | 16 / 4 bytes | + +Revision (same day, log play-20261127-114321-28084): the first version read tables' constants through the slots' raw +twins and used `port::constants(.., 16 or 256)`. On NVIDIA the view heap is capped at 1,000,000 descriptors and the +twins (2 x 2^21) do not fit: `host view heaps hold 1000000 views ... raw_twins=false`, so every table constant asked +for 256 bytes: ~108 views a frame in place, 2,841-4,075 "not aligned", 2,574-3,669 fills, 13.8 fps. Cause (b), not +(a). Fix: a constant buffer's slot itself is a structured view of dwords, which begins on any 4 bytes and needs no +twin and no residual offset (a residual table would cost a root SRV per shader and a dependent load per read; a +structured view's first element is the title's own dword). Counts are split by binder: off 4 bytes as root, in +tables' slots, in title slots; read in place in tables' slots and in title slots. + +Coherence is the port's (section 2, 5): only the view kind changed; which bytes are T is still decided per page by +the oracle. Fallbacks (not in a region, pages shaders write, off alignment) keep the old copy paths, so correctness +does not depend on the port opening. Pages shaders write keep V exactly as before. + +Not done: a mirror slot made in place keeps the region buffer until the title rewrites the slot; a page that becomes +the shaders' later is still read in place through it (the same window as the port's oracle, section 6). + +Log lines: `renderer port 1: ... per frame: N constant views read in place (...; T in tables' slots, M in title +slots, the rest root views)`: N in the thousands; `not in place: off 4 bytes R root, T' in tables' slots, M' in title +slots` all ~0; `fills read out of them` ~0. Must not appear: `host root signature refused`, `host pipeline refused`, +`constant buffer not on 4 bytes on the host`. diff --git a/scripts/perf/summarize_run.py b/scripts/perf/summarize_run.py new file mode 100644 index 000000000..b4e621bbc --- /dev/null +++ b/scripts/perf/summarize_run.py @@ -0,0 +1,793 @@ +#!/usr/bin/env python3 +"""Summarize one VIctory run (frametime.csv + victory.log / play-*.log) as JSON + markdown. + +Usage: + python scripts/perf/summarize_run.py <run dir | victory.log | play-*.log | frametime.csv> [more ...] + [--out DIR] [--label TEXT] [--stall-ms 200] [--heavy-draws 1000] [--warmup-s 30] + python scripts/perf/summarize_run.py --compare A B [--stall-ms 200] (A, B: run dirs or *.summary.json) + python scripts/perf/summarize_run.py --latest [N] (the N newest runs of %LOCALAPPDATA%\\victory\\runs) + +Only the standard library is used. Nothing here is estimated unless it says so: every figure is either read +from a file, or computed from file values with the definition printed in the output's "definitions" list. + +Inputs and what they hold + frametime.csv one row per ~1 s window: frames, mean ms/frame, MAX ms/frame, CPU prepare ms, GPU ms/pct, + draws, MB copied/sent/fetched, RAM, CPU %. Header comments name CPU, GPU, driver, switches. + victory.log a frame line (~every 1-5 s: fps, ms/frame, preparing/GPU/copy-back ms, draws), per-frame + subsystem lines (submission preparing, descriptor sync, relay, card clock, frame activity), + `stall:` watchdog lines (with where the threads stood), shader cache hits/misses, + passswitch/gfxswitch lines (ablations switched in the F1 menu), launcher lines. + play-*.log the same log, first line is `# console=... build=... switches: ...`; no frametime.csv: the + time series is rebuilt from the frame lines (no per-window max, so no tail figures). +""" +import argparse, csv, glob, json, math, os, re, sys +from datetime import datetime, timezone + +ANSI = re.compile(r'\x1b\[[0-9;]*m') +TS = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+)Z') +NUM = r'(-?[\d.]+)' + + +def iso_ms(s): + return datetime.fromisoformat(s).replace(tzinfo=timezone.utc).timestamp() * 1000.0 + + +def wquantile(pairs, q): + """Weighted quantile of [(value, weight)].""" + pairs = sorted(pairs) + tot = sum(w for _, w in pairs) + if tot <= 0: + return None + acc = 0.0 + for v, w in pairs: + acc += w + if acc >= q * tot: + return v + return pairs[-1][0] + + +def mean(xs): + xs = [x for x in xs if x is not None] + return sum(xs) / len(xs) if xs else None + + +def r(x, n=2): + return None if x is None else round(x, n) + + +# ----------------------------------------------------------------------------------------------- inputs +def find_inputs(path): + """-> (csv_path|None, log_path|None, name).""" + if os.path.isdir(path): + c = os.path.join(path, 'frametime.csv') + l = os.path.join(path, 'victory.log') + return (c if os.path.exists(c) else None, l if os.path.exists(l) else None, os.path.basename(path.rstrip('\\/'))) + if path.lower().endswith('.csv'): + d = os.path.dirname(path) + l = os.path.join(d, 'victory.log') + return path, (l if os.path.exists(l) else None), (os.path.basename(d) if os.path.basename(d) != 'cache' else 'cache-frametime') + return None, path, os.path.basename(path) + + +def read_csv(path): + meta, rows = {}, [] + with open(path, encoding='utf-8', errors='replace') as f: + lines = f.read().splitlines() + body = [] + for ln in lines: + if ln.startswith('#'): + m = re.match(r'#\s*([\w ]+):\s*(.*)', ln) + if m: + meta[m.group(1).strip()] = m.group(2).strip() + elif ln.strip(): + body.append(ln) + rd = csv.DictReader(body) + for d in rd: + try: + rows.append({k: float(v) for k, v in d.items() if v not in (None, '')}) + except ValueError: + continue + return meta, rows + + +FRAME_RE = re.compile( + NUM + r' fps, ' + NUM + r' ms/frame \(' + NUM + r' preparing: copies ' + NUM + r' ms ' + NUM + r' MB, textures ' + NUM + + r' ms ' + NUM + r' MB; ' + NUM + r' on the GPU; ' + NUM + r' copying back ' + NUM + r' MB\), ' + NUM + + r' draws/frame, dropped ' + NUM + r' without a host pipeline \(' + NUM + r' being made\) and ' + NUM + r' indirect') + +# name -> (regex, group names) ; every value is a per-frame figure of the window the line closes +SUBSYS = { + 'prep_split': (r'submission preparing per frame \(ms\): before the steps ' + NUM + r", the lists' steps " + NUM + + r', flush ' + NUM + r', snapshots ' + NUM + r', card copies ' + NUM, + ['before_steps_ms', 'lists_steps_ms', 'flush_ms', 'snapshots_ms', 'card_copies_ms']), + 'prep_sub': (r'before the steps split: sync_heaps ' + NUM + r', sweep ' + NUM + r', make_waiting ' + NUM + + r', asking the write-watch ' + NUM, ['sync_heaps_ms', 'sweep_ms', 'make_waiting_ms', 'write_watch_ms']), + 'activity': (r'frame activity ms/frame .*?: submission lock ' + NUM + r', watch/dependencies ' + NUM + + r', descriptor sync ' + NUM + r', pending views ' + NUM + r', GPU handoff ' + NUM + r', GPU settle ' + NUM + + r', relay ' + NUM + r', present ' + NUM + r', buffer views ' + NUM + r', texture views ' + NUM, + ['sub_lock_ms', 'watch_deps_ms', 'desc_sync_ms', 'pending_views_ms', 'gpu_handoff_ms', 'gpu_settle_ms', + 'relay_ms', 'present_ms', 'buffer_views_ms', 'texture_views_ms']), + 'desc_sync': (r'descriptor sync per frame: ' + NUM + r' ms collecting pages, ' + NUM + r' ms scanning, ' + NUM + + r' ms mirroring', ['collect_ms', 'scan_ms', 'mirror_ms']), + 'desc_slots': (r'descriptor records the title copied into its heap as bytes: per frame ' + NUM + + r' changed heap pages, ' + NUM + r' slots looked at, ' + NUM + r' whose record was new and was mirrored', + ['heap_pages', 'slots_looked_at', 'slots_mirrored']), + 'desc_calls': (r'descriptors ' + NUM + r' ms \(' + NUM + r' calls.*?heap_buffers ' + NUM + r' ms', + ['descriptors_pass_ms', 'descriptors_pass_calls', 'heap_buffers_pass_ms']), + 'card_clock': (r"the card's clock per frame: nothing of ours queued " + NUM + r' ms \(the card about ' + NUM + r'% busy', + ['card_idle_ms', 'card_busy_pct_by_count']), + 'relay': (r'the relay per frame .*?: ' + NUM + r' flights landed in ' + NUM + r' landings.*?waited ' + NUM + + r' ms for the card with nothing to land and ' + NUM + r' ms for fetches.*?and was ' + NUM + r' ms landing', + ['flights', 'landings', 'relay_wait_card_ms', 'relay_wait_fetch_ms', 'relay_landing_ms']), + 'sent_ahead': (r'submissions sent ahead per frame: ' + NUM + r' in ' + NUM + r' settles .*?' + NUM + + r' ms waiting for the card', ['submissions_sent_ahead', 'settles', 'settle_wait_ms']), + 'buf_refresh': (r'buffer refresh per frame: ' + NUM + r' MB requested in ' + NUM + r' requests, ' + NUM + + r' MB after merging in ' + NUM + r' spans', ['refresh_req_mb', 'refresh_requests', 'refresh_merged_mb', 'refresh_spans']), + 'card_copies': (r'host copies in the card\'s memory: .*?per frame: ' + NUM + r' MB sent up in ' + NUM + + r' ranges, ' + NUM + r' pieces compared on the card, ' + NUM + r' of them fetched \(' + NUM + r' MB\)', + ['card_sent_up_mb', 'card_ranges', 'card_pieces_compared', 'card_pieces_fetched', 'card_fetched_mb']), + 'gpuspan': (r"the card's own timestamps per frame, over " + NUM + r' frames: inside sends: title lists ' + NUM + + r' ms in ' + NUM + r' sends.*?between sends with nothing to run ' + NUM + r' ms \(' + NUM + + r' gaps, the longest ' + NUM + r' ms\); first send to last ' + NUM, + ['span_frames', 'gpu_title_lists_ms', 'sends', 'gpu_gap_ms', 'gaps', 'longest_gap_ms', 'first_to_last_ms']), + 'dstorage': (r'dstorage: last ' + NUM + r' s requests=' + NUM + r' mb_per_s=' + NUM, ['window_s', 'requests', 'mb_per_s']), +} +SUBSYS_C = {k: (re.compile(v[0]), v[1]) for k, v in SUBSYS.items()} +STALL_RE = re.compile(r'stall: the frame has not advanced; inside: (.*?) frame=(\d+) stalled_ms=(\d+) presented=(\d+) ' + r'submissions_started=(\d+) submissions_finished=(\d+)') +ACT_COUNTERS = re.compile(r'presented=(\d+) submissions_started=(\d+) submissions_finished=(\d+)') +CACHE_RE = re.compile(r'shaders from the cache and translated so far hits=(\d+) misses=(\d+)') +TRANS_RE = re.compile(r'shader translated stage="(\w+)".*? ms=' + NUM) +PASS_RE = re.compile(r'(passswitch|gfxswitch): (.*)') +PASSOFF_RE = re.compile(r'emulator passes off(?: \([^)]*\))?: ([^;]*?)(?:;|$)') +GFXON_RE = re.compile(r'graphics methods on(?: \([^)]*\))?: ([^;]*?)(?:;|$)') +PIPE_MAKING_RE = re.compile(r'frame=(\d+) stage') + + +def read_log(path): + with open(path, encoding='utf-8', errors='replace') as f: + txt = ANSI.sub('', f.read()) + L = {'header': None, 'launcher': [], 'frames': [], 'sub': {k: [] for k in SUBSYS}, 'stalls': [], 'counters': [], + 'cache': None, 'translations': 0, 'translate_ms': 0.0, 'passes': [], 'console': None, 'first_ts': None, + 'last_ts': None, 'passes_off_last': None, 'gfx_on_last': None, 'warn': 0, 'errors': 0, 'flags': {}} + for i, ln in enumerate(txt.split('\n')): + if i == 0 and ln.startswith('# console='): + L['header'] = ln + ln = ln.lstrip('') + if ln.startswith('[launcher]'): + L['launcher'].append(ln[10:].strip()) + continue + if ln.startswith('console '): + L['console'] = ln.split(None, 1)[1].strip() + m = TS.match(ln) + if not m: + continue + t = iso_ms(m.group(1)) + if L['first_ts'] is None: + L['first_ts'] = t + L['last_ts'] = t + if ' WARN ' in ln: + L['warn'] += 1 + elif ' ERROR ' in ln: + L['errors'] += 1 + if 'shader translated' in ln: + L['translations'] += 1 + mm = TRANS_RE.search(ln) + if mm: + L['translate_ms'] += float(mm.group(2)) + continue + if ' fps, ' in ln and 'ms/frame (' in ln: + mm = FRAME_RE.search(ln) + if mm: + v = [float(x) for x in mm.groups()] + L['frames'].append({'t': t, 'fps': v[0], 'ms': v[1], 'prep_ms': v[2], 'copies_ms': v[3], 'copies_mb': v[4], + 'tex_ms': v[5], 'tex_mb': v[6], 'gpu_ms': v[7], 'copyback_ms': v[8], 'copyback_mb': v[9], + 'draws': v[10], 'dropped': v[11], 'making': v[12], 'indirect': v[13]}) + continue + if 'stall:' in ln: + mm = STALL_RE.search(ln) + if mm: + L['stalls'].append({'t': t, 'inside': mm.group(1), 'frame': int(mm.group(2)), 'stalled_ms': int(mm.group(3)), + 'presented': int(mm.group(4))}) + continue + if 'frame activity' in ln: + mm = ACT_COUNTERS.search(ln) + if mm: + L['counters'].append({'t': t, 'presented': int(mm.group(1)), 'started': int(mm.group(2)), 'finished': int(mm.group(3))}) + mm = CACHE_RE.search(ln) + if mm: + L['cache'] = (int(mm.group(1)), int(mm.group(2))) + mm = PASSOFF_RE.search(ln) + if mm: + L['passes_off_last'] = mm.group(1).strip() + mm = GFXON_RE.search(ln) + if mm: + L['gfx_on_last'] = mm.group(1).strip() + mm = PASS_RE.search(ln) + if mm: + L['passes'].append({'t': t, 'kind': mm.group(1), 'text': mm.group(2)[:200]}) + for k, (rx, names) in SUBSYS_C.items(): + if k == 'desc_calls' and 'emulator passes off' not in ln: + continue + mm = rx.search(ln) + if mm: + d = {n: float(x) for n, x in zip(names, mm.groups())} + d['t'] = t + L['sub'][k].append(d) + break + # a few one-off facts + for key, pat in (('dlss', r'DLSS Super Resolution is supported'), ('streamline_loaded', r'Streamline loaded'), + ('framegen_on', r'frame ?gen\w* (?:is )?(?:on|enabled)'), ('auto_a', r'VICTORY_AUTO_A')): + L['flags'][key] = bool(re.search(pat, txt, re.I)) + mm = re.search(r'dlss[^\n]*?(mode|quality)=\"?(\w+)', txt, re.I) + return L + + +# ----------------------------------------------------------------------------------------------- analysis +def windows_from_csv(rows): + """One record per ~1 s window; dt from consecutive t_ms. First row has no dt (kept for counts only).""" + w = [] + prev_t = None + for x in rows: + n = x.get('frames', 0.0) + dt = (x['t_ms'] - prev_t) if prev_t is not None else None + prev_t = x['t_ms'] + w.append({'t': x['t_ms'], 'dt': dt, 'n': n, 'avg': x.get('ms_per_frame'), 'max': x.get('frame_ms_max'), + 'draws': x.get('draws', 0.0), 'making': x.get('making', 0.0), 'row': x}) + return w + + +def windows_from_log(frames): + w = [] + prev = None + for f in frames: + dt = (f['t'] - prev) if prev is not None else None + prev = f['t'] + n = f['fps'] * dt / 1000.0 if dt else 0.0 + w.append({'t': f['t'], 'dt': dt, 'n': n, 'avg': f['ms'], 'max': None, 'draws': f['draws'], 'making': f['making'], 'row': f}) + return w + + +def reconstruct(wins): + """Per window of n frames with mean a and max m: one frame at m, n-1 at (n*a-m)/(n-1). + Exact in the window's frame count, sum of time and maximum; only a model of the spread in between.""" + out = [] + for x in wins: + n = int(round(x['n'])) + if n <= 0 or x['avg'] is None: + continue + if x['max'] is None or n == 1: + out.append((x['avg'] if x['max'] is None else x['max'], n if n > 0 else 1) if n > 1 or x['max'] is None else (x['max'], 1)) + continue + rest = (n * x['avg'] - x['max']) / (n - 1) + if rest <= 0: + out.append((x['avg'], n)) + else: + out.append((x['max'], 1)) + out.append((rest, n - 1)) + return out + + +def dist(wins, tag): + """Frame-time statistics of a set of windows.""" + wins = [x for x in wins if x['n'] and x['avg']] + if not wins: + return None + frames = sum(x['n'] for x in wins) + time_ms = sum(x['n'] * x['avg'] for x in wins) + plain = [(x['avg'], x['n']) for x in wins] + rec = reconstruct(wins) + d = {'windows': len(wins), 'frames': int(round(frames)), 'seconds': r(time_ms / 1000, 1), + 'fps_mean': r(1000 * frames / time_ms) if time_ms else None, + 'ms_mean': r(time_ms / frames), + 'ms_median_windowavg': r(wquantile(plain, 0.5)), + 'ms_p90_windowavg': r(wquantile(plain, 0.9)), + 'ms_p99_windowavg': r(wquantile(plain, 0.99))} + if all(x['max'] is not None for x in wins): + d['ms_median_reconstructed'] = r(wquantile(rec, 0.5)) + d['ms_p90_reconstructed'] = r(wquantile(rec, 0.90)) + d['ms_p99_reconstructed'] = r(wquantile(rec, 0.99)) + d['ms_worst_frame'] = r(max(x['max'] for x in wins)) + p99 = d['ms_p99_reconstructed'] + d['fps_1pct_low_p99'] = r(1000 / p99, 1) if p99 else None + # mean fps of the slowest 1 % of frames (reconstructed) + tot = sum(w for _, w in rec) + k, acc, sl = max(1, int(tot * 0.01)), 0, [] + for v, w in sorted(rec, reverse=True): + take = min(w, k - acc) + sl += [v] * take + acc += take + if acc >= k: + break + d['fps_1pct_low_mean_of_slowest'] = r(1000 / mean(sl), 1) if sl else None + wm = sorted(x['max'] for x in wins) + d['window_max_ms_p50'] = r(wm[len(wm) // 2]) + d['window_max_ms_p90'] = r(wm[int(len(wm) * 0.9) - 1 if len(wm) > 1 else 0]) + d['tag'] = tag + return d + + +def stalls_csv(wins, thr, ref=None, rel=3.0): + """A stall window = a window whose slowest frame is >= thr ms (CSV keeps only one max per window, so the + stalled time is a LOWER bound: sum of those maxima).""" + thr = max(thr, rel * ref) if ref else thr + if wins and all(x['max'] is None for x in wins): + return {'threshold_ms': r(thr, 1), 'stall_windows': None, 'stalled_ms_lower_bound': None, 'worst_ms': None, + 'windows_total': len(wins), 'share_of_windows': None, 'over_1000ms_windows': None} + s = [x for x in wins if x['max'] is not None and x['max'] >= thr] + return {'threshold_ms': r(thr, 1), 'stall_windows': len(s), 'stalled_ms_lower_bound': r(sum(x['max'] for x in s), 0), + 'worst_ms': r(max((x['max'] for x in s), default=0), 0), + 'windows_total': len(wins), + 'share_of_windows': r(len(s) / len(wins), 3) if wins else None, + 'over_1000ms_windows': sum(1 for x in s if x['max'] >= 1000)} + + +def phases(wins, heavy_draws, warm_s): + """Boot -> first heavy scene -> stabilised. World entry = first of 3 consecutive windows with mean draws/frame + >= heavy_draws. Stabilised = first window after entry+warm_s from which the next 10 windows all have + window-mean ms within +-25 % of the median of the second half of the heavy windows.""" + if not wins: + return {} + t0 = wins[0]['t'] - (wins[1]['dt'] if len(wins) > 1 and wins[1]['dt'] else 1000) + out = {'t0_epoch_ms': wins[0]['t']} + entry = None + for i in range(len(wins) - 2): + if all(wins[j]['draws'] >= heavy_draws for j in (i, i + 1, i + 2)): + entry = i + break + # first window with any scene (draws >= 100, 3 in a row) + scene = None + for i in range(len(wins) - 2): + if all(wins[j]['draws'] >= 100 for j in (i, i + 1, i + 2)): + scene = i + break + # first window after which no pipelines are being made + out['first_window_pipelines_being_made'] = wins[0]['making'] + mk = [i for i, x in enumerate(wins) if x['making'] > 0] + out['seconds_until_pipelines_made_done'] = r((wins[mk[-1]]['t'] - t0) / 1000, 1) if mk else 0.0 + out['seconds_to_scene_draws_ge_100'] = r((wins[scene]['t'] - t0) / 1000, 1) if scene is not None else None + out['seconds_to_heavy_scene'] = r((wins[entry]['t'] - t0) / 1000, 1) if entry is not None else None + out['heavy_draws_threshold'] = heavy_draws + out['stabilised_at_s'] = None + out['stabilise_rule'] = (f'first window >= {warm_s:.0f}s after heavy-scene entry whose next 10 windows are all within +-25% ' + 'of the median ms/frame of the second half of the heavy windows') + if entry is not None: + heavy = [x for x in wins[entry:] if x['draws'] >= heavy_draws and x['avg']] + if len(heavy) >= 12: + half = sorted(x['avg'] for x in heavy[len(heavy) // 2:]) + ref = half[len(half) // 2] + out['ref_ms_second_half'] = r(ref) + for i in range(entry, len(wins) - 10): + if wins[i]['t'] - wins[entry]['t'] < warm_s * 1000: + continue + if all(wins[j]['avg'] and abs(wins[j]['avg'] - ref) <= 0.25 * ref for j in range(i, i + 10)): + out['stabilised_at_s'] = r((wins[i]['t'] - t0) / 1000, 1) + out['stabilised_after_entry_s'] = r((wins[i]['t'] - wins[entry]['t']) / 1000, 1) + break + out['_entry_index'] = entry + out['_entry_t'] = wins[entry]['t'] if entry is not None else None + out['_t0'] = t0 + return out + + +def csv_columns(wins, sel): + """Frame-weighted means of the CSV columns over the selected windows.""" + sel = [x for x in sel if x['n']] + if not sel: + return {} + tw = sum(x['n'] for x in sel) + cols = ['cpu_prepare_ms', 'gpu_ms', 'gpu_pct', 'copies_ms', 'copies_mb', 'textures_ms', 'textures_mb', 'copyback_ms', + 'copyback_mb', 'draws', 'dropped', 'indirect', 'heap_passes', 'heap_ms', 'texture_refresh_ms', 'card_passes', + 'card_compares', 'card_sent_mb', 'card_ranges', 'card_pieces', 'card_fetched', 'card_fetched_mb', 'card_waits', + 'card_wait_ms'] + out = {} + for c in cols: + vals = [(x['row'].get(c), x['n']) for x in sel if c in x['row']] + if vals: + out[c] = r(sum(v * w for v, w in vals) / sum(w for _, w in vals), 3) + # gpu_pct is 0 when the GPU timestamps are not on; report the share of windows that have it + g = [x['row'].get('gpu_pct', 0) for x in sel] + out['_gpu_pct_windows_nonzero'] = sum(1 for v in g if v > 0) + out['_windows'] = len(sel) + out['ram_mb_last'] = r(sel[-1]['row'].get('ram_mb'), 0) + out['ram_mb_max'] = r(max(x['row'].get('ram_mb', 0) for x in sel), 0) + out['cpu_pct_mean'] = r(mean([x['row'].get('cpu_pct') for x in sel]), 1) + return out + + +def sub_means(L, t_from): + """Mean of each per-frame log line in the heavy phase (simple mean of lines, one per window).""" + out = {} + for k, lines in L['sub'].items(): + sel = [d for d in lines if t_from is None or d['t'] >= t_from] + if not sel: + continue + keys = [n for n in sel[0] if n != 't'] + out[k] = {n: r(mean([d[n] for d in sel]), 3) for n in keys} + out[k]['_lines'] = len(sel) + return out + + +def classify_stalls(L): + """Group the watchdog lines: lines of the same frame number belong to one stall; its length is the largest + stalled_ms; its cause the `inside:` text (what the threads stood in at the first line).""" + groups = [] + for s in L['stalls']: + if groups and groups[-1]['frame'] == s['frame']: + g = groups[-1] + g['stalled_ms'] = max(g['stalled_ms'], s['stalled_ms']) + g['lines'] += 1 + continue + groups.append(dict(s, lines=1)) + by = {} + for g in groups: + key = re.sub(r'\s*\(last entered \d+ ms ago\)', '', g['inside']) + key = re.sub(r' x\d+', '', key)[:140] + d = by.setdefault(key, {'count': 0, 'ms': 0, 'worst_ms': 0}) + d['count'] += 1 + d['ms'] += g['stalled_ms'] + d['worst_ms'] = max(d['worst_ms'], g['stalled_ms']) + return {'watchdog_stalls': len(groups), 'watchdog_ms_total': sum(g['stalled_ms'] for g in groups), + 'watchdog_worst_ms': max((g['stalled_ms'] for g in groups), default=0), + 'by_inside': dict(sorted(by.items(), key=lambda kv: -kv[1]['ms']))} + + +def label_run(name, meta, L): + """What the files say about the configuration. Anything not stated is 'unknown'; nothing is inferred.""" + sw = {} + src = None + if meta.get('switches'): + src = meta['switches'] + elif L and L.get('header'): + src = L['header'].split('switches:', 1)[1] if 'switches:' in L['header'] else '' + if src: + for tok in re.findall(r'(VICTORY_[A-Z0-9_]+)=(\S*)', src): + sw[tok[0]] = tok[1] + if L: + for ln in L['launcher']: + m = re.match(r'(VICTORY_[A-Z0-9_]+)=(.*)', ln) + if m: + sw.setdefault(m.group(1), m.group(2)) + lab = {} + console = None + if L and L.get('header'): + m = re.match(r'# console=(\S+) build=(\S+)', L['header']) + if m: + console, lab['build'] = m.group(1), m.group(2) + if L and L.get('console') and not console: + console = 'series-x' if 'Series X' in L['console'] else ('series-s' if 'Series S' in L['console'] else L['console']) + if L: + for ln in L['launcher']: + m = re.search(r'profile=(\w+)', ln) + if m: + lab['build'] = m.group(1) + lab['console_profile'] = console or 'unknown' + lab['dlss'] = ('on:' + sw.get('VICTORY_DLSS_MODE', '?')) if sw.get('VICTORY_DLSS') == '1' else ( + 'off' if sw or L else 'unknown') + if sw.get('VICTORY_DLSS') != '1' and L and L['flags'].get('streamline_loaded'): + lab['dlss'] = 'streamline loaded (mode not in switch list)' + fx = sw.get('VICTORY_FRAMEGEN_X') + lab['framegen'] = ('off (ready)' if (sw.get('VICTORY_FRAMEGEN') == '1' and fx in ('0', None)) else + f'on x{fx}' if sw.get('VICTORY_FRAMEGEN') == '1' else 'off/unknown') + lab['resolution_switch'] = ('native-1440p' if sw.get('VICTORY_NATIVE_1440P') == '1' else + '1080p-render' if sw.get('VICTORY_RENDER_1080P') == '1' else 'default/unknown') + lab['panel'] = sw.get('VICTORY_PANEL', 'unset') + lab['auto_a_switch'] = sw.get('VICTORY_AUTO_A', 'unset') + lab['relay'] = sw.get('VICTORY_RELAY', 'unset') + if L: + lab['shader_cache'] = ({'hits': L['cache'][0], 'misses': L['cache'][1]} if L['cache'] else 'no cache line in log') + lab['shader_translations_in_log'] = L['translations'] + lab['passes_off_final'] = L['passes_off_last'] or 'unknown' + lab['gfx_methods_on_final'] = L['gfx_on_last'] or 'unknown' + lab['ablation_events_in_log'] = len(L['passes']) + lab['cache_state_hint'] = None + if L and L['cache']: + h, m = L['cache'] + lab['cache_state_hint'] = (('shader-translation cache warm (misses=0, hits=%d)' % h) if m == 0 else + ('shader-translation cache COLD (all %d translated this run)' % m) if h == 0 else + ('shader-translation cache partly cold (misses=%d of %d)' % (m, h + m))) + lab['n_switches_listed'] = len(sw) + return lab, sw + + +def log_counters(L, t_from): + c = [x for x in L['counters'] if t_from is None or x['t'] >= t_from] + if len(c) < 2: + return {} + dp = c[-1]['presented'] - c[0]['presented'] + ds = c[-1]['started'] - c[0]['started'] + return {'submissions_per_presented_frame': r(ds / dp, 2) if dp else None, 'presented_in_span': dp, 'submissions_in_span': ds} + + +def summarise(path, a): + csv_path, log_path, name = find_inputs(path) + meta, rows, L = {}, [], None + if csv_path: + meta, rows = read_csv(csv_path) + if log_path: + L = read_log(log_path) + S = {'name': name, 'sources': {'csv': csv_path, 'log': log_path}, 'hardware': {k: meta.get(k) for k in ('cpu', 'gpu', 'driver', 'ram', 'os', 'display', 'version')}} + if rows: + wins = windows_from_csv(rows) + S['time_series'] = 'frametime.csv (1 s windows, exact per-window mean and max)' + elif L and L['frames']: + wins = windows_from_log(L['frames']) + S['time_series'] = 'log frame lines (windows ~1-5 s, no per-window max: tail figures unavailable)' + else: + S['error'] = 'no usable frame data' + return S + S['label'] = label_run(name, meta, L)[0] + S['label']['custom'] = a.label + S['t_start_utc'] = datetime.fromtimestamp(wins[0]['t'] / 1000, timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + ph = phases(wins, a.heavy_draws, a.warmup_s) + entry_i, entry_t = ph.pop('_entry_index'), ph.pop('_entry_t') + ph.pop('_t0') + S['phases'] = ph + body = wins[1:] if len(wins) > 1 else wins # first window has no dt + S['session'] = dist(body, 'whole session (boot, menu, load, play)') + S['session']['duration_s'] = r((wins[-1]['t'] - wins[0]['t']) / 1000, 1) + heavy = [x for x in wins if x['draws'] >= a.heavy_draws] + S['heavy_scene'] = dist(heavy, f'windows with mean draws/frame >= {a.heavy_draws}') + ref_h = (S['heavy_scene'] or {}).get('ms_median_reconstructed', (S['heavy_scene'] or {}).get('ms_median_windowavg')) + ref_s = S['session'].get('ms_median_reconstructed', S['session']['ms_median_windowavg']) + S['stalls_csv_windows'] = stalls_csv(body, a.stall_ms, ref_s, a.stall_rel) + if heavy: + S['heavy_scene']['stalls'] = stalls_csv(heavy, a.stall_ms, ref_h, a.stall_rel) + if entry_i is not None: + after = [x for x in wins[entry_i:] if x['t'] - wins[entry_i]['t'] >= a.warmup_s * 1000] + S['steady'] = dist(after, f'after heavy-scene entry + {a.warmup_s:.0f} s (all windows)') + if S['steady']: + S['steady']['stalls'] = stalls_csv(after, a.stall_ms, ref_h, a.stall_rel) + if rows: + S['columns_heavy'] = csv_columns(wins, heavy) + S['columns_session'] = csv_columns(wins, body) + # fraction of heavy windows with a GPU number: gpu_ms is only filled when GPU spans are on + if L: + S['log'] = {'seconds_logged': r((L['last_ts'] - L['first_ts']) / 1000, 1), 'warn_lines': L['warn'], 'error_lines': L['errors'], + 'shader_translations': L['translations'], 'shader_translate_ms_total': r(L['translate_ms'], 0), + 'stall_attribution': classify_stalls(L)} + t_from = entry_t if entry_t is not None else None + if L['frames']: + fl = [f for f in L['frames'] if t_from is None or f['t'] >= t_from] + if fl: + S['log']['frame_lines_heavy'] = {k: r(mean([f[k] for f in fl]), 2) for k in + ('fps', 'ms', 'prep_ms', 'copies_ms', 'copies_mb', 'tex_ms', 'tex_mb', 'gpu_ms', + 'copyback_ms', 'copyback_mb', 'draws', 'dropped')} + S['log']['frame_lines_heavy']['_lines'] = len(fl) + S['log']['per_frame_subsystems_heavy'] = sub_means(L, t_from) + S['log']['counters'] = log_counters(L, t_from) + S['log']['dstorage_mb_per_s_peak'] = r(max((d['mb_per_s'] for d in L['sub']['dstorage']), default=0), 1) + S['definitions'] = [ + f'stall window = CSV window whose slowest frame >= max({a.stall_ms:g} ms, {a.stall_rel:g} x the median ms/frame of its span) (threshold shown per span); stalled time is a lower bound (one max per window).', + 'watchdog stall = a `stall:` log line group (same frame number); length = largest stalled_ms; cause = `inside:` text.', + 'ms_*_windowavg: quantiles of the windows\' mean ms/frame weighted by frames (hides tails).', + 'ms_*_reconstructed: per window one frame at the logged max and the rest at the remaining mean; exact in frame count, ' + 'total time and window max, a model in between. 1% low = 1000/P99 (fps_1pct_low_p99) and mean fps of the slowest 1% frames.', + f'heavy scene = windows with mean draws/frame >= {a.heavy_draws}; world entry = 3 consecutive such windows; "stabilised" rule in phases.', + 'per_frame_subsystems_heavy = plain mean over log lines at/after world entry; each line is one window\'s per-frame figure; ' + 'subsystem ms are summed over threads (they can exceed the frame time).', + 'gpu_ms/gpu_pct (CSV) are 0 unless GPU timestamp spans are on; see columns_heavy._gpu_pct_windows_nonzero.', + ] + return S + + +# ----------------------------------------------------------------------------------------------- output +def fmt(v): + return '-' if v is None else (f'{v:g}' if isinstance(v, (int, float)) else str(v)) + + +def md(S): + o = [] + if 'error' in S: + return f"# {S['name']}\n\n{S['error']}\n" + lab = S['label'] + o.append(f"# Run summary: {S['name']}\n") + o.append(f"- start (UTC): {S['t_start_utc']} duration: {fmt(S['session']['duration_s'])} s time series: {S['time_series']}") + o.append(f"- sources: csv={S['sources']['csv']} log={S['sources']['log']}") + hw = S['hardware'] + if any(hw.values()): + o.append(f"- hardware: {fmt(hw['cpu'])} | {fmt(hw['gpu'])} | driver {fmt(hw['driver'])} | RAM {fmt(hw['ram'])} | {fmt(hw['os'])} | display {fmt(hw['display'])}") + o.append(f"- profile: {lab['console_profile']} build: {lab.get('build','unknown')} DLSS: {lab['dlss']} frame-gen: {lab['framegen']} " + f"resolution switch: {lab['resolution_switch']} panel: {lab['panel']} auto-A switch: {lab['auto_a_switch']}") + o.append(f"- shader cache: {fmt(lab.get('cache_state_hint'))}; passes off at end: {fmt(lab.get('passes_off_final'))}; graphics methods on at end: {fmt(lab.get('gfx_methods_on_final'))}; switch events in log: {fmt(lab.get('ablation_events_in_log'))}") + o.append('') + o.append('## Frame time\n') + o.append('| span | windows | frames | s | fps mean | ms mean | ms median | ms P90 | ms P99 | worst ms | 1% low fps (P99) |') + o.append('|---|---|---|---|---|---|---|---|---|---|---|') + for key in ('session', 'heavy_scene', 'steady'): + d = S.get(key) + if not d: + continue + med = d.get('ms_median_reconstructed', d['ms_median_windowavg']) + p90 = d.get('ms_p90_reconstructed', d['ms_p90_windowavg']) + p99 = d.get('ms_p99_reconstructed', d['ms_p99_windowavg']) + o.append(f"| {d['tag']} | {d['windows']} | {d['frames']} | {fmt(d['seconds'])} | {fmt(d['fps_mean'])} | {fmt(d['ms_mean'])} | " + f"{fmt(med)} | {fmt(p90)} | {fmt(p99)} | {fmt(d.get('ms_worst_frame'))} | {fmt(d.get('fps_1pct_low_p99'))} |") + o.append('') + o.append('## Phases\n') + for k, v in S['phases'].items(): + o.append(f'- {k}: {fmt(v)}') + o.append('') + st = S['stalls_csv_windows'] + o.append(f"## Stalls (CSV windows with a frame >= {st['threshold_ms']} ms for the session; per span below)\n") + o.append(f"- whole session: {st['stall_windows']} of {st['windows_total']} windows, >= {fmt(st['stalled_ms_lower_bound'])} ms stalled " + f"(lower bound), worst {fmt(st['worst_ms'])} ms, {st['over_1000ms_windows']} windows with a frame > 1 s") + for key in ('heavy_scene', 'steady'): + d = S.get(key) + if d and d.get('stalls'): + s = d['stalls'] + o.append(f"- {key} (threshold {fmt(s['threshold_ms'])} ms): {s['stall_windows']} of {s['windows_total']} windows, >= {fmt(s['stalled_ms_lower_bound'])} ms, worst {fmt(s['worst_ms'])} ms") + if 'log' in S: + sa = S['log']['stall_attribution'] + o.append(f"- watchdog (log): {sa['watchdog_stalls']} stalls, {sa['watchdog_ms_total']} ms, worst {sa['watchdog_worst_ms']} ms") + for k, v in list(sa['by_inside'].items())[:6]: + o.append(f" - {v['count']}x {v['ms']} ms (worst {v['worst_ms']}): {k}") + o.append('') + if S.get('columns_heavy'): + o.append('## CSV columns, heavy scene (frame-weighted means per frame)\n') + o.append('| column | mean |') + o.append('|---|---|') + for k, v in S['columns_heavy'].items(): + o.append(f'| {k} | {fmt(v)} |') + o.append('') + if 'log' in S: + lg = S['log'] + o.append('## Log, from world entry on\n') + o.append(f"- log span {fmt(lg['seconds_logged'])} s, WARN lines {lg['warn_lines']}, ERROR lines {lg['error_lines']}, " + f"shader translations {lg['shader_translations']} ({fmt(lg['shader_translate_ms_total'])} ms total), peak DirectStorage {fmt(lg['dstorage_mb_per_s_peak'])} MB/s") + if lg.get('frame_lines_heavy'): + o.append(f"- frame lines: {json.dumps(lg['frame_lines_heavy'])}") + if lg.get('counters'): + o.append(f"- submissions: {json.dumps(lg['counters'])}") + o.append('') + for k, v in lg['per_frame_subsystems_heavy'].items(): + o.append(f'- {k}: {json.dumps(v)}') + o.append('') + o.append('## Definitions\n') + for d in S['definitions']: + o.append(f'- {d}') + return '\n'.join(o) + '\n' + + +HEADLINE = [ + ('heavy_scene.fps_mean', 'heavy: fps mean'), ('heavy_scene.ms_mean', 'heavy: ms mean'), + ('heavy_scene.ms_median_reconstructed', 'heavy: ms median'), ('heavy_scene.ms_p90_reconstructed', 'heavy: ms P90'), + ('heavy_scene.ms_p99_reconstructed', 'heavy: ms P99'), ('heavy_scene.fps_1pct_low_p99', 'heavy: 1% low fps'), + ('heavy_scene.stalls.stall_windows', 'heavy: stall windows'), ('heavy_scene.stalls.stalled_ms_lower_bound', 'heavy: stalled ms (>=)'), + ('session.fps_mean', 'session: fps mean'), ('session.ms_p99_reconstructed', 'session: ms P99'), + ('stalls_csv_windows.stall_windows', 'session: stall windows'), ('stalls_csv_windows.stalled_ms_lower_bound', 'session: stalled ms (>=)'), + ('phases.seconds_to_heavy_scene', 'seconds to heavy scene'), ('phases.stabilised_after_entry_s', 'seconds entry->stable'), + ('columns_heavy.cpu_prepare_ms', 'CPU prepare ms/frame'), ('columns_heavy.gpu_ms', 'GPU ms/frame (CSV)'), + ('columns_heavy.draws', 'draws/frame'), ('columns_heavy.copies_mb', 'copies MB/frame'), ('columns_heavy.textures_mb', 'texture MB/frame'), + ('columns_heavy.copyback_mb', 'copy-back MB/frame'), ('columns_heavy.card_sent_mb', 'card sent MB/frame'), + ('columns_heavy.ram_mb_max', 'RAM max MB'), + ('log.counters.submissions_per_presented_frame', 'submissions/presented frame'), + ('log.per_frame_subsystems_heavy.desc_slots.slots_looked_at', 'descriptor slots looked at/frame'), + ('log.per_frame_subsystems_heavy.desc_slots.slots_mirrored', 'descriptor slots mirrored/frame'), + ('log.per_frame_subsystems_heavy.card_clock.card_busy_pct_by_count', 'card busy % (log count)'), + ('log.per_frame_subsystems_heavy.activity.present_ms', 'present ms/frame (thread sum)'), + ('log.per_frame_subsystems_heavy.prep_split.before_steps_ms', 'prep: before steps ms'), + ('log.per_frame_subsystems_heavy.prep_split.card_copies_ms', 'prep: card copies ms'), + ('log.stall_attribution.watchdog_stalls', 'watchdog stalls'), +] + + +def dig(d, path): + for p in path.split('.'): + if not isinstance(d, dict) or p not in d: + return None + d = d[p] + return d + + +def compare(A, B, a): + o = [f"# A/B: {A['name']} (A) vs {B['name']} (B)\n", + f"- A: {json.dumps({k: A['label'].get(k) for k in ('console_profile','dlss','framegen','resolution_switch','panel')})}", + f"- B: {json.dumps({k: B['label'].get(k) for k in ('console_profile','dlss','framegen','resolution_switch','panel')})}", + '- differences under ~5 % are noise (docs/findings.md); scenes differ run to run.\n', + '| metric | A | B | B-A | % |', '|---|---|---|---|---|'] + for path, name in HEADLINE: + x, y = dig(A, path), dig(B, path) + if x is None and y is None: + continue + if isinstance(x, (int, float)) and isinstance(y, (int, float)): + pct = f'{100 * (y - x) / x:+.1f}' if x else '-' + o.append(f'| {name} | {fmt(x)} | {fmt(y)} | {y - x:+.2f} | {pct} |') + else: + o.append(f'| {name} | {fmt(x)} | {fmt(y)} | - | - |') + return '\n'.join(o) + '\n' + + +def first(S, *paths): + for p in paths: + v = dig(S, p) + if v is not None: + return v + return None + + +def index_md(Ss): + cols = [('heavy fps', ('heavy_scene.fps_mean',)), + ('heavy ms med', ('heavy_scene.ms_median_reconstructed', 'heavy_scene.ms_median_windowavg')), + ('heavy ms P99', ('heavy_scene.ms_p99_reconstructed', 'heavy_scene.ms_p99_windowavg')), + ('heavy stall win', ('heavy_scene.stalls.stall_windows',)), + ('sess fps', ('session.fps_mean',)), ('s to heavy', ('phases.seconds_to_heavy_scene',)), + ('cpu prep ms', ('columns_heavy.cpu_prepare_ms',)), ('draws/f', ('columns_heavy.draws',)), + ('watchdog stalls', ('log.stall_attribution.watchdog_stalls',)), + ('watchdog ms', ('log.stall_attribution.watchdog_ms_total',))] + o = ['| run | profile | DLSS | framegen | passes off at end | dur s | ' + ' | '.join(c[0] for c in cols) + ' |', + '|' + '---|' * (6 + len(cols))] + vals = [[] for _ in cols] + for S in Ss: + if 'error' in S: + o.append(f"| {S['name']} | error |") + continue + l = S['label'] + row = [] + for i, (_, ps) in enumerate(cols): + v = first(S, *ps) + row.append(fmt(v)) + if isinstance(v, (int, float)): + vals[i].append(v) + o.append(f"| {S['name']} | {l['console_profile']} | {l['dlss']} | {l['framegen']} | {fmt(l.get('passes_off_final'))} | " + f"{fmt(S['session']['duration_s'])} | " + ' | '.join(row) + ' |') + for nm, fn in (('MEDIAN of runs', lambda v: sorted(v)[len(v) // 2]), ('MIN', min), ('MAX', max)): + o.append(f'| **{nm}** | | | | | | ' + ' | '.join(fmt(r(fn(v), 2)) if v else '-' for v in vals) + ' |') + return '\n'.join(o) + '\n' + + +def load_any(p, a): + if p.endswith('.summary.json') or (p.endswith('.json') and os.path.isfile(p)): + return json.load(open(p, encoding='utf-8')) + return summarise(p, a) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('paths', nargs='*') + ap.add_argument('--out', help='folder for <name>.summary.json and <name>.summary.md (default: print markdown)') + ap.add_argument('--label', help='free text stored in the summary (e.g. "cold, A pressed at 12 s, scenario S1")') + ap.add_argument('--stall-ms', type=float, default=200.0) + ap.add_argument('--stall-rel', type=float, default=3.0, help='also require max >= this x the span median') + ap.add_argument('--heavy-draws', type=float, default=1000.0) + ap.add_argument('--warmup-s', type=float, default=30.0) + ap.add_argument('--compare', nargs=2, metavar=('A', 'B')) + ap.add_argument('--latest', nargs='?', const=1, type=int) + a = ap.parse_args() + if a.compare: + A, B = load_any(a.compare[0], a), load_any(a.compare[1], a) + txt = compare(A, B, a) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, 'compare.md'), 'w', encoding='utf-8').write(txt) + print(txt) + return 0 + paths = [] + for q in a.paths: + paths += sorted(glob.glob(q)) if any(c in q for c in '*?[') else [q] + if a.latest: + base = os.path.join(os.environ.get('LOCALAPPDATA', ''), 'victory', 'runs') + paths += sorted(d for d in glob.glob(os.path.join(base, '*')) if os.path.isfile(os.path.join(d, 'victory.log')))[-a.latest:] + if not paths: + ap.error('no input') + rc = 0 + allS = [] + for p in paths: + S = summarise(p, a) + if a.out: + os.makedirs(a.out, exist_ok=True) + base = re.sub(r'[^\w.-]+', '_', S['name']) + json.dump(S, open(os.path.join(a.out, base + '.summary.json'), 'w', encoding='utf-8'), indent=1) + open(os.path.join(a.out, base + '.summary.md'), 'w', encoding='utf-8').write(md(S)) + else: + sys.stdout.reconfigure(encoding='utf-8') + print(md(S)) + rc |= 1 if 'error' in S else 0 + allS.append(S) + if a.out and len(allS) > 1: + open(os.path.join(a.out, 'index.md'), 'w', encoding='utf-8').write(index_md(allS)) + return rc + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1 index a7afa7270..840d3bacf 100644 --- a/scripts/play-foxhound.ps1 +++ b/scripts/play-foxhound.ps1 @@ -74,8 +74,6 @@ $settings = @{ VICTORY_CARD_REHASH_RUNS = '1'; VICTORY_JOIN_COPIES = '1'; VICTORY_CARD_STEPS = '2'; VICTORY_CARD_AWAKE = '1' VICTORY_CARD_BUFFERS_MIN_KB = '64'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_INDIRECT_BATCH = '2' VICTORY_UPLOAD_AHEAD = '1'; VICTORY_SHOW_AFTER = '1'; VICTORY_MAP_THREADS = '1' - # Shader writes into big write-combined copies stay on the card (-5 ms a frame) - VICTORY_WC_NO_BACK = '1'; VICTORY_WC_NO_BACK_MIN_KB = '1024' # The title's page-mapping copies kept without Windows views (no cutscene freezes at scene cuts) VICTORY_SOFT_VIEWS = 'copies' # Textures: pool with no blocks made ahead, 16 ms a pass, no catch-up, levels not on demand (sharp)