From 8dd30ab472697c47b141c273c2a00f8ce1c00520 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:44:25 -0500 Subject: [PATCH 01/16] A write through one view of a page is seen at its other views; page writes counted; levels on demand (off); warm-up; card memory numbers Memory sync: - The guard over every view of a physical page (code by myokex, victory-amd c6dc4d8, after pull request #115 by Spexivus, its correction by joroyt and a part of VIctory #1122 by tightfall): the title shows one page at several addresses and a copy was guarded at one only. 0.8 to 1.0 million writes through another view in a five-minute run on the test machine. VICTORY_VIEW_GUARD=0 turns it off. - Kernel reads into title memory are read beside and copied in (Joshua Odom, 10ea38e). - Writes of the storage layer into physical pages are counted where the title has the pages mapped and can open the guards there (VICTORY_PAGE_WRITES, off: counted only). Failed page-destination reads are retried. Card memory: - Levels on demand, off unless VICTORY_LEVELS_ON_DEMAND=1: a texture the title fills takes card memory for the levels the title holds; held levels get memory only while the card has room and are asked for again. Its test runs on the software adapter; not run on a card yet. - Refused texture slots are held back so a pass reaches the slots behind them; room can be kept for card copies of title buffers (off). Tools: translate --warm all; the shader cache is keyed on the translator's source; counters for copy-back races, page writes and the copies the texture sweep never lets go; a walls trace. Game runs of these changes on an RTX 4070: five five-minute runs without a device loss or a failed request. This merged tree was built; its test suites were run on the tree the changes come from (gpu 129, hle 97). Co-Authored-By: Claude Fable 5.2 --- README.md | 48 + apps/victory/src/main.rs | 11 + apps/victory/src/translate.rs | 81 ++ crates/victory-formats/src/texture.rs | 147 +- crates/victory-gpu/src/copystat.rs | 22 + crates/victory-gpu/src/descriptor.rs | 44 +- crates/victory-gpu/src/descriptor/host.rs | 514 ++++++- crates/victory-gpu/src/draw.rs | 51 +- crates/victory-gpu/src/host.rs | 26 +- crates/victory-gpu/src/inplace.rs | 100 +- crates/victory-gpu/src/lib.rs | 5 +- crates/victory-gpu/src/list.rs | 10 + crates/victory-gpu/src/resource.rs | 314 +++- crates/victory-gpu/src/shader_cache.rs | 108 +- crates/victory-gpu/src/shadow.rs | 538 ++++++- crates/victory-gpu/src/texture.rs | 266 +++- crates/victory-gpu/src/tiles.rs | 1419 +++++++++++++++++++ crates/victory-gpu/src/watch.rs | 364 ++++- crates/victory-hle/src/modules/d3d12x.rs | 13 + crates/victory-hle/src/modules/dstorage.rs | 85 +- crates/victory-hle/src/modules/files.rs | 75 +- crates/victory-hle/src/modules/gameinput.rs | 2 +- crates/victory-hle/src/modules/xmem.rs | 125 ++ crates/victory-shader/build.rs | 65 + crates/victory-shader/src/emit/mod.rs | 27 + 25 files changed, 4219 insertions(+), 241 deletions(-) create mode 100644 crates/victory-gpu/src/tiles.rs create mode 100644 crates/victory-shader/build.rs diff --git a/README.md b/README.md index 7dc43e24..8c99e406 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,12 @@ developer or publisher. - **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors (GPL-2.0-only) was used as a reference for how the same title behaves under another layer. Fixes inspired by it were written anew in VIctory's code. +- The guard over every view of a memory page is code by **myokex** + ([victory-amd](https://github.com/myokex/victory-amd), commit `c6dc4d8`), which + adapts pull request #115 here by Spexivus, its correction by joroyt and a part of + VIctory #1122 by tightfall. The read-beside fix for kernel reads into title + memory is by **Joshua Odom** (commit `10ea38e` of the same fork family). Both + are carried here unchanged apart from one merge conflict. - This fork's changes were developed with [Claude Code](https://claude.com/claude-code). ## Status of this fork (2026-11-25) @@ -38,6 +44,48 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, | Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | | Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) | +### Newest (2026-11-25, later the same day) + +Memory sync between the title's memory and the copies on the card: +- **A write through one view of a physical page is seen by the copies taken + through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title + shows one page at several addresses and a copy was guarded at one of them + only. Measured on the test machine: 0.8 to 1.0 million such writes in a + five-minute run, every one of which used to leave a copy stale. Since it + went in, the first room had its walls in the later frames of 4 runs out of + 4 (2 of 5 before); the room's very first shot still comes up without walls + in some runs. +- Kernel reads into title memory are read beside and copied in, so a block + guarded again in between no longer fails the read. +- Writes of the storage layer into physical pages are counted where the title + has those pages mapped (10,000 to 50,000 guarded blocks of copies lay under + them in every run) and can open the guards there: + `VICTORY_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more). +- Failed page-destination reads are retried (`VICTORY_DSTORAGE_RETRIES=0` = as before). + +Card memory (the test card is full from the first frame of the world: 85 to +99 % of its budget for a whole run, about 26,000 texture copies let go and +3,400 made again in five minutes, 2.8 GB of render targets that are all in +use): +- Levels on demand, **off by default** (`VICTORY_LEVELS_ON_DEMAND=1`): a + texture the title fills takes card memory only for the levels the title + holds (2.2 to 3.0 GB of the copies were levels it does not hold). Its test + runs on the software adapter; it has not run on a card yet. +- Refused texture slots are held back for a few seconds so that a pass + reaches the slots behind them (`VICTORY_FULL_CARD_PASS=0` = as before); + room can be kept for the card copies of title buffers + (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`, off). + +Tools and diagnostics: +- `victory translate --warm all --jobs N` translates every + shader ahead of a run, on the processor only (about 4.5 to 6.5 minutes + here); the shader cache is keyed on the translator's source, so a new + build that does not touch the translator starts warm. +- Counters, all off or diagnostics-only: `VICTORY_MERGE_RACE=1` (title bytes + a copy-back is about to put back to older values: none found in 138,000 + copy-backs), `VICTORY_WALLS_TRACE`, `VICTORY_CARD_ACCOUNTING`, and a census + of the copies the texture sweep never lets go. + ### What this fork changed (summary) Rendering: diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 842ce773..ead9f7c8 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -84,6 +84,13 @@ enum Command { /// Worker threads (default: every logical core). #[arg(long)] jobs: Option, + /// Warm the run's shader cache: a file of shader hashes (the 16 + /// hex digits a run's log names a shader by, anywhere in a line); + /// the containers with those hashes are translated into the + /// cache and nothing else is done. Set `VICTORY_HOST_WAVE` and + /// `VICTORY_VIEW_LIMIT` to what the run's log says of the host. + #[arg(long)] + warm: Option, }, /// Prepare, map and bind a title executable; with --execute, run it. Run { @@ -152,6 +159,7 @@ fn main() -> Result<()> { pipelines, list, jobs, + warm, } => { // `VICTORY_VIEW_LIMIT=`: translate as on a host whose view heap is capped if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { @@ -161,6 +169,9 @@ fn main() -> Result<()> { if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { victory_shader::emit::set_host_max_wave(n); } + if let Some(file) = warm { + return translate::warm(paths, &file, jobs); + } translate::run(paths, validate, pipelines, list, jobs) } Command::Run { diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 1d13ae2c..640d2109 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -152,6 +152,87 @@ struct Checks { host: Option<(Host, emit::HostShader)>, } +/// `translate --warm `: the containers whose hash the file names are +/// translated into the run's shader cache, on `jobs` threads; nothing is +/// made on the GPU. A run of the title then finds them there instead of +/// translating each at its first use. +pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> { + // `--warm all`: every container found, whatever its hash. + let all = file.as_os_str() == "all"; + let mut wanted: HashSet = HashSet::new(); + if !all { + let text = std::fs::read_to_string(file)?; + for line in text.lines() { + for word in line.split(|c: char| !c.is_ascii_hexdigit()) { + if word.len() == 16 { + wanted.insert(word.to_ascii_lowercase()); + } + } + } + anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display()); + } + // `VICTORY_WARM_SECONDS=`: stop taking new shaders after n seconds + // (what is done stays in the cache; the next warm-up goes on from there). + let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::().ok()); + let cfg = victory_core::Config::load()?; + victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + let paths = crate::default_paths(paths)?; + let threads = jobs.unwrap_or(4).max(1); + let began = std::time::Instant::now(); + let done = Mutex::new(HashSet::new()); + let counts = [const { AtomicUsize::new(0) }; 5]; + for root in &paths { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Some(bytes) = job.bytes() else { + continue; + }; + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { + counts[3].fetch_add(1, Ordering::Relaxed); + break; + } + if (!all && !wanted.contains(&hash)) || !lock(&done).insert(hash) { + continue; + } + let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(1000) { + println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64()); + } + let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) { + Ok(true) => 0, + Ok(false) => 1, + Err(_) => 2, + }; + counts[which].fetch_add(1, Ordering::Relaxed); + } + }); + } + }); + } + } + let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed)); + let asked = if all { "all".to_owned() } else { wanted.len().to_string() }; + let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" }; + println!( + "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}", + translated + there + failed, + began.elapsed().as_secs_f64() + ); + Ok(()) +} + pub fn run( paths: Vec, validate: bool, diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index a1f72e43..fa719c93 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -594,9 +594,7 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }) + self.walk::(tiled, linear, mip, slice, row_pitch, depth_pitch) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -609,22 +607,19 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }) + self.walk::(linear, tiled, mip, slice, row_pitch, depth_pitch) } - /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). + /// Copies contiguous runs in one direction between the two layouts. #[allow(clippy::too_many_arguments)] - fn walk( + fn walk( &self, - tiled_len: usize, + src: &[u8], + dst: &mut [u8], mip: u32, slice: u32, - linear_len: usize, row_pitch: usize, depth_pitch: usize, - mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -650,6 +645,11 @@ impl Layout { .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) .and_then(|offset| offset.checked_add(bytes)) .ok_or(Error::TooSmall)?; + let (tiled_len, linear_len) = if DETILE { + (src.len(), dst.len()) + } else { + (dst.len(), src.len()) + }; if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } @@ -672,12 +672,12 @@ impl Layout { runs.push((first_tiled, first_linear, bytes - first_linear)); } // A mip can end partway through the last run. Check the other runs - // once so each row can copy them with a compile-time length. + // once so each row can copy them as fixed-size chunks. let (body, last) = runs.split_at(runs.len().saturating_sub(1)); - let run_len = body - .first() - .map(|run| run.2) - .filter(|&len| body.iter().all(|run| run.2 == len)); + let chunk_size = body.first().map(|run| run.2).filter(|&size| { + body.iter() + .all(|&(offset, _, len)| len == size && offset.is_multiple_of(size)) + }); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -685,16 +685,22 @@ impl Layout { let linear_row = z as usize * depth_pitch + y as usize * row_pitch; if linear { let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); + copy_run::(src, dst, tiled_row as usize, linear_row, bytes); } else { let tiled_row = (base + self.row(m, y, inner)) as usize; - match run_len { - Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), - Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), - Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy), - _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy), + match chunk_size { + Some(8) if tiled_row.is_multiple_of(8) => { + copy_runs::<8, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(16) if tiled_row.is_multiple_of(16) => { + copy_runs::<16, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(32) if tiled_row.is_multiple_of(32) => { + copy_runs::<32, DETILE>(src, dst, body, tiled_row, linear_row) + } + _ => copy_runs::<0, DETILE>(src, dst, body, tiled_row, linear_row), } - copy_runs::<0>(last, tiled_row, linear_row, &mut copy); + copy_runs::<0, DETILE>(src, dst, last, tiled_row, linear_row); } } } @@ -702,16 +708,47 @@ impl Layout { } } -/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0. -fn copy_runs( +fn copy_run( + src: &[u8], + dst: &mut [u8], + tiled: usize, + linear: usize, + len: usize, +) { + let (from, to) = if DETILE { + (tiled, linear) + } else { + (linear, tiled) + }; + dst[to..][..len].copy_from_slice(&src[from..][..len]); +} + +/// A row of equal runs is contiguous in linear memory. Treat it as a +/// slice of arrays so only the tiled chunk needs a bounds check per copy. +/// Use the byte ranges for irregular runs and the last run of each row. +fn copy_runs( + src: &[u8], + dst: &mut [u8], runs: &[(usize, usize, usize)], tiled_row: usize, linear_row: usize, - copy: &mut impl FnMut(usize, usize, usize), ) { - for &(tiled, linear, len) in runs { - let len = if N == 0 { len } else { N }; - copy(tiled_row + tiled, linear_row + linear, len); + if N == 0 { + for &(tiled, linear, len) in runs { + copy_run::(src, dst, tiled_row + tiled, linear_row + linear, len); + } + } else if DETILE { + let tiled = src.as_chunks::().0; + let linear = dst[linear_row..][..runs.len() * N].as_chunks_mut::().0; + for (out, &(offset, ..)) in linear.iter_mut().zip(runs) { + *out = tiled[(tiled_row + offset) / N]; + } + } else { + let tiled = dst.as_chunks_mut::().0; + let linear = src[linear_row..][..runs.len() * N].as_chunks::().0; + for (input, &(offset, ..)) in linear.iter().zip(runs) { + tiled[(tiled_row + offset) / N] = *input; + } } } @@ -968,6 +1005,58 @@ mod tests { } } + #[test] + fn tiled_chunks_match_element_offsets_with_odd_row_pitches() { + for swizzle in [ + Swizzle::SW_256B_S, + Swizzle::SW_256B_D, + Swizzle::SW_4KB_S, + Swizzle::SW_4KB_D, + Swizzle::SW_64KB_S, + Swizzle::SW_64KB_D, + ] { + for n in [1, 2, 4, 8, 16] { + let l = Layout::new(&Desc { + depth: 2, + ..desc(73, 39, 7, n, swizzle) + }) + .unwrap(); + let n = n as usize; + let tiled: Vec<_> = (0..l.size) + .map(|i| (i.wrapping_mul(0x9e37_79b9) >> 24) as u8) + .collect(); + let mut retiled = vec![0xbb; tiled.len()]; + let mut expected_tiled = retiled.clone(); + for slice in 0..l.slices { + for (mip, m) in l.mips.iter().enumerate() { + let mip = mip as u32; + let bytes = m.width as usize * n; + let pitch = bytes + 3; + // Keep padding between rows, with exactly the active + // bytes in the last row. + let len = (m.height as usize - 1) * pitch + bytes; + let mut linear = vec![0xcc; len]; + let mut expected = linear.clone(); + for y in 0..m.height { + for x in 0..m.width { + let src = l.offset(mip, x, y, slice).unwrap() as usize; + let dst = y as usize * pitch + x as usize * n; + expected[dst..][..n].copy_from_slice(&tiled[src..][..n]); + expected_tiled[src..][..n].copy_from_slice(&tiled[src..][..n]); + } + } + l.detile(&tiled, mip, slice, &mut linear, pitch, len) + .unwrap(); + assert_eq!(linear, expected, "{swizzle:?} {n} mip {mip} slice {slice}"); + l.tile(&mut retiled, mip, slice, &expected, pitch, len) + .unwrap(); + } + } + assert_eq!(retiled, expected_tiled, "{swizzle:?} {n}"); + } + } + } + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 204b6c45..ba56d635 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -743,6 +743,22 @@ fn log_memory() { mb(card[0]), mb(card[3]), ); + let targets = crate::resource::targets_census(); + tracing::info!( + "host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB", + targets[0], + mb(targets[1]), + targets[10], + mb(targets[11]), + targets[2], + mb(targets[3]), + targets[4], + mb(targets[5]), + targets[6], + mb(targets[7]), + targets[8], + mb(targets[9]), + ); tracing::info!( "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ @@ -1121,6 +1137,12 @@ pub(crate) fn log(frames: f64) { c[C::GpuWritesLeftOut as usize], mb(c[C::GpuWritesLeftOutBytes as usize]), ); + let [together, written, mapped] = + [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ + {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" + ); // Where the wall clock of a frame goes: the phases of a frame, the // processor time of the whole process, and what each submitting and // recording thread did. diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 84850149..9305bf56 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -353,7 +353,11 @@ struct Views { shape_index: std::collections::BTreeMap, } -static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views { +/// Read far more often than written: every slot a draw reads through a +/// table is looked up here, on several recording threads at once in the +/// world. Readers share it; only a view not seen before (a new table entry +/// or shape) and a released resource take it alone. +static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { list: Vec::new(), index: std::collections::BTreeMap::new(), by_resource: std::collections::BTreeMap::new(), @@ -480,6 +484,12 @@ impl Views { Some(View::Placed(unordered, resource, desc)) } + /// 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]) + } + /// 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] { @@ -522,8 +532,10 @@ fn words_for(view: View) -> [u32; 2] { View::Placed(unordered, resource, desc) => { let (shape, address) = shape_of(*unordered, resource, desc); if address >> PLACED_ADDRESS_BITS == 0 { - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(shape) = views.shape(shape) { + // 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)); + if let Some(shape) = shape { NAMED_WHOLE[1].fetch_add(1, Relaxed); return placed_words(shape, address); } @@ -532,7 +544,19 @@ fn words_for(view: View) -> [u32; 2] { _ => {} } } - VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view) + // A view written before keeps its entry and generation. + if let Some(words) = views_read().entry_of(&view) { + return words; + } + views_write().entry(view) +} + +fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) } /// For the memory line: the distinct views kept ([`Views`]), those of them @@ -546,7 +570,7 @@ fn words_for(view: View) -> [u32; 2] { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn views_kept() -> [u64; 8] { use std::sync::atomic::Ordering::Relaxed; - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let views = views_read(); let each = size_of::<(View, u32)>() as u64; let shape = size_of::() as u64; let (mut constants, mut placed) = (0, 0); @@ -697,7 +721,7 @@ pub(crate) fn forget(resource: usize) { .lock() .unwrap_or_else(|e| e.into_inner()) .remove(&resource); - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let mut views = views_write(); let Some(entries) = views.by_resource.remove(&resource) else { return; }; @@ -722,12 +746,12 @@ pub(crate) fn forget(resource: usize) { fn view_at(i: u32, generation: u32) -> Option { match generation >> KIND_SHIFT { 0 => { - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let views = views_read(); let (view, current) = views.list.get(i as usize)?; (*current == generation).then(|| view.clone()) } CONSTANT => Some(constant_of(i, generation)), - PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation), + PLACED => views_read().placed_of(i, generation), _ => None, } } @@ -1104,8 +1128,8 @@ mod tests { View::Placed(_, r, _) => *r == resource, _ => false, }; - let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); - let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + 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(); 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 7b18b458..49e4ca1d 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -85,7 +85,66 @@ pub(crate) struct HostHeap { /// by slot and by address ([`Spans`]): which slots a newer view of /// other memory there makes stale, and which to look at again when the /// runtime maps, unmaps or writes memory ([`remapped`]). - placed: Mutex, + placed: std::sync::Arc>, +} + +/// The spans of every view heap made ([`HostHeap::placed`]), for the +/// texture code, which has no heap at hand ([`next_start`], +/// [`first_viewed`]). +static PLACED_SPANS: Mutex>>> = Mutex::new(Vec::new()); + +/// Where the next texture placed inside `[start, end)` starts, past the +/// first bytes of the one at `start` ([`HEAD`]): what is there of the +/// texture at `start` ends there, whatever its full size. `None`: no view +/// in a slot shaders pick by index describes memory in that range. +pub(crate) fn next_start(start: u64, end: u64) -> Option { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end)) + .min() +} + +/// The lowest level that a view of the placed texture at `start` shows, +/// over the slots shaders pick by index that hold one now. The title +/// views a texture from the first level it holds. `None`: no such slot. +pub(crate) fn first_viewed(start: u64) -> Option { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start)) + .min() +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose first level with memory changed since a texture pass last took +/// them ([`HostHeap::texture_views_remade`]). +static RESHOWN: Mutex> = Mutex::new(Vec::new()); + +/// The first level with memory of the placed texture at `start` changed: +/// its slots are made again at the next texture pass. +pub(crate) fn levels_changed(start: u64) { + RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose last upload left a held level without tiles (the card had no +/// room, or no heap could be had), and when (`crate::host::moment`). A +/// texture pass makes their slots due again once the card has room +/// ([`HostHeap::texture_slots_waiting`]). +static WAITING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + +/// The last upload of the placed texture at `start` left a held level +/// without tiles. A texture picked by index is uploaded once and then +/// only when its memory is found changed, and its staging buffer goes +/// with the upload: without this the level stayed empty (the texture +/// blurred, or black if no level had tiles) for as long as the title left +/// its memory alone, where a texture refused for want of room is tried +/// again. +pub(crate) fn levels_waiting(start: u64) { + WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment()); } /// Title memory by the placed texture views that describe it: per span of @@ -110,6 +169,8 @@ pub(crate) struct Spans { rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, + /// The level each slot's view starts at ([`Spans::shows`]). + first: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked /// out once for each (a title writes the views of a few thousand /// descriptions, thousands of times a frame). @@ -227,8 +288,30 @@ impl Spans { stale } + /// The view in slot `index` starts at level `first` of its texture. + fn shows(&mut self, index: u32, first: u32) { + self.first.insert(index, first); + } + + /// The lowest level a view of the texture at `start` starts at. + fn first_viewed(&self, start: u64) -> Option { + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + } + + /// The first span that starts inside `[start, end)` past the first + /// [`HEAD`] bytes of it. + fn next_start(&self, start: u64, end: u64) -> Option { + self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at) + } + + /// The slots that hold a view of the texture at `start`. + fn slots_at(&self, start: u64) -> Vec { + self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default() + } + /// Slot `index` holds no placed texture view any more. fn forget(&mut self, index: u32) { + self.first.remove(&index); let Some(start) = self.by_slot.remove(&index) else { return; }; @@ -248,6 +331,76 @@ impl Spans { .flat_map(|span| span.1.iter().copied()) .collect() } + + /// The slots of the textures that hold bytes of `[start, end)`, for a + /// write there: as [`Spans::slots_in`], but when a texture starts at + /// `start` itself the one before it is left out (it ends where that + /// one starts, and a request that fills a texture begins at its first + /// byte: `slots_in` would name its neighbour with every such write). + fn slots_holding(&self, start: u64, end: u64) -> Vec { + if end <= start { + return Vec::new(); + } + let before = if self.by_start.contains_key(&start) { + None + } else { + self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span) + }; + before + .into_iter() + .chain(self.by_start.range(start..end).map(|(_, span)| span)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } +} + +/// Title memory written behind the guards' back whose bytes are there +/// (DirectStorage's reads into physical pages, at the addresses the title +/// has them mapped; `crate::watch::title_memory_written`), since a texture +/// pass last took the ranges ([`page_written`]). Kept apart from +/// [`REMAPPED`] so that what such writes do is counted by itself. +static PAGE_WRITTEN: Mutex> = Mutex::new(Vec::new()); + +/// Since the start: such ranges kept for a pass; ranges dropped because no +/// pass took them; slots of placed textures that held bytes of them when a +/// pass took them; of those, the slots whose texture had been uploaded +/// before the write (out of the queue, or in it after an upload): they are +/// the ones that kept the bytes from before, and the ones made due when +/// `VICTORY_PAGE_WRITES` asks for it. +pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Frames from the pass that takes a written range to the look at its +/// slots: the levels of one texture arrive in a few requests, and a look +/// two frames on takes those of the next frame with it. +const PAGE_WRITE_AFTER: u64 = 2; + +/// The bytes of a write the guards do not see are in title memory `[at, +/// at + len)`: the placed textures there changed with no descriptor +/// written and nothing mapped. Kept for the next texture pass +/// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its +/// ranges; locks one mutex and calls nothing. +pub(crate) fn page_written(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. + const MOST: usize = 1 << 15; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + PAGE_WRITES[0].fetch_add(1, Relaxed); + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed); + ranges.clear(); + } + ranges.push((start, end)); } /// Title memory the runtime mapped, unmapped or is about to write since a @@ -373,6 +526,10 @@ struct Waiting { pub(crate) struct TextureQueue { slots: std::collections::BTreeMap, writes: u64, + /// Slots held back because the card had no room for the host copy + /// they need ([`TextureQueue::hold`]), each with the write it was + /// held as. + held: std::collections::BTreeMap, } impl TextureQueue { @@ -449,6 +606,37 @@ impl TextureQueue { } } + /// The card has no room for the host copy slot `index` needs: it is + /// not handed out again before frame `due`, or before the card has + /// room again ([`TextureQueue::room`]). Nothing else of it changes: it + /// is not a slot "waiting for its memory", and when it is due it has + /// its old place among the slots never looked at. (It stayed due, so + /// every pass on a full card looked at the same few hundred slots + /// again and stopped there, and the slots behind them were never + /// reached: the ones whose host copy exists and only wants bringing up + /// to date, and the ones whose memory went, which is what lets host + /// copies go and makes room.) + fn hold(&mut self, index: u32, write: u64, due: u64) { + if let Some(w) = self.same(index, write) { + w.due = w.due.max(due); + self.held.insert(index, write); + } + } + + /// The card has room again at `frame`: the slots held back for lack of + /// it are due now, as if they had never been held. Returns how many. + fn room(&mut self, frame: u64) -> usize { + let held = std::mem::take(&mut self.held); + let mut back = 0; + for (index, write) in held { + if let Some(w) = self.same(index, write) { + w.due = w.due.min(frame); + back += 1; + } + } + back + } + /// Slot `index` was uploaded with `mapped` bytes of its memory there, /// not all of it: looked at again from frame `due`. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { @@ -770,7 +958,16 @@ impl HostHeap { tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), - placed: Mutex::default(), + placed: { + let spans = std::sync::Arc::>::default(); + if !sampler { + PLACED_SPANS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(std::sync::Arc::downgrade(&spans)); + } + spans + }, }; // A slot never written is undefined: shaders reading one (a slot // the title wrote in a way we do not know, or a table entry no @@ -981,6 +1178,16 @@ impl HostHeap { textures.later(index, write, frame, most); } + /// See [`TextureQueue::hold`]. + pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + } + + /// See [`TextureQueue::room`]. + pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + } + /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { @@ -999,6 +1206,7 @@ impl HostHeap { /// whose pass runs first takes them (a title has one view heap). pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { use std::sync::atomic::Ordering::Relaxed; + self.texture_slots_page_written(frame); let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); if ranges.is_empty() { return 0; @@ -1018,6 +1226,54 @@ impl HostHeap { slots.len() } + /// Takes the ranges of title memory written behind the guards' back + /// since the last call ([`page_written`]) and finds the slots whose + /// placed texture holds bytes of them ([`Spans::slots_holding`]). A + /// slot whose texture was uploaded before the write shows the bytes + /// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`, + /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory + /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]); + /// its host copy exists, so the upload needs no room on the card. A + /// slot still waiting for its first upload is left as it is: that + /// upload takes the bytes that are there by then. Slots tables read + /// are left to their draws. Counted either way; returns how many slots + /// it made due. + fn texture_slots_page_written(&self, frame: u64) -> usize { + let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] + } + + /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): + /// the slots that held bytes of them, those of them uploaded before, + /// and those made due (the latter, if `due`). + fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] { + use std::sync::atomic::Ordering::Relaxed; + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let held = slots.len(); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + // Uploaded before: out of the queue, or in it after an upload (in + // part, or whole and being looked at again). + slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + PAGE_WRITES[2].fetch_add(held as u64, Relaxed); + PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed); + if !due { + return [held, slots.len(), 0]; + } + for &slot in &slots { + textures.changed(slot, frame, frame + PAGE_WRITE_AFTER); + } + [held, slots.len(), slots.len()] + } + /// Whether host slot `index` is made from the very record the title /// has at `handle` now. Its host texture then exists (a slot keeps what /// it views), so bringing that texture up to date takes no memory of @@ -1048,6 +1304,101 @@ impl HostHeap { .is_some_and(Option::is_some) } + /// Levels on demand (`crate::tiles`): makes again the host slots of the + /// placed textures whose first level with memory changed since the + /// last call ([`levels_changed`]), each from the view it was made + /// from, so that it shows the texture from that level ([`make`]). Only + /// slots that are made; a slot draws read through a table is made by + /// its draw. Returns how many it made. + /// shortcut: the starts are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + /// Levels on demand (`crate::tiles`): the card has room, so the slots + /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left + /// a held level without tiles at least a second ago + /// ([`levels_waiting`]) are due again from the next frame, as memory + /// mapped under them would make them + /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the + /// level its tiles. To be called only while the card has room: without + /// it the upload would give nothing again. Slots tables read are left + /// to their draws (`texture.rs` `upload` asks again for those). Returns + /// how many slots it made due. + /// shortcut: kept in one place for all heaps, as the starts below. + pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize { + if self.sampler { + return 0; + } + let starts: Vec = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.is_empty() { + return 0; + } + let starts: Vec = waiting + .iter() + .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2)) + .map(|(&start, _)| start) + .take(Self::WAITING_A_PASS) + .collect(); + for start in &starts { + waiting.remove(start); + } + starts + }; + if starts.is_empty() { + return 0; + } + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed); + slots.len() + } + + /// Textures a pass asks again for their levels + /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles + /// may take the room the others were asked for, and an upload that + /// gives nothing is a whole texture staged and copied for nothing. + const WAITING_A_PASS: usize = 128; + + pub(crate) fn texture_views_remade(&self) -> usize { + if self.sampler { + return 0; + } + let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); + if starts.is_empty() { + return 0; + } + let slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let mut remade = 0; + for slot in slots { + let Some(&key) = made.get(slot as usize) else { + continue; + }; + if key == 0 { + continue; + } + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + continue; + }; + if let Some(kept) = make(&view, self.cpu(slot)) { + self.keep(slot, kept); + remade += 1; + } + } + remade + } + /// The memory of the texture title slot `index` views is not mapped /// (any more): a host slot made from it becomes null again, so that /// the host copy can be let go (`crate::resource::let_go_idle`; a slot @@ -1204,21 +1555,27 @@ impl HostHeap { Some(View::Placed(false, resource, desc)) if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => { - Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32)) + // (And the level the view starts at: word 4 of a texture + // view's description, after format, dimension, mapping + // and a pad.) + Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) } _ => None, }; let stale = { use std::sync::atomic::Ordering::Relaxed; let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - let span = placed_view - .and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?)))); + let span = placed_view.and_then(|(resource, start, first)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first)) + }); match span { - Some((start, end)) => { + Some((start, end, first)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.rule = stale_rule(); - placed.note(index, start, end, !seen) + let stale = placed.note(index, start, end, !seen); + placed.shows(index, first); + stale } None => { placed.forget(index); @@ -2104,6 +2461,32 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } + // Levels on demand (`crate::tiles`): a texture made level by + // level is shown from the first level that is the title's + // and has memory, if the title's view starts before it (a + // level without memory reads zeros: a black texture). The + // title's own view mostly starts there already. + if let Some(first) = crate::resource::first_shown(resource) + && first > 0 + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }; + // The texture's own view (the title gave none): all of it. + let whole = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: own.Format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -2209,6 +2592,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + // An empty title buffer: nothing to view, and no host copy to + // look for (#70: such views were in flight at device removals). + if len == 0 { + return None; + } if *unordered { buffer_uav(address, len, uav_desc(words), at) } else { @@ -2449,6 +2837,29 @@ mod tests { assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); } + /// What the texture code asks of the spans (levels on demand): where + /// the next texture starts inside a span, the lowest level a view of a + /// texture shows, and a texture's slots. + #[test] + fn spans_say_the_next_start_and_the_lowest_level_viewed() { + let mut spans = Spans::default(); + // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, + // and the next one 0x6000 after it (run 188). + spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(1, 3); + spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(2, 1); + spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); + assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); + assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); + assert_eq!(spans.first_viewed(0x1_0000), Some(1)); + assert_eq!(spans.first_viewed(0x1_6000), None); + assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]); + // The view from level 1 goes: the texture is viewed from level 3. + spans.forget(2); + assert_eq!(spans.first_viewed(0x1_0000), Some(3)); + } + /// Views of one placed texture are told from views of others by the /// address and the resource description, not by what they show. #[test] @@ -2566,6 +2977,38 @@ mod tests { assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } + /// Slots held back for lack of room on the card are not handed out + /// until their frame, keep their place, are not counted as waiting + /// for their memory, and all come back at once when the card has room; + /// a slot written again meanwhile is the title's new write. + #[test] + fn slots_held_for_lack_of_room_come_back_when_there_is_room() { + let mut q = TextureQueue::default(); + for i in 0..4u32 { + q.written(20 + i, 1, 0, false); + } + let due = q.due(1, 100); + assert_eq!(due.len(), 4); + // The card is full: slots 20 and 21 are held back until frame 101. + for &(index, write) in due.iter().filter(|d| d.0 < 22) { + q.hold(index, write, 101); + } + let now: Vec = q.due(2, 100).into_iter().map(|d| d.0).collect(); + assert!(!now.contains(&20) && !now.contains(&21)); + assert!(now.contains(&22) && now.contains(&23)); + assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory"); + // Due again at their frame, in the order they had. + assert_eq!(q.due(101, 100), due); + // Slot 21 is written again while held: due as written. + q.written(21, 3, 0, false); + assert!(q.due(3, 100).iter().any(|d| d.0 == 21)); + // Room again at frame 5: slot 20 is due at once, and only it was + // still held as it was. + assert_eq!(q.room(5), 1); + assert!(q.due(5, 100).iter().any(|d| d.0 == 20)); + assert_eq!(q.room(6), 0); + } + /// Textures of which only the smallest levels are held, packed into /// one another's address range (the three of run 188: 0x2c000 bytes /// each at full size, their starts 0x2000 and 0x4000 apart): writing @@ -2659,6 +3102,63 @@ mod tests { assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); } + /// A write names the textures that hold its bytes: the one that + /// starts where the write starts, not the neighbour before it, whose + /// held levels end there. + #[test] + fn a_write_at_the_start_of_a_packed_texture_names_it_alone() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // A request that fills the second texture's held levels. + assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]); + // From inside the first one's held levels on: both. + assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]); + // A whole 64 KiB page: every texture that starts in it. + assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]); + // Past the last start, the last one; past all, or no bytes, none. + assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]); + assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]); + } + + /// A write behind the guards' back under a placed texture: a slot + /// waiting for its first upload is left alone, one uploaded before is + /// counted, and made due two frames on when that is asked for. (The + /// ranges are handed over here, not through the list all heaps share.) + #[test] + fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fed_0000_0000u64; + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc); + assert!(heap.note_buffer(1, Some(&view), false).is_empty()); + let written = [(at, at + 0x1000)]; + // Waiting for its first upload: held, not uploaded, nothing done. + assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Uploaded and out of the queue. Memory elsewhere: nothing. + assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]); + // Under it, counted only: it stays out of the queue. + assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]); + assert_eq!(slots(u64::MAX), []); + // Under it, asked for: due two frames on, not before. + assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]); + assert_eq!(slots(61), []); + assert_eq!(slots(62), [1]); + } + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that /// overlaps others is left out of the spans, as before. #[test] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 29f34cf7..ee74cc47 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -385,6 +385,20 @@ pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), /// new ones, since the start. pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); +/// Whether a pass over the textures picked by index on a full card holds +/// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`: +/// no, as before: they stay due, each pass looks at the same ones again +/// and stops at the 257th). Held back, such a slot is looked at again +/// after about four seconds or as soon as the card has room, and the pass +/// goes on to the slots behind it: the ones whose host copy exists and +/// only wants bringing up to date, and the ones whose memory went (letting +/// their host copies go is what makes room). What is uploaded while the +/// card has room is the same either way. +fn full_card_pass() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0")) +} + /// Whether a texture that has its host copy is still brought up to date /// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: /// no). @@ -1587,7 +1601,10 @@ impl State { static NEXT: AtomicU64 = AtomicU64::new(0); let now = crate::host::now_ms().max(1); let next = NEXT.load(Ordering::Relaxed); - let due_now = if next == 0 { !room } else { now >= next }; + // (With levels on demand the card may never be without room: the + // lines then start with the first texture made that way.) + let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0; + let due_now = if next == 0 { !room || by_level } else { now >= next }; if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { return; } @@ -1687,9 +1704,22 @@ impl State { once!("textures picked by index: the card has no room for more; they wait"); } let mut refused = 0; + // Room again: the slots held back while the card was full are due + // now (`full_card_pass`). + if room { + host.texture_slots_room(frame); + } // Slots whose texture's memory the runtime mapped, unmapped or // wrote since the last pass are due again. host.texture_slots_remapped(frame); + // Levels on demand: the slots of textures whose first level with + // memory changed since the last pass are made again from it. + host.texture_views_remade(); + // And with room, the textures whose upload left a held level + // without the card's memory are uploaded again. + if room { + host.texture_slots_waiting(frame); + } let (due, census) = host.texture_slots_due(frame, 4096); HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { @@ -1844,7 +1874,15 @@ impl State { && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); if !has_its_texture { refused += 1; - if refused > 256 { + if full_card_pass() { + // Held back for the frames of about four seconds + // (`most`), or until the card has room; the pass + // goes on, within a count that bounds one pass. + host.texture_slot_held(index, write, frame + most); + if refused > 1024 { + break; + } + } else if refused > 256 { break; } continue; @@ -3258,13 +3296,16 @@ fn view_state(view: Option<&View>) -> String { memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) ), }; - format!("placed texture view_format={} {state}", d[0]) + // (Last, so that readers of the older lines still find + // theirs: the level the view starts at, and how many it shows.) + format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32) } Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { format!( - "texture object {r:#x} view_format={} {}", + "texture object {r:#x} view_format={} {} view_levels={}", d.as_ref().map_or(0, |d| d[0]), - texture_state(*r as This) + texture_state(*r as This), + d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32)) ) } Some(v) => format!("{v:?}").chars().take(80).collect(), diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 492ae72a..6559af14 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -679,7 +679,7 @@ fn create() -> windows::core::Result { /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. -fn warp_adapter() -> windows::core::Result { +pub(crate) fn warp_adapter() -> windows::core::Result { // SAFETY: plain DXGI adapter queries. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; @@ -2698,7 +2698,8 @@ fn declared_writes(runs: &[&HostList]) -> Vec { /// ([`read_backs`]), the frame's main pass by scissor rectangle with its /// culling dispatches (`draw.rs`, `walls_census`), the shader-written /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host -/// copies found stale after their refresh (`shadow.rs`), and, in the +/// copies found stale after their refresh (`shadow.rs`; only with +/// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the /// runtime, the read requests that fail (with 2: every request). pub(crate) fn walls_trace() -> bool { static ON: OnceLock = OnceLock::new(); @@ -5607,6 +5608,13 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us } impl Host { + /// The queue everything of ours runs on, for a call that must go to it + /// in order with the lists (`crate::tiles`: a texture's levels are + /// given memory ahead of the list that uploads them). + pub(crate) fn queue(&self) -> &ID3D12CommandQueue { + &self.queue + } + /// A buffer in the upload heap, mapped for writing. /// A buffer of `size` bytes the card writes and we read (a read back), /// in the state copies into it need. @@ -5854,6 +5862,7 @@ impl Meter { "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) ); + crate::tiles::status(); { let [queued, due, away, partly, oldest] = [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); @@ -5877,6 +5886,19 @@ impl Meter { crate::descriptor::host::STALE[4].load(Ordering::Relaxed) ); } + { + let mode = crate::watch::page_writes(); + let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); + let [kept, dropped, slots, uploaded] = + [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); + tracing::info!( + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)", + bytes >> 20, + if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, + if mode & 4 != 0 { "told as well" } else { "counted only" }, + if mode & 2 != 0 { "made due again" } else { "left as they were" } + ); + } #[cfg(feature = "diagnostics")] tracing::info!( "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461dfa..60751b53 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -267,11 +267,17 @@ pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: struct Views { /// By address: bytes, the section's handle, the offset in it. views: BTreeMap, + /// By section and byte offset of a 64 KiB page: the address of that + /// page in every view that shows it. A write through one view of a + /// page is a write of the bytes every other view shows + /// (`crate::watch` guards them all). + pages: BTreeMap<(usize, u64), Vec>, /// Sections by handle: bytes, and whether made committed. sections: Vec<(usize, u64, bool)>, } -static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() }); +static VIEWS: Mutex = + Mutex::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), sections: Vec::new() }); fn views() -> std::sync::MutexGuard<'static, Views> { VIEWS.lock().unwrap_or_else(|e| e.into_inner()) @@ -288,7 +294,17 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { /// The runtime mapped `[at, at + len)` as a view of `section` from /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { - views().views.insert(at, (len, section, offset)); + { + let mut v = views(); + v.views.insert(at, (len, section, offset)); + for k in 0..len.div_ceil(K64) { + v.pages.entry((section, offset + (k * K64) as u64)).or_default().push(at + k * K64); + } + } + // This view is writable from now on: a guard over the same bytes at + // another view must look at them again, and the pages are noted written + // there (`crate::watch`). + crate::watch::views_mapped(section, offset, len); } /// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): @@ -303,8 +319,86 @@ pub(crate) fn views_gone(at: usize, len: usize) { let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); let gone: Vec = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); for base in gone { - v.views.remove(&base); + let Some((bytes, section, offset)) = v.views.remove(&base) else { + continue; + }; + for k in 0..bytes.div_ceil(K64) { + let key = (section, offset + (k * K64) as u64); + if let Some(pages) = v.pages.get_mut(&key) { + let page = base + k * K64; + pages.retain(|&shown| shown != page); + if pages.is_empty() { + v.pages.remove(&key); + } + } + } + } +} + +/// The title views that overlap `[start, end)`, as `(address, bytes)`. +pub(crate) fn views_between(start: usize, end: usize) -> Vec<(usize, usize)> { + if start >= end { + return Vec::new(); + } + let v = views(); + let mut out = Vec::new(); + if let Some((&base, &(bytes, _, _))) = v.views.range(..=start).next_back() + && base + bytes > start + { + out.push((base, bytes)); + } + for (&base, &(bytes, _, _)) in v.views.range(start.saturating_add(1)..end) { + out.push((base, bytes)); + } + out +} + +/// The address of the 64 KiB page shown at `page` in every title view that +/// shows it, `page`'s own address included; empty if `page` is not a view. +pub(crate) fn pages_of(page: usize) -> Vec { + let v = views(); + let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else { + return Vec::new(); + }; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return Vec::new(); + } + v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() +} + +/// The title views that show any of the physical bytes `[offset, offset + +/// len)` of `section`, as `(address, bytes)` ranges in address order; not +/// those of a page shown in very many views (`MANY_VIEWS`). +pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> { + if len == 0 { + return Vec::new(); + } + let v = views(); + let end = offset.saturating_add(len as u64); + let mut pages: Vec = Vec::new(); + let mut at = offset - offset % K64 as u64; + while at < end { + if let Some(shown) = v.pages.get(&(section, at)) + && shown.len() <= crate::watch::MANY_VIEWS + { + pages.extend(shown.iter().copied()); + } + match at.checked_add(K64 as u64) { + Some(next) => at = next, + None => break, + } + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for page in pages { + match runs.last_mut() { + Some((first, bytes)) if *first + *bytes == page => *bytes += K64, + _ => runs.push((page, K64)), + } } + runs } /// How the views cover `[at, at + len)`. diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index db53f110..e001a473 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -50,6 +50,8 @@ pub mod shader_cache; mod memory; #[cfg(windows)] mod shadow; +#[cfg(windows)] +mod tiles; pub mod signature; #[cfg(windows)] mod texture; @@ -62,5 +64,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_written, + writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 44c89654..f9edaab5 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -861,6 +861,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { // Depth textures shaders also write: what they wrote, first. list.twin_use(dst, false, true); list.twin_use(src, false, false); + // A destination made level by level gets its levels' memory + // ahead of this list (`crate::tiles`). + crate::texture::card_writes(list, dst, to, None); ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); crate::texture::host_written(dst); @@ -994,6 +997,11 @@ extern "system" fn copy_texture_region( // A depth texture shaders also write: what they wrote, first (the // source above too). list.twin_use(dst.resource, false, true); + // A destination made level by level gets the level's memory ahead + // of this list (`crate::tiles`): the title's bake copies each level + // of its result into a block-compressed texture of that kind, and + // a copy into a level without memory is dropped. + crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32)); ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(dst.resource); let mut to_location = dst; @@ -1147,6 +1155,8 @@ extern "system" fn resolve( // Depth textures shaders also write: what they wrote, first. list.twin_use(dst, false, true); list.twin_use(src, false, false); + // As for a copy (`crate::tiles`). + crate::texture::card_writes(list, dst, to, Some(dst_sub)); ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); crate::texture::host_written(dst); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index e4fee24d..d701973c 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -244,22 +244,24 @@ pub(crate) fn pc_format(format: u32) -> u32 { /// (NVIDIA) refused the whole texture, so every pass that wrote it drew /// nothing. There 8-bit RGBA stands in: the same channels in the same /// order, every 4-bit level exact and every 5-bit level within 1/510. +/// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit +/// float RGBA stands in, with at least R9G9B9E5's precision and range. /// The title's pipelines and views of such targets name the stand-in too /// ([`view_format`], the host view checks). /// shortcut: copies between such a target and a texture the title fills /// itself in the 16-bit format are skipped ([`stands_in`]); convert them /// if a pass turns out to need one. pub(crate) fn target_format(format: u32) -> u32 { - const STAND_INS: [(u32, u32); 2] = [(86, 28), (115, 28)]; + const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)]; let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else { return format; }; #[cfg(windows)] { use windows::Win32::Graphics::Direct3D12::*; - static REFUSED: std::sync::OnceLock<[bool; 2]> = std::sync::OnceLock::new(); + static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new(); let refused = REFUSED.get_or_init(|| { - STAND_INS.map(|(f, _)| { + STAND_INS.map(|(f, to)| { let Some(host) = crate::host::host() else { return false; }; @@ -279,7 +281,7 @@ pub(crate) fn target_format(format: u32) -> u32 { | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; let refused = asked.is_err() || support.Support1.0 & both != both; if refused { - tracing::info!(format = f, "the host does not render to this format: 8-bit RGBA stands in"); + tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used"); } refused }) @@ -1125,6 +1127,10 @@ pub(crate) struct HostTexture { /// Whether its contents come from title memory ([`fills`]): counted in /// [`KINDS`] while it lives. filled: bool, + /// Made without memory of its own (`crate::tiles`): the tiles its + /// levels have been given. Its `bytes` are 0: what it holds of the card + /// is counted there. + pub(crate) tiled: Option, } /// What a title texture has on the host: its host copy and, for a depth @@ -1303,7 +1309,49 @@ fn hosted(this: This, make: bool) -> Option { .clear .as_ref() .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::()); - let Some(texture) = host_texture(&r.desc, r.host.state, clear) else { + // Levels on demand (`crate::tiles`): a texture the title places in + // memory and fills, of a megabyte or more, that does not hold all + // its levels now, is made without memory and given it level by + // level. It does not hold them all if its memory is not all + // mapped, if the next texture starts inside its span, or if a + // view of it starts below level 0. Every other texture, and this + // one if the card will not have it so, is made as before. + const TEXTURE_2D: u32 = 3; + let mut tiled = None; + let mut texture = None; + let shape_fits = fills(&r.desc) + && r.desc.dimension == TEXTURE_2D + && r.desc.depth_or_array_size == 1 + && r.desc.mip_levels > 1 + && r.desc.sample_count <= 1; + if shape_fits && r.host.placed.load(Relaxed) && crate::tiles::wanted() { + let bytes = footprint(&r.desc).map_or(0, |f| f.size); + let start = r.data() as u64; + // What the upload can read: a console layout, no XOR mode + // (`crate::texture` `staging`). + let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()); + let partly = readable + && bytes >= crate::tiles::floor() + && (!crate::texture::committed(r.data().cast_const(), bytes as usize) + || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() + || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0)); + let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None }; + let cut = reserved + .as_ref() + .zip(crate::host::host()) + .and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels))); + // (Both or neither: a reserved texture the card will not cut + // into tiles is dropped here, and the old kind is made below.) + if cut.is_some() { + tiled = cut; + texture = reserved; + } + } + let texture = match texture { + Some(texture) => Some(texture), + None => host_texture(&r.desc, r.host.state, clear), + }; + let Some(texture) = texture else { r.host.refused.store(true, Relaxed); return None; }; @@ -1320,7 +1368,10 @@ fn hosted(this: This, make: bool) -> Option { ); } let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); - let mut host = HostTexture::new(texture, state); + let mut host = match tiled { + Some(tiled) => HostTexture::new_tiled(texture, state, tiled), + None => HostTexture::new(texture, state), + }; host.filled = fills(&r.desc); if host.filled { KINDS[0].fetch_add(1, Relaxed); @@ -1371,7 +1422,9 @@ pub(crate) fn room() -> bool { let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; mb.trim().parse::().ok().map(|mb| mb << 20) }); - let filled = KINDS[1].load(Relaxed); + // (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 { return filled < limit; } @@ -1379,11 +1432,31 @@ pub(crate) fn room() -> bool { return true; } match crate::host::host().and_then(|h| h.video_memory()) { - Some([budget, used, ..]) => used < budget / 100 * room_percent(), + // What is kept for card copies of title buffers not made yet + // counts as used (`crate::shadow::card_room_kept`; 0 by default). + Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(), None => filled < WITHOUT_BUDGET, } } +/// [`room`] as it was at most a tenth of a second ago, for a question +/// asked of many textures a frame ([`room`] asks the system each time). +#[cfg(windows)] +pub(crate) fn room_lately() -> bool { + use std::sync::atomic::Ordering::Relaxed; + // The tenth of a second of the last asking, counted from 1, and its + // answer in the lowest bit. + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let tenth = crate::host::now_ms() / 100 + 1; + let last = LAST.load(Relaxed); + if last >> 1 == tenth { + return last & 1 != 0; + } + let room = room(); + LAST.store((tenth << 1) | u64::from(room), Relaxed); + room +} + /// The share of the card's budget, in percent, up to which host copies of /// textures picked by index are made ([`room`]): 90 unless /// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a @@ -1474,7 +1547,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, return; } let began = std::time::Instant::now(); - let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new(); + // (The last: made level by level, its bytes are those of its tiles.) + let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new(); // Textures the title fills without a host copy: never one, one let go. let mut without = [0u64; 2]; { @@ -1487,7 +1561,10 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, } let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); match made.as_ref() { - Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)), + Some((host, _)) => copies.push(match &host.tiled { + Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true), + None => (r.data() as usize, r.desc, host.bytes, false), + }), None => without[usize::from(r.host.gone.load(Relaxed))] += 1, } } @@ -1508,9 +1585,16 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, // a level not mapped; with the largest level not mapped; with no // level mapped; copies without a console layout (not asked). let mut c = [0u64; 7]; - for &(memory, desc, bytes) in &copies { + // Of the copies: made level by level, and the bytes of their tiles. + let mut on_demand = [0u64; 2]; + for &(memory, desc, bytes, by_level) in &copies { c[0] += 1; c[1] += bytes; + if by_level { + on_demand[0] += 1; + on_demand[1] += bytes; + continue; + } let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { c[6] += 1; continue; @@ -1587,6 +1671,7 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; let walk_ms = began.elapsed().as_millis() as u64; + let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20]; tracing::info!( "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ @@ -1597,7 +1682,8 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ - {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own" + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \ + copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)" ); WALKING.store(false, Relaxed); }; @@ -1688,6 +1774,66 @@ pub(crate) fn let_go_idle() { } } +/// For the memory line: the host copies the sweep never lets go +/// ([`let_go_idle`] takes only copies of textures the title fills that the +/// host never copied into), by what would say they are dead weight. A +/// count and the bytes (twins included) of: the copies the host renders to +/// or writes; of them, those whose title memory is not mapped now (its +/// first page); those nothing has used for 30 seconds and 60 frames and +/// that no list and no slot holds; those that are both; the copies of +/// textures the title fills that the host copied into; and, of the first, +/// the placed ones. Render-target copies grew from 2,319 MB at the world's +/// first frame to 3,075 MB 150 s later in run 197 and never shrank, while +/// 26,517 copies of filled textures were let go to stay under the card's +/// line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn targets_census() -> [u64; 12] { + use std::sync::atomic::Ordering::Relaxed; + let mut c = [0u64; 12]; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, twin)) = made.as_ref() else { + continue; + }; + let copied_into = host.filled && crate::texture::host_wrote(at); + if host.filled && !copied_into { + continue; + } + let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + let mut add = |i: usize| { + c[i] += 1; + c[i + 1] += bytes; + }; + if copied_into { + add(8); + continue; + } + add(0); + let placed = r.host.placed.load(Relaxed); + // Its first page: what is there of a texture starts there. + let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1); + let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1; + if unmapped { + add(2); + } + if idle { + add(4); + } + if unmapped && idle { + add(6); + } + if placed { + add(10); + } + } + c +} + /// For the memory line: title textures with a host copy the host renders /// to or writes and those copies' bytes (twins included); title textures /// without a host copy and the bytes of title memory they are; host copies @@ -1772,6 +1918,24 @@ impl HostTexture { state: std::sync::atomic::AtomicU32::new(state), bytes, filled: false, + tiled: None, + } + } + + /// A texture made without memory of its own (`crate::tiles`): counted + /// as a host texture of no bytes. + fn new_tiled( + texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + tiled: crate::tiles::Tiled, + ) -> HostTexture { + HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes: 0, + filled: false, + tiled: Some(tiled), } } } @@ -1843,6 +2007,18 @@ fn host_texture( desc: &ResourceDesc, state: u32, clear: *const c_void, +) -> Option { + host_texture_as(desc, state, clear, false) +} + +/// [`host_texture`]; `reserved`: without memory of its own, to be given +/// tiles level by level (`crate::tiles`). +#[cfg(windows)] +fn host_texture_as( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, + reserved: bool, ) -> Option { use windows::Win32::Graphics::Direct3D12::*; const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access @@ -1898,23 +2074,40 @@ fn host_texture( ..Default::default() }; let mut texture: Option = None; - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. - let made = unsafe { - host.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), - // The same layout: format, then color or depth and stencil. - clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), - &mut texture, - ) + let made = if reserved { + // The card's own layout of 64 KiB tiles, which a reserved texture + // must have. + d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32; + // SAFETY: as below; a texture the title fills has no clear value. + unsafe { + host.device.CreateReservedResource( + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + None, + &mut texture, + ) + } + } else { + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut texture, + ) + } }; if let Err(e) = made { - tracing::warn!(error = %e, desc = ?d, "no host texture"); + tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); } if let Some(t) = &texture { crate::host::name(t, || { @@ -1924,6 +2117,73 @@ fn host_texture( texture } +/// The host copy of title texture `this` if it is made and was made +/// without memory of its own (`crate::tiles`); it is not made here. +#[cfg(windows)] +pub(crate) fn host_tiled(this: This) -> Option { + if this.is_null() || !crate::tiles::wanted() { + return None; + } + hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand) +} + +/// The first level a view of title texture `this` may show, if its host +/// copy is made level by level and some level is held and has memory +/// (`crate::tiles::Tiled::first_shown`). +#[cfg(windows)] +pub(crate) fn first_shown(this: This) -> Option { + host_tiled(this)?.tiled()?.first_shown() +} + +/// A host copy made without memory of its own (`crate::tiles`), as a +/// submission-time step of a list holds it. +#[cfg(windows)] +pub(crate) struct OnDemand(std::sync::Arc); + +// SAFETY: the host texture is named only in queue calls, which any thread +// may make; what it has been given is behind a lock of its own. +#[cfg(windows)] +unsafe impl Send for OnDemand {} +// SAFETY: as above. +#[cfg(windows)] +unsafe impl Sync for OnDemand {} + +#[cfg(windows)] +impl OnDemand { + pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> { + self.0.tiled.as_ref() + } + + /// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's + /// title memory starts (its slots are made again if the first level + /// they may show changed). + /// Held levels get tiles only while the card has room ([`room`]). + /// Returns whether a level is still without its tiles: the caller + /// records the upload again later. + pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool { + let Some(tiled) = &self.0.tiled else { + return false; + }; + let (changed, waiting) = tiled.uploaded(&self.0.texture, held, room()); + if changed { + crate::descriptor::host::levels_changed(memory); + } + if waiting { + crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + waiting + } + + /// [`crate::tiles::Tiled::card_wrote`]; `memory` as above. + pub(crate) fn card_wrote(&self, levels: u32, memory: u64) { + if let Some(tiled) = &self.0.tiled + && tiled.card_wrote(&self.0.texture, levels) + { + crate::descriptor::host::levels_changed(memory); + } + } +} + /// A texture's console memory and description; `None` for buffers. pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { if this.is_null() { diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 34ac4ac3..c5365c4c 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -1,7 +1,7 @@ //! Translated shaders kept on disk (decision 0003): under the configured -//! cache folder, keyed by the container's content and by the VIctory build -//! that translated it (the BLAKE3 of our executable), so a rebuilt -//! translator never serves an old translation. Entries go through +//! cache folder, keyed by the container's content and by the translator +//! that translated it (its source fingerprint and settings, see `build`), so +//! a changed translator never serves an old translation. Entries go through //! `victory-pipeline`'s content-addressed cache, which writes them //! atomically; an entry that does not read back is translated again. //! @@ -37,60 +37,58 @@ pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) } -/// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time). -fn build() -> &'static [u8; 32] { - static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); - BUILD.get_or_init(|| { - let exe = std::env::current_exe().and_then(std::fs::read); - let limit = victory_shader::emit::loop_limit(); - if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { - tracing::warn!( - limit, - "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" - ); - } - match exe { - Ok(mut bytes) => { - bytes.extend_from_slice(&limit.to_le_bytes()); - // So is the view heap's null slot (it differs by host GPU): - // a translation cached without the clamp must not be served. - crate::descriptor::host::probe_view_limit(); - bytes.extend_from_slice(&victory_shader::emit::view_heap_limit().to_le_bytes()); - // Which group barriers wait is part of the translation too. - bytes.push(victory_shader::emit::group_sync()); - // So are the switches that pick the form of a wave64 program: - // without them here a run with `VICTORY_WAVE_WIDE=0` was - // served the translations an earlier run of the same - // executable had cached with the switch unset. - for name in [ - "VICTORY_WAVE_WIDE", - "VICTORY_WAVE_DEEP_SKIPS", - "VICTORY_WAVE_OWN_BITS", - "VICTORY_F16_NEAREST", - ] { - bytes.extend_from_slice(name.as_bytes()); - bytes.push(b'='); - if let Some(value) = std::env::var_os(name) { - bytes.extend_from_slice(value.as_encoded_bytes()); - } - bytes.push(0); +/// What identifies the translation, besides the container: the shader +/// crate's fingerprint (its source, every switch it reads, the host facts the +/// device gave it, the loop limit, barrier waits and clean-up passes) and +/// this file's encoding of the result. Not the whole executable any more: a +/// rebuild that leaves the translator alone keeps its translations (each new +/// build used to translate the title's thousands of shaders again, which kept +/// the first minutes of every test run short of pipelines). +/// `VICTORY_SHADER_CACHE_KEY=exe` restores the old key (the executable's hash). +/// Worked out per lookup, so a translation made before the device said its +/// wave size is never filed under the later key. +fn build() -> [u8; 32] { + static WARNED: std::sync::Once = std::sync::Once::new(); + let limit = victory_shader::emit::loop_limit(); + if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { + WARNED.call_once(|| tracing::warn!(limit, "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner")); + } + static EXE: OnceLock> = OnceLock::new(); + let exe = EXE.get_or_init(|| { + if std::env::var_os("VICTORY_SHADER_CACHE_KEY").is_some_and(|v| v == "exe") { + match std::env::current_exe().and_then(std::fs::read) { + Ok(bytes) => Some(*blake3::hash(&bytes).as_bytes()), + Err(e) => { + tracing::warn!(error = %e, "cannot read our executable; keying on the translator"); + None } - // And which clean-up passes ran over the translated code. - bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); - *blake3::hash(&bytes).as_bytes() - } - Err(e) => { - // Without it no entry can be trusted: a fresh key per run. - tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default(); - *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() } + } else { + None } - }) + }); + let mut h = blake3::Hasher::new(); + h.update(b"victory shader cache key 2\0"); + if let Some(exe) = exe { + h.update(exe); + } + h.update(&victory_shader::emit::translation_fingerprint()); + h.update(include_bytes!("shader_cache.rs")); + *h.finalize().as_bytes() +} + +/// The offline warm-up (`victory translate --warm`): `container` is +/// translated into the cache unless it is there already. `Ok(true)`: it +/// was translated now. Needs [`use_shader_cache`] and the same host facts +/// the run will have (`victory_shader::emit::translation_fingerprint`). +pub fn warm(container: &[u8]) -> Result { + let cache = CACHE.get().ok_or("no shader cache")?; + let ran = AtomicBool::new(false); + let translate = |c: &[u8]| { + ran.store(true, Ordering::Relaxed); + victory_shader::emit::translate(c).map_err(|e| e.to_string()) + }; + cached(cache, &build(), container, translate).map(|_| ran.load(Ordering::Relaxed)) } /// The translation of a console shader container, from the cache when @@ -98,7 +96,7 @@ fn build() -> &'static [u8; 32] { pub(crate) fn host_shader(container: &[u8]) -> Result { let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, build(), container, translate), + Some(cache) => cached(cache, &build(), container, translate), None => translate(container), } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 133e871a..f47de440 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -162,6 +162,40 @@ fn card_limits() -> (u64, u64) { /// Bytes alive of copies' card sides, and of their "before" twins. static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// Whether the texture queue leaves room on the card for the card copies +/// of title buffers that are not made yet +/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default). +/// +/// The copies are made in one burst when the world loads (run 189: 94 of +/// its 95 within two seconds, right before the first world frame), and +/// [`card_for`] makes one only while the card is under eight tenths of its +/// budget. That held as long as the textures picked by index filled the +/// card after the burst. Since the texture queue keeps packed neighbours +/// (52b8060) it fills the card while the world loads: 85% and more at the +/// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked +/// for shader writes in 600 to 720 MB a frame where it had been 30, and +/// the frame went from about 240 to 370-470 ms. +/// +/// With the switch, the texture queue's rule (`resource::room`) counts the +/// part of [`card_limits`]' second number that no copy has taken yet as +/// used, and a copy may be made up to nine tenths of the budget: the room +/// it takes was kept for it. After the burst what is kept is what the +/// burst left of the limit (87 MB of 1,024 in run 189). +fn card_room_kept_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1")) +} + +/// The bytes of the card's memory the texture queue leaves free for card +/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with +/// the switch off or without card copies. +pub(crate) fn card_room_kept() -> u64 { + if !card_room_kept_on() || !cards() { + return 0; + } + card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed)) +} + /// The copies in the card's memory. static CARDED: Mutex>> = Mutex::new(Vec::new()); @@ -212,8 +246,11 @@ fn card_for(size: u64) -> Option { // queue's own rule (`resource::room`: nine tenths of the budget) counts // them, so the card's use stays where it was and the textures' share // shrinks by the copies' bytes, at most `card_limits`' second number. + // (With `card_room_kept_on` the texture queue kept this copy's room + // free, and the copy may go up to the queue's own line.) + let tenths = if card_room_kept_on() { 9 } else { 8 }; if let Some([budget, used, ..]) = host.video_memory() - && used + size > budget / 10 * 8 + && used + size > budget / 10 * tenths { return None; } @@ -598,6 +635,155 @@ fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, out } +/// The runs of 4-byte words of title memory (cut on its addresses; +/// `read` and `merged` are of the memory at `address`) that hold a byte in +/// which `merged` differs from `read`, as (offset, bytes) in order to +/// `put`. A shader stores words, so these are what the card wrote; every +/// other byte of `merged` is the title's as it was read. +fn word_runs(address: usize, read: &[u8], merged: &[u8], mut put: impl FnMut(usize, usize)) { + let n = read.len().min(merged.len()); + let mut i = 0; + while i < n { + // Equal bytes are passed over, 32 at a time while they last. + match first_difference(&read[i..n], &merged[i..n]) { + Some(d) => i += d, + None => break, + } + // From the word that holds this byte (or the stretch's first + // byte) to the end of the last word in a row that holds one. + let first = i - ((address + i) & 3).min(i); + let mut end = first; + while end < n { + let word = (((address + end) | 3) + 1 - address).min(n); + if read[end..word] == merged[end..word] { + break; + } + end = word; + } + put(first, end - first); + i = end; + } +} + +/// Whether the merges that write a stretch of title memory back +/// ([`Shadow::relay_merge`], [`Shadow::card_merge`], +/// [`Shadow::card_merge_relay`]) look, right before that write, for title +/// bytes it is about to put back to older values (`VICTORY_MERGE_RACE=1`; +/// off by default). Logging only: [`merge_race`]. +fn merge_race_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MERGE_RACE").is_some_and(|v| v == "1")) +} + +/// [`merge_race`]'s sums. Of frame `frame`, and in `total` since the +/// start: stretches written back, their bytes, title bytes put back to +/// older values, bytes the title and the card both changed, stretches with +/// either, the runs a write of the card's words alone makes +/// ([`word_runs`]) and their bytes. `said`: the frame's first stretches +/// with either. `quiet`: frames since the last line. +struct MergeRace { + frame: u64, + now: [u64; 7], + said: Vec, + total: [u64; 7], + quiet: u64, +} + +static MERGE_RACE: Mutex = + Mutex::new(MergeRace { frame: 0, now: [0; 7], said: Vec::new(), total: [0; 7], quiet: 0 }); + +/// With [`merge_race_on`], right before a merge writes `merged` over title +/// memory at `address` (a stretch of the copy of the title buffer `copy`: +/// start and bytes): title memory is read once more and compared with +/// `read`, what the merge read of it before. A byte that changed in +/// between and that the write-back stores with its value as first read +/// (the card did not change it) is a title byte put back to an older +/// value; one the write-back stores with the card's byte is one both +/// changed. Only bytes the write-back stores are looked at. Summed per +/// frame; a line for every frame that has any, and one every 100 frames +/// whatever it holds, so that "none" is said, not assumed. +/// +/// A lower bound: a title write that lands after this read (while the +/// write-back itself runs) is not seen, nor one that wrote a byte and then +/// its old value again. Costs one more read and two compares of every +/// stretch written back, on the thread that merges. +fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u8], which: &'static str) { + if !merge_race_on() { + return; + } + let Some(read) = read else { + return; + }; + let n = read.len().min(merged.len()); + let (read, merged) = (&read[..n], &merged[..n]); + let mut runs: Vec<(usize, usize)> = Vec::new(); + word_runs(address, read, merged, |off, len| runs.push((off, len))); + let whole = [(0, n)]; + let looked: &[(usize, usize)] = &whole; + let mut again = vec![0u8; n]; + let (mut put_back, mut both, mut first) = (0u64, 0u64, None); + if crate::host::read_into(address as *const u8, &mut again) { + for &(off, len) in looked { + for i in off..off + len { + if again[i] == read[i] || again[i] == merged[i] { + continue; + } + if merged[i] == read[i] { + put_back += 1; + first.get_or_insert(i); + } else { + both += 1; + } + } + } + } + let frame = crate::frame::current(); + let mut race = MERGE_RACE.lock().unwrap_or_else(|e| e.into_inner()); + if race.frame != frame { + race.quiet += 1; + if race.now[4] > 0 || race.quiet >= 100 { + tracing::info!( + frame = race.frame, + stretches = race.now[0], + stretch_bytes = race.now[1], + put_back = race.now[2], + both_changed = race.now[3], + stretches_hit = race.now[4], + word_runs = race.now[5], + word_run_bytes = race.now[6], + stretches_since_start = race.total[0], + stretch_bytes_since_start = race.total[1], + put_back_since_start = race.total[2], + both_changed_since_start = race.total[3], + stretches_hit_since_start = race.total[4], + word_runs_since_start = race.total[5], + word_run_bytes_since_start = race.total[6], + first = ?race.said, + "merge race: title bytes that changed between a merge's read of title memory and its write-back of what shaders wrote, in this frame (VICTORY_MERGE_RACE=1)" + ); + race.quiet = 0; + } + race.frame = frame; + race.now = [0; 7]; + race.said.clear(); + } + let hit = u64::from(put_back + both > 0); + let run_bytes: u64 = runs.iter().map(|r| r.1 as u64).sum(); + let add = [1, n as u64, put_back, both, hit, runs.len() as u64, run_bytes]; + for (i, v) in add.iter().enumerate() { + race.now[i] += v; + race.total[i] += v; + } + if hit > 0 && race.said.len() < 8 { + race.said.push(format!( + "{which}: copy {:#x}+{:#x} stretch {address:#x}+{n:#x}: {put_back} put back (first at {:#x}), {both} both changed", + copy.0, + copy.1, + address + first.unwrap_or(0) + )); + } +} + #[cfg(test)] mod relay_tests { use super::{Flights, changed_runs, merge_piece, outside}; @@ -857,51 +1043,54 @@ fn give_back(v: Vec) { const NOT_WATCHED: u8 = 2; -/// Where `a` and `b` (of one length) first differ, compared eight bytes at -/// a time. +// Fixed-size equality compiles to two SIMD comparisons on Windows x64. +// Only the first or last unequal chunk needs a byte-wise search. +const DIFF_CHUNK: usize = 32; + +/// Where `a` and `b` first differ within their common length. fn first_difference(a: &[u8], b: &[u8]) -> Option { - let whole = a.len().min(b.len()) / 8 * 8; - let from = a[..whole] - .as_chunks::<8>().0.iter() - .zip(b[..whole].chunks_exact(8)) - .position(|(x, y)| x != y) - .map_or(whole, |word| word * 8); - a[from..].iter().zip(&b[from..]).position(|(x, y)| x != y).map(|i| from + i) + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::(); + let (b_chunks, b_tail) = b[..len].as_chunks::(); + let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) { + Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]), + None => (len - a_tail.len(), a_tail, b_tail), + }; + a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i) } -/// Where `a` and `b` (of one length) last differ. +/// Where `a` and `b` last differ within their common length. fn last_difference(a: &[u8], b: &[u8]) -> Option { - let whole = a.len().min(b.len()) / 8 * 8; - if let Some(i) = a[whole..].iter().zip(&b[whole..]).rposition(|(x, y)| x != y) { - return Some(whole + i); - } - let word = a[..whole] - .as_chunks::<8>().0.iter() - .zip(b[..whole].chunks_exact(8)) - .rposition(|(x, y)| x != y)? - * 8; - a[word..word + 8] + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::(); + let (b_chunks, b_tail) = b[..len].as_chunks::(); + if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) { + return Some(len - a_tail.len() + i); + } + let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?; + a_chunks[chunk] .iter() - .zip(&b[word..word + 8]) + .zip(&b_chunks[chunk]) .rposition(|(x, y)| x != y) - .map(|i| word + i) + .map(|i| chunk * DIFF_CHUNK + i) } #[cfg(test)] mod difference_tests { use super::{first_difference, last_difference}; - /// The word-wise searches agree with the byte-wise ones they replace. + /// The chunk searches agree with a byte-wise scan across chunk boundaries. #[test] fn differences_are_found_as_byte_by_byte() { - let base: Vec = (0..61u32).map(|i| (i * 7 + 3) as u8).collect(); - let same = base.clone(); - assert_eq!(first_difference(&base, &same), None); - assert_eq!(last_difference(&base, &same), None); - for len in [0usize, 1, 7, 8, 9, 16, 23, 61] { + let base: Vec = (0..98u32).map(|i| (i * 7 + 3) as u8).collect(); + for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] { + let a = &base[1..1 + len]; + let same = a.to_vec(); + assert_eq!(first_difference(&same, a), None); + assert_eq!(last_difference(&same, a), None); for at in 0..len { for other in at..len { - let (a, mut b) = (&base[..len], base[..len].to_vec()); + let mut b = a.to_vec(); b[at] ^= 0x80; b[other] ^= 0x01; let first = a.iter().zip(&b).position(|(x, y)| x != y); @@ -912,6 +1101,19 @@ mod difference_tests { } } } + + #[test] + fn differences_ignore_bytes_past_the_shorter_slice() { + let a = [0; 65]; + let mut b = [0; 67]; + b[65] = 1; + assert_eq!(first_difference(&a, &b), None); + assert_eq!(last_difference(&b, &a), None); + b[32] = 1; + b[64] = 1; + assert_eq!(first_difference(&b, &a), Some(32)); + assert_eq!(last_difference(&a, &b), Some(64)); + } } /// The unit shader writes are looked for and put back in. @@ -1325,6 +1527,80 @@ mod wide_tests { } } +/// What [`Shadow::copy_back`] does with a piece that differs from the +/// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From +/// the first byte that differs to the last, title memory is read into +/// `title` (scratch, sized to that stretch) by `read` (the stretch's offset +/// in the piece, where to), the GPU's bytes are put in and `host` takes the +/// result. The stretch's offset in the piece and its length if that changed +/// title memory; none if nothing differs or title memory is not there. +/// `runs` takes the runs of the stretch (offsets into `title`, lengths) +/// whose bytes are the GPU's and differ from the title's as read: only +/// those are to be written, so a title write that lands between the read +/// and the write elsewhere in the stretch stays (upstream VIctory #2009). +/// `mask` is scratch. +fn back_piece( + host: &mut [u8], + old: &[u8], + title: &mut Vec, + mask: &mut Vec, + runs: &mut Vec<(usize, usize)>, + read: impl FnOnce(usize, &mut [u8]) -> bool, +) -> Option<(usize, usize)> { + runs.clear(); + // From the first byte that differs to the last: title memory is read + // and written there only (a shader that sets a few words of a piece + // cost a read, a walk and a write of all 64 KiB of it). + let first = first_difference(host, old)?; + let last = last_difference(host, old).unwrap_or(first); + let n = last + 1 - first; + let (host, old) = (&mut host[first..=last], &old[first..=last]); + title.clear(); + title.resize(n, 0); + if !read(first, title) { + return None; + } + // Title memory with the GPU's bytes put in; the copy takes the title's + // bytes in turn. + // Without a branch, so the loop runs many bytes at a time: the GPU's + // byte where the copy's byte is not what it was before the submission + // and the title left its byte as it was, else the title's. (With the + // two searches above this was 44 ms a frame for 970 pieces.) + // Where the shader and the title both changed a byte while the GPU ran, + // the title's stays: the shader computed its byte from the copy's older + // data (one cleared a bit of a record the title had already replaced, + // and copying it back broke the title's object: an access violation + // through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2). + mask.clear(); + mask.resize(n, 0); + let mut differs = 0u8; + for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) { + let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; + let merged = (*t & !gpu) | (*h & gpu); + *m = merged ^ *t; + differs |= *m; + *t = merged; + *h = merged; + } + if differs == 0 { + return None; + } + let mut i = 0; + while i < n { + while i < n && mask[i] == 0 { + i += 1; + } + let start = i; + while i < n && mask[i] != 0 { + i += 1; + } + if i > start { + runs.push((start, i - start)); + } + } + Some((first, n)) +} + /// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages /// compared, changed runs put in, and their bytes. static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; @@ -1363,7 +1639,93 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { #[cfg(test)] mod merge_tests { - use super::changed_runs; + use super::{PIECE, back_piece, changed_runs}; + + /// A piece put back takes the GPU's bytes where the copy changed and + /// the title's everywhere else, reads and writes title memory only from + /// the first change to the last, and its scratch holds that stretch and + /// no more: not the 64 KiB per range it once was. + #[test] + fn a_piece_put_back_reads_only_its_stretch() { + let old: Vec = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect(); + // The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5, + // 9 and 40,000 (the GPU's byte wins where both wrote). + let mut title_memory = old.clone(); + title_memory[7] ^= 0x11; + title_memory[40_000] ^= 0x22; + let mut host = old.clone(); + for at in [5, 9] { + host[at] ^= 0x33; + } + let gpu = host.clone(); + let mut scratch = Vec::new(); + let (mut mask, mut runs) = (Vec::new(), Vec::new()); + let mut asked = None; + let read = |first: usize, into: &mut [u8]| { + asked = Some((first, into.len())); + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5))); + assert_eq!(asked, Some((5, 5))); + let mut wanted = title_memory[5..10].to_vec(); + wanted[0] = gpu[5]; + wanted[4] = gpu[9]; + assert_eq!(scratch, wanted); + assert_eq!(host[5..10], wanted); + // Only the GPU's two bytes are written back (upstream #2009). + assert_eq!(runs, [(0, 1), (4, 1)]); + // The copy outside the stretch is left as it was. + assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]); + assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity()); + + // Nothing differs: title memory is not read. + let mut same = old.clone(); + assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None); + // Title memory not there: nothing to write, the copy unchanged. + let mut host = gpu.clone(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None); + assert!(host == gpu); + // The GPU wrote what the title holds already: nothing to write. + let mut title_memory = old.clone(); + title_memory[5] = gpu[5]; + title_memory[9] = gpu[9]; + let mut host = gpu.clone(); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None); + // A whole piece changed: the scratch grows to it. + let mut host: Vec = old.iter().map(|b| !b).collect(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE))); + assert_eq!(scratch.len(), PIECE); + } + + /// A byte the shader and the title both changed while the GPU ran keeps + /// the title's (the shader computed it from the copy's older data); a + /// byte only the shader changed goes back, and only such bytes are in + /// the runs to write (PalmVIDev e0b70476, upstream #2009). + #[test] + fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() { + let old = vec![1u8, 2, 3, 4, 5, 6]; + let mut host = old.clone(); + host[1] = 20; // the GPU alone + host[3] = 40; // both + host[4] = 50; // the GPU alone + let mut title_memory = old.clone(); + title_memory[3] = 44; + title_memory[5] = 66; // the title alone + let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4))); + assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed"); + assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result"); + assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); + } /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. @@ -1504,6 +1866,51 @@ 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. +/// +/// [`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 +/// copy never took, and the title had not written lately, was neither +/// 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 { + (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() +} + +#[cfg(test)] +mod stale_tests { + use super::*; + + #[test] + fn pages_never_taken_are_stale_written_or_not() { + let base = 0x100; + let copied = [5, 0, 5, 5]; + let at = |page: usize| page * PAGE; + // 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()); + } +} + /// Copies of windows outside buffers let go since the start, and their /// bytes. static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; @@ -1927,44 +2334,27 @@ impl Shadow { for &(at, n) in &differing { self.changed(at, at + n); } - let mut title = vec![0u8; PIECE]; + // Sized to each stretch read (`back_piece`): a zeroed 64 KiB per + // range, most of whose ranges differ nowhere, was most of the + // work for small ranges. + let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); for (at, n) in differing { // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let old = &before[at - from..at - from + n]; - // From the first byte that differs to the last: title - // memory is read and written there only (a shader that sets - // a few words of a piece cost a read, a walk and a write of - // all 64 KiB of it). - let Some(first) = first_difference(host, old) else { + let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title); + let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else { continue; }; - let last = last_difference(host, old).unwrap_or(first); - let (at, n) = (at + first, last + 1 - first); - let (host, old) = (&mut host[first..=last], &old[first..=last]); - let title = &mut title[..n]; - if !crate::host::read_into((start + at) as *const u8, title) { - continue; - } - // Title memory with the GPU's bytes put in; the copy takes - // the title's bytes in turn. - // Without a branch, so the loop runs many bytes at a time: - // the GPU's byte where the copy's byte is not what it was - // before the submission, else the title's. (With the two - // searches above this was 44 ms a frame for 970 pieces.) - let mut differs = 0u8; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { - let gpu = if *h != *o { 0xffu8 } else { 0 }; - let merged = (*t & !gpu) | (*h & gpu); - differs |= merged ^ *t; - *t = merged; - *h = merged; - } - if differs != 0 { - crate::watch::writing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; + let at = at + first; + crate::watch::writing(start + at, n); + // Only the GPU's bytes (upstream #2009): the rest of the + // stretch is the title's as read, and a title write landing + // there since stays. + for &(off, len) in &runs { + crate::host::write_mapped((start + at + off) as *mut u8, title[off..].as_ptr(), len); + written += len; } } // Our write shows as a title write at the copy's next refresh, @@ -2048,10 +2438,14 @@ impl Shadow { if !crate::host::read_into((start + at) as *const u8, title) { return 0; } + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); if !merge_piece(now, held, title) { return 0; } crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } @@ -2221,9 +2615,7 @@ 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)) => written.into_iter().any(|(page, write)| { - page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at) - }), + Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), None => true, }) } @@ -2278,11 +2670,7 @@ impl Shadow { }; let stale: Vec = { let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - written - .into_iter() - .filter(|&(page, write)| page >= base && copied.get(page - base).is_none_or(|&at| at == 0 || write > at)) - .map(|(page, _)| page) - .collect() + stale_pages_in(base, &copied, a, e, &written) }; for page in stale { let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); @@ -2435,7 +2823,7 @@ impl Shadow { /// title's that arrived between the refresh and the look. fn refresh_check(&self, from: usize, to: usize) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) { + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) { return; } const SAMPLE: usize = 256; @@ -2662,6 +3050,9 @@ impl Shadow { title.resize(n, 0); let mut written = 0; if crate::host::read_into((start + at) as *const u8, title) { + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); // As in `copy_back`: the card's byte where it is not what it // was before the submission, else the title's. let mut differs = 0u8; @@ -2674,6 +3065,7 @@ impl Shadow { } if differs != 0 { crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); written = n; } @@ -2738,6 +3130,9 @@ impl Shadow { title.clear(); title.resize(n, 0); let mapped = crate::host::read_into((start + at) as *const u8, title); + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = (mapped && merge_race_on()).then(|| title.clone()); let mut changed = false; for (a, b) in outside(at, at + n, skip) { let (a, b) = (a - at, b - at); @@ -2749,6 +3144,7 @@ impl Shadow { return 0; } crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 34e7d515..bdac9f75 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -56,6 +56,19 @@ pub(crate) struct Staging { uploaded: std::sync::atomic::AtomicBool, /// When a list last recorded a use of it (`crate::host::moment`). used: std::sync::atomic::AtomicU64, + /// Levels on demand (`crate::tiles`): the texture's host copy was made + /// without memory of its own when the staging buffer was made. + on_demand: bool, + /// For such a texture: the levels that were the title's at the last + /// detiling (a bit a level; the staging buffer holds zeros for the + /// others), and what that was judged by ([`Staging::judgement`]). + detiled: std::sync::atomic::AtomicU32, + judged: [std::sync::atomic::AtomicU64; 2], + /// For such a texture: when an upload last left a held level without + /// tiles (`crate::host::moment`, never 0; 0: none did). The upload is + /// recorded again about a second later if the card has room by then + /// ([`upload`]). + waiting: std::sync::atomic::AtomicU64, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -225,6 +238,7 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { if !first && before.is_none() { return true; } + card_writes(list, placed, to, None); crate::list::ensure_state(list, placed, COPY_DEST); let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the location never releases. @@ -576,6 +590,32 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) }; use std::sync::atomic::Ordering::Relaxed; staging.used.store(crate::host::moment(), Relaxed); + // Levels on demand: a view of the texture now starts at another + // level, or another texture now starts inside its span, with no byte + // of its memory changed. The levels are judged anew: detiled again at + // this list's submission, and uploaded by this list. + if staging.on_demand && staging.judgement() != staging.judged() { + staging.forget(); + staging.dirty.store(true, Relaxed); + } + // Levels on demand: the last upload left a held level without tiles + // (the card had no room, or no heap could be had), and nothing else + // would record an upload again until the title writes the texture: the + // level stayed empty, the texture blurred or black. Asked again about + // once a second, and only when the card has room; the staging buffer + // still holds the level's bytes. + if staging.on_demand { + let since = staging.waiting.load(Relaxed); + if since != 0 && crate::host::long_ago(since, 1000, 2) { + if crate::resource::room_lately() { + staging.waiting.store(0, Relaxed); + staging.dirty.store(true, Relaxed); + crate::tiles::STATS[10].fetch_add(1, Relaxed); + } else { + staging.waiting.store(crate::host::moment().max(1), Relaxed); + } + } + } // The host texture has the staging buffer's contents: only the check // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the @@ -649,11 +689,207 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) staging.dirty.store(false, Relaxed); }); } - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); + // Levels on demand (`crate::tiles`): after the check below, in the + // order of this list's steps, and before the list is executed, the + // levels the staging buffer holds as the title's are given the card's + // memory if they have none. The list copies every level, so each one + // given here is written whole by it (the rest are copies into no + // memory, which the card drops). + let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None }; + let Some(on_demand) = on_demand else { + // Once per submission however many of its lists sample the texture. + list.defer_texture(staging); + return; + }; + list.defer_texture(staging.clone()); + list.defer_host(move || { + let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64); + staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed); + // A texture picked by index has no staging buffer after this + // upload: its slots are made due again by the texture pass. + if waiting { + crate::descriptor::host::levels_waiting(staging.memory as u64); + } + }); +} + +/// Levels on demand: the levels a list claimed for its zeros +/// (`crate::tiles::Tiled::claim`), held by the list's submission-time +/// step. A list that is reset without having been submitted gives the +/// claim up, or the next list that writes those levels would send no zeros +/// and what its write does not cover would be what the tiles' last owner +/// left. +struct Claimed { + on_demand: crate::resource::OnDemand, + fresh: u32, + ran: std::sync::atomic::AtomicBool, +} + +impl Drop for Claimed { + fn drop(&mut self) { + if self.fresh != 0 + && !*self.ran.get_mut() + && let Some(tiled) = self.on_demand.tiled() + { + tiled.unclaim(self.fresh); + } + } +} + +/// Levels on demand (`crate::tiles`): the card itself is about to write +/// title texture `resource` in `list` (a copy or a resolve into level +/// `level`, or into every level). If its host copy `texture` was made +/// without memory, the levels written get theirs when the list is +/// submitted, ahead of it on the queue; the ones that have none yet are +/// first written with zeros, here in the same list, so that what the +/// card's write does not cover is not what the tiles' last owner left. +/// To be called before the list is brought to the state of that write. +/// shortcut: two lists that write the same new level, submitted in the +/// other order than recorded, lose the first one's write under the zeros +/// of the other; so does an upload recorded and not yet submitted. +pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option) { + let Some(on_demand) = crate::resource::host_tiled(resource) else { + return; + }; + let Some(tiled) = on_demand.tiled() else { + return; + }; + let levels = match level { + Some(level) => tiled.with_level(level), + None => tiled.every_level(), + }; + if levels == 0 { + return; + } + let fresh = tiled.claim(levels); + // Of them, the ones whose zeros could not be recorded. + let mut unzeroed = if host().is_none() { fresh } else { 0 }; + if fresh != 0 + && let Some(host) = host() + { + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut bytes = 0u64; + // SAFETY: outputs for one subresource. + unsafe { + host.device + .GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes)); + } + let Some((buffer, data)) = list.upload(host, bytes) else { + // (With the levels that share its tiles, if it is one of + // the small ones.) + unzeroed |= tiled.with_level(level); + continue; + }; + // SAFETY: a mapped buffer of `bytes` bytes, just made. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above; the list holds the buffer until it is reset. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + } + // A new level without its zeros gets no tiles from this list: the + // card's write into it is lost (the level reads zeros, as before the + // write), which is less wrong than a part write over what the tiles' + // last owner left. The next list that writes it claims it again. + unzeroed &= fresh; + if unzeroed != 0 { + tiled.unclaim(unzeroed); + } + let levels = levels & !unzeroed; + if levels == 0 { + return; + } + let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64); + let step = Claimed { + on_demand, + fresh: fresh & !unzeroed, + ran: std::sync::atomic::AtomicBool::new(false), + }; + list.defer_host(move || { + step.ran.store(true, std::sync::atomic::Ordering::Relaxed); + step.on_demand.card_wrote(levels, memory); + }); } impl Staging { + /// Levels on demand: what says, beside the mapping, which levels of + /// the texture are the title's now. First the lowest level a live view + /// of the texture shows (0 without a view that says): the title's own + /// word, a texture it holds from level 3 on is viewed from level 3. + /// Then where the next texture placed in this one's span starts, in + /// bytes from this one's start (`u64::MAX`: none does): for a texture + /// viewed from level 0 although a neighbour sits where its large + /// levels would be. + fn judgement(&self) -> [u64; 2] { + let start = self.memory as u64; + let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from); + let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size)) + .map_or(u64::MAX, |at| at - start); + [first, limit] + } + + /// What [`Staging::judgement`] said at the last detiling. + fn judged(&self) -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)] + } + + /// Levels on demand: the levels that are the title's now, a bit a + /// level. A level is held if no view starts above it, its bytes end + /// before the next texture starts, and all of them are mapped. The + /// smallest levels share the texture's first block and are held + /// together. (The console layout: that block first, then the other + /// levels from the smallest up, level 0 last: + /// `victory_formats::texture::Layout`.) A texture this cannot tell + /// the levels of holds them all. + fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 { + let mips = &self.layout.mips; + if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 { + return u32::MAX; + } + let tail = (self.layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize) + }; + let mut held = 0u32; + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset }; + if level as u64 >= first && there(m.offset, end) { + held |= 1 << level; + } + } + if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) { + for level in tail..mips.len() { + if level as u64 >= first { + held |= 1 << level; + } + } + } + held + } + + /// Forgets what the staging buffer was last filled from: the next + /// refresh detiles anew, whether the memory changed or not. + fn forget(&self) { + *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default(); + } + /// The title memory the texture is read from: address and bytes. pub(crate) fn memory(&self) -> (usize, usize) { (self.memory as usize, self.layout.size as usize) @@ -835,6 +1071,20 @@ impl Staging { /// Detiles `tiled` (the texture's memory) into the staging buffer. fn detile(&self, tiled: &[u8]) { self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); + // Levels on demand: which levels are the title's is judged here, + // once, for what the staging buffer holds from now on. The step + // that gives levels their memory goes by this answer. + let held = if self.on_demand { + use std::sync::atomic::Ordering::Relaxed; + let judged = self.judgement(); + self.judged[0].store(judged[0], Relaxed); + self.judged[1].store(judged[1], Relaxed); + let held = self.held_levels(judged); + self.detiled.store(held, Relaxed); + held + } else { + u32::MAX + }; #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -852,6 +1102,11 @@ impl Staging { let linear = unsafe { std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) }; + if mip < 32 && held & (1 << mip) == 0 { + // Not the title's: zeros, not what lies in that memory. + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) @@ -1095,6 +1350,9 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { /// The staging state of a title texture, made on first use. fn staging(resource: This, texture: &ID3D12Resource) -> Option> { + // Asked before the table is locked: the sweep lets go of a staging + // buffer with its texture's host side locked, in that order. + let on_demand = crate::resource::host_tiled(resource).is_some(); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); if let Some(s) = map.get(&(resource as usize)) { @@ -1162,6 +1420,10 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { dirty: std::sync::atomic::AtomicBool::new(true), uploaded: std::sync::atomic::AtomicBool::new(false), used: std::sync::atomic::AtomicU64::new(crate::host::moment()), + on_demand, + detiled: std::sync::atomic::AtomicU32::new(0), + judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], + waiting: std::sync::atomic::AtomicU64::new(0), }); map.insert(resource as usize, s.clone()); Some(s) diff --git a/crates/victory-gpu/src/tiles.rs b/crates/victory-gpu/src/tiles.rs new file mode 100644 index 00000000..a8b98f63 --- /dev/null +++ b/crates/victory-gpu/src/tiles.rs @@ -0,0 +1,1419 @@ +//! Levels on demand: host copies of title textures that take the card's +//! memory level by level, as the title holds the levels. +//! +//! The title places a texture's whole chain of levels in its address space +//! and holds only some of them: the smallest first, at the start of the +//! texture's memory. The memory of the larger ones is either not mapped, +//! or belongs to the next texture, which the title packs where they would +//! be (run 188). A host copy was a committed texture: every level of it +//! took the card's memory from the first upload on. Run 189's accounting +//! line counted 2.2 to 3.0 GB of 4.3 to 5.5 GB of host copies in levels +//! whose title memory was not mapped, on some 1,600 copies; with about +//! 2.2 to 3.1 GB of render targets that filled the card, and textures +//! that needed a new host copy waited for room (the main character's face +//! among them, runs 188 and 189). +//! +//! Here such a texture is a reserved one (`CreateReservedResource`): it has +//! every level, so level numbers and sizes are what they were, but no +//! memory. The rules: +//! - A level is given tiles of a heap of ours (`UpdateTileMappings`, on the +//! queue) only in a submission-time step of a list that also writes all +//! of that level: the upload of the texture (`texture.rs` `upload`, which +//! copies every level from the staging buffer every time), or, before +//! the card itself writes the texture (a copy, a resolve), an upload of +//! every level with every level given (`texture.rs` `make_whole`). The +//! step runs when the list is submitted, before the list is executed, so +//! the mapping is ahead of the copy on the queue. Tiles hold what their +//! last owner left; no level is shown before it is written whole. +//! - Which levels are held is said by one function, at the moment the +//! staging buffer is filled (`Staging::held_levels`): the levels whose +//! title memory is mapped and lies before the start of the next texture +//! placed in this one's span. The staging buffer holds zeros for the +//! others, and the step gives tiles by that same answer. +//! - The small levels the card packs into shared tiles are given together +//! when any of them is held; the upload writes all of them (zeros for +//! the ones not held). +//! - A shader must not reach a level without memory (it reads zeros: a +//! black texture). The host view of a slot is made from the first level +//! that is held and has tiles ([`show_from`], `descriptor/host.rs` +//! `make`), and the slots of a texture are made again when that level +//! changes (`HostHeap::texture_views_remade`). +//! - shortcut: tiles are not taken back while the host copy lives. A level +//! the title lets go of, or that turns out to be the next texture's, +//! keeps its tiles; it is hidden by the views and written with zeros at +//! the next upload. Its tiles go back when the host copy does. +//! +//! Only for a texture the title places in memory and fills, two-dimensional, +//! one layer, more than one level, of [`floor`] bytes or more, whose memory +//! is not all its own when the host copy is made (`resource.rs` `hosted`); +//! every other texture is made as before. Off unless +//! `VICTORY_LEVELS_ON_DEMAND=1`. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::host; + +/// The card's tile: 64 KiB. +const TILE: u64 = 64 << 10; + +/// Tiles in one heap of the pool (64 MiB). The largest level given is a +/// 4096x4096 one of one byte a texel: 256 tiles. +const HEAP_TILES: u32 = 1024; + +/// Since the start, or now: such textures alive; the bytes all their +/// levels would take; the bytes of the tiles given to them; the bytes of +/// the pool's heaps; such textures made in all; levels given; calls of +/// `UpdateTileMappings`; their microseconds; heaps given back to the card; +/// uploads that left a held level without tiles (the card had no room, or +/// no heap could be had); uploads recorded again for such a level. +pub(crate) static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + +/// Whether textures are made this way: the switch +/// (`VICTORY_LEVELS_ON_DEMAND=1`; off by default), and a card that reads +/// zeros from, and drops writes to, levels without memory (tiled resources +/// tier 2). +pub(crate) fn wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var_os("VICTORY_LEVELS_ON_DEMAND").is_some_and(|v| v == "1") { + return false; + } + let Some(host) = host() else { + return false; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query into a struct of its own size. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let tier = options.TiledResourcesTier.0; + let on = asked.is_ok() && tier >= 2; + tracing::info!( + tier, + on, + floor_kb = floor() >> 10, + "host copies of title textures take the card's memory level by level (VICTORY_LEVELS_ON_DEMAND=1)" + ); + on + }) +} + +/// The bytes from which a texture is made this way: a megabyte, or +/// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not +/// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six +/// tiles at most, and most of the calls for nothing.) +pub(crate) fn floor() -> u64 { + static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); + *BYTES.get_or_init(|| { + std::env::var("VICTORY_LEVELS_MIN_KB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(1 << 20, |kb| kb.max(64) << 10) + }) +} + +/// The bytes of the tiles given to textures now: the card's memory they +/// hold (`resource.rs` `room` counts it with the other host copies). +pub(crate) fn given_total() -> u64 { + STATS[2].load(Ordering::Relaxed) +} + +/// One heap of the pool and its free runs of tiles (first tile, tiles), in +/// order, no two touching. +struct Heap { + heap: ID3D12Heap, + free: Vec<(u32, u32)>, +} + +// SAFETY: a heap of the device, named only in queue and device calls, which +// any thread may make; its free runs are plain numbers behind `POOL`'s lock. +unsafe impl Send for Heap {} + +impl Heap { + fn free_tiles(&self) -> u32 { + self.free.iter().map(|run| run.1).sum() + } +} + +/// The pool's heaps by place; a place is empty after its heap went back to +/// the card (a texture names its heaps by place). +static POOL: Mutex>> = Mutex::new(Vec::new()); + +/// `count` tiles of one heap, in as many runs as it takes, the lowest free +/// tiles first (single free tiles are used up before a long run is cut): +/// the heap, its place in the pool and the runs (first tile, tiles). A new +/// heap is made when no heap has that many free. +fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u32, u32)>)> { + if count == 0 || count > HEAP_TILES { + return None; + } + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let found = pool.iter().position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count)); + let index = match found { + Some(index) => index, + None => { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u64::from(HEAP_TILES) * TILE, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut made: Option = None; + // SAFETY: plain creation; the out pointer is ours. + if let Err(e) = unsafe { device.CreateHeap::(&raw const desc, &raw mut made) } { + tracing::warn!(error = %e, "no heap for texture levels given on demand: those levels stay empty"); + return None; + } + let fresh = Heap { + heap: made?, + free: vec![(0, HEAP_TILES)], + }; + STATS[3].fetch_add(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + match pool.iter().position(Option::is_none) { + Some(index) => { + pool[index] = Some(fresh); + index + } + None => { + pool.push(Some(fresh)); + pool.len() - 1 + } + } + } + }; + let h = pool[index].as_mut()?; + let mut runs = Vec::new(); + let mut left = count; + while left > 0 { + let &(start, tiles) = h.free.first()?; + let part = tiles.min(left); + runs.push((start, part)); + if part == tiles { + h.free.remove(0); + } else { + h.free[0] = (start + part, tiles - part); + } + left -= part; + } + Some((h.heap.clone(), index, runs)) +} + +/// Gives the runs `runs` of the pool's heap at `index` back; runs that +/// touch become one. A heap with every tile free goes back to the card, +/// unless it is the pool's only one. (Called when the texture that held +/// the tiles is dropped: nothing on the card reads through its mappings +/// any more, as for any host texture that is dropped.) +fn give_back(index: usize, runs: &[(u32, u32)]) { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(h)) = pool.get_mut(index) else { + return; + }; + h.free.extend_from_slice(runs); + h.free.sort_unstable(); + let mut joined: Vec<(u32, u32)> = Vec::with_capacity(h.free.len()); + for &(from, tiles) in &h.free { + match joined.last_mut() { + Some(last) if last.0 + last.1 == from => last.1 += tiles, + _ => joined.push((from, tiles)), + } + } + h.free = joined; + let all_free = h.free_tiles() == HEAP_TILES; + if all_free && pool.iter().flatten().count() > 1 { + pool[index] = None; + STATS[3].fetch_sub(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + STATS[8].fetch_add(1, Ordering::Relaxed); + } +} + +/// What is given so far to one texture. +struct Given { + /// Per level with tiles of its own: whether it has them. + levels: Vec, + /// Whether the small levels the card packs together have theirs. + packed: bool, + /// The runs taken: the heap's place, first tile, tiles. + runs: Vec<(usize, u32, u32)>, +} + +/// A host texture made without memory, and the tiles its levels have been +/// given. +pub(crate) struct Tiled { + /// Tiles of each level that has tiles of its own (level 0 first). + standard: Vec, + /// The tiles of the levels the card packs together (0: there are none); + /// they are the levels from `standard.len()` on. + packed: u32, + /// Levels in all. + levels: u32, + /// The bytes all its tiles would take. + pub(crate) full: u64, + given: Mutex, + /// The first level a view of the texture may show: the first one that + /// is held or was written by the card and has tiles (`u32::MAX`: none + /// yet). + shown: AtomicU32, + /// The levels held at the last upload (a bit a level). + held: AtomicU32, + /// The levels the card itself wrote, in lists submitted so far. + card: AtomicU32, + /// The levels a recorded list of the card's own writes has already + /// written with zeros first ([`Tiled::claim`]). + claimed: AtomicU32, +} + +impl Tiled { + /// For `texture`, just made reserved with `levels` levels and one + /// layer: how the card cuts it into tiles. `None` if the card will not + /// say, or cuts it in a way this does not handle; the caller then makes + /// the texture the old way. + pub(crate) fn make(device: &ID3D12Device, texture: &ID3D12Resource, levels: u32) -> Option { + if levels == 0 || levels > 16 { + return None; + } + let mut total = 0u32; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut shape = D3D12_TILE_SHAPE::default(); + let mut count = levels; + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); levels as usize]; + // SAFETY: outputs of our own, `count` tilings of them. + unsafe { + device.GetResourceTiling( + texture, + Some(&raw mut total), + Some(&raw mut packed), + Some(&raw mut shape), + Some(&raw mut count), + 0, + tilings.as_mut_ptr(), + ); + } + let standard_levels = u32::from(packed.NumStandardMips); + if total == 0 || standard_levels + u32::from(packed.NumPackedMips) != levels || standard_levels > count { + return None; + } + let mut standard = Vec::with_capacity(standard_levels as usize); + for tiling in &tilings[..standard_levels as usize] { + let tiles = tiling.WidthInTiles * u32::from(tiling.HeightInTiles) * u32::from(tiling.DepthInTiles); + if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { + return None; + } + standard.push(tiles); + } + let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; + if packed_tiles > HEAP_TILES { + return None; + } + let full = u64::from(total) * TILE; + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(full, Ordering::Relaxed); + STATS[4].fetch_add(1, Ordering::Relaxed); + Some(Tiled { + given: Mutex::new(Given { + levels: vec![false; standard.len()], + packed: false, + runs: Vec::new(), + }), + standard, + packed: packed_tiles, + levels, + full, + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + claimed: AtomicU32::new(0), + }) + } + + /// At the submission of a list that uploads every level of `texture` + /// from its staging buffer, of which `held` are the title's now (the + /// others are zeros there): tiles for the held ones that have none. + /// `room`: whether the card has room for more host copies + /// (`resource.rs` `room`). Without room no held level gets tiles: the + /// list still brings the levels that have theirs up to date (which + /// takes none of the card's memory), and its copies into the others go + /// nowhere. (An upload of a host copy that exists passes the full + /// card's gate in `draw.rs` on the ground that it takes no memory; + /// with tiles given here regardless, the line would not bound these + /// textures.) + /// Returns whether the first level a view may show changed, and + /// whether a level named is still without tiles (no room, or no heap + /// could be had): the caller has the upload recorded again later, or + /// the level would stay empty until the title writes the texture. + pub(crate) fn uploaded(&self, texture: &ID3D12Resource, held: u32, room: bool) -> (bool, bool) { + match host() { + Some(host) => self.uploaded_on(host.queue(), &host.device, texture, held, room), + None => (false, false), + } + } + + /// [`Tiled::uploaded`] on a queue and a device. + pub(crate) fn uploaded_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + held: u32, + room: bool, + ) -> (bool, bool) { + self.held.store(held, Ordering::Relaxed); + let card = self.card.load(Ordering::Relaxed); + let named = held | card; + // The levels the card itself writes are few and are not kept + // waiting: a write of the card's into no memory is lost. + let changed = self.give_on(queue, device, texture, named, if room { named } else { card }); + (changed, self.without(named) != 0) + } + + /// At the submission of a list in which the card itself writes the + /// levels `levels` of `texture` (after zeros, if they were new: + /// [`Tiled::claim`]): tiles for those that have none. Returns whether + /// the first level a view may show changed. + /// Only the levels this list writes get tiles here: a held level that + /// is waiting for room is written by no copy of this list, and tiles + /// hold what their last owner left. + pub(crate) fn card_wrote(&self, texture: &ID3D12Resource, levels: u32) -> bool { + match host() { + Some(host) => self.card_wrote_on(host.queue(), &host.device, texture, levels), + None => false, + } + } + + /// [`Tiled::card_wrote`] on a queue and a device. + pub(crate) fn card_wrote_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + levels: u32, + ) -> bool { + let card = self.card.fetch_or(levels, Ordering::Relaxed) | levels; + let changed = self.give_on(queue, device, texture, card | self.held.load(Ordering::Relaxed), levels); + // A level that got no tiles (no heap could be had): the list's + // zeros and its write went nowhere, so the next list that writes + // the level sends its zeros again. + let without = self.without(levels); + if without != 0 { + self.unclaim(without); + } + changed + } + + /// The bits of the levels that get their tiles with level `level`: + /// itself, or every level the card packs together if it is one of them. + pub(crate) fn with_level(&self, level: u32) -> u32 { + let first_packed = self.standard.len() as u32; + if level < first_packed { + 1 << level + } else if level < self.levels { + self.every_level() & !((1u32 << first_packed) - 1) + } else { + 0 + } + } + + /// Of `levels`, the ones that have no tiles now and that no list + /// recorded before has claimed: the caller's list writes them with + /// zeros before the card's own write, so that what the write does not + /// cover is not what the tiles' last owner left. + pub(crate) fn claim(&self, levels: u32) -> u32 { + let fresh = self.without(levels); + fresh & !self.claimed.fetch_or(fresh, Ordering::Relaxed) + } + + /// Gives up the claim on `levels` ([`Tiled::claim`]): the zeros of the + /// list that claimed them never reached tiles of theirs (the list was + /// reset without being submitted, the zeros could not be recorded, or + /// no tiles could be had), so the next list that writes them sends its + /// own. + /// shortcut: a second list recorded between the claim and this sends + /// no zeros; if it is the first whose write gets tiles, what that + /// write does not cover is what the tiles' last owner left. + pub(crate) fn unclaim(&self, levels: u32) { + self.claimed.fetch_and(!levels, Ordering::Relaxed); + } + + /// Of `levels` (a bit a level), the ones that have no tiles now. + pub(crate) fn without(&self, levels: u32) -> u32 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let first_packed = self.standard.len() as u32; + let mut without = 0; + for level in 0..self.levels.min(32) { + let has = if level < first_packed { given.levels[level as usize] } else { given.packed }; + if !has { + without |= 1 << level; + } + } + levels & without + } + + /// Gives tiles to the levels of `texture` that both `named` and `may` + /// name (a bit a level, level 0 the lowest) and that have none yet; + /// the levels the card packs together get theirs when any of them is + /// so named. `named`: the levels that are the title's or the card's + /// own, by which the first level a view may show is told; `may`: the + /// ones of them that may get tiles in this call. To be called only + /// from a submission-time step of a list that writes every level of + /// `may`, whole: the call is ahead of that list on `queue`, and tiles + /// hold what their last owner left. + /// Returns whether the first level a view may show changed + /// ([`Tiled::first_shown`]): the caller has the texture's slots made + /// again. + pub(crate) fn give_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, + ) -> bool { + let has = |level: u32| level < 32 && named & (1 << level) != 0; + let now = |level: u32| level < 32 && named & may & (1 << level) != 0; + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let first_packed = self.standard.len() as u32; + // (subresource, tiles, the level if it has tiles of its own) to map now. + let mut wanted: Vec<(u32, u32, Option)> = Vec::new(); + for level in 0..first_packed { + if !given.levels[level as usize] && now(level) { + wanted.push((level, self.standard[level as usize], Some(level as usize))); + } + } + if self.packed > 0 && !given.packed && (first_packed..self.levels).any(now) { + wanted.push((first_packed, self.packed, None)); + } + for (subresource, tiles, level) in wanted { + let Some((heap, index, runs)) = take(device, tiles) else { + continue; + }; + let at = D3D12_TILED_RESOURCE_COORDINATE { + X: 0, + Y: 0, + Z: 0, + Subresource: subresource, + }; + let size = D3D12_TILE_REGION_SIZE { + NumTiles: tiles, + ..Default::default() + }; + // One region, the subresource's tiles in order, on as many + // ranges of the heap as the runs taken. + let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; runs.len()]; + let starts: Vec = runs.iter().map(|run| run.0).collect(); + let counts: Vec = runs.iter().map(|run| run.1).collect(); + let began = std::time::Instant::now(); + // SAFETY: a live reserved texture and a live heap of ours; one + // region of `tiles` tiles from the subresource's first tile; + // `runs.len()` ranges whose counts add up to `tiles`, in three + // arrays of that length that live through the call. + unsafe { + queue.UpdateTileMappings( + texture, + 1, + Some(&raw const at), + Some(&raw const size), + &heap, + runs.len() as u32, + Some(flags.as_ptr()), + Some(starts.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + STATS[6].fetch_add(1, Ordering::Relaxed); + STATS[7].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + match level { + Some(level) => given.levels[level] = true, + None => given.packed = true, + } + for &(start, count) in &runs { + given.runs.push((index, start, count)); + } + STATS[2].fetch_add(u64::from(tiles) * TILE, Ordering::Relaxed); + STATS[5].fetch_add(1, Ordering::Relaxed); + } + let with_tiles = |level: u32| { + if level < first_packed { + given.levels[level as usize] + } else { + given.packed + } + }; + let shown = (0..self.levels).find(|&level| has(level) && with_tiles(level)).unwrap_or(u32::MAX); + self.shown.swap(shown, Ordering::Relaxed) != shown + } + + /// The first level a view of the texture may show; `None` while no + /// level is both held and given (the views are then as the title made + /// them, and read zeros). + pub(crate) fn first_shown(&self) -> Option { + let shown = self.shown.load(Ordering::Relaxed); + (shown != u32::MAX).then_some(shown) + } + + /// Whether level `level` has tiles. + #[cfg(test)] + fn has_tiles(&self, level: u32) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + match given.levels.get(level as usize) { + Some(&has) => has, + None => level < self.levels && given.packed, + } + } + + /// Whether every level has tiles. + #[cfg(test)] + fn whole(&self) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.levels.iter().all(|&has| has) && (self.packed == 0 || given.packed) + } + + /// A bit for every level of the texture. + pub(crate) fn every_level(&self) -> u32 { + if self.levels >= 32 { u32::MAX } else { (1 << self.levels) - 1 } + } + + /// The bytes of the tiles it has now. + pub(crate) fn given_bytes(&self) -> u64 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.runs.iter().map(|run| u64::from(run.2) * TILE).sum() + } +} + +impl Drop for Tiled { + fn drop(&mut self) { + let given = self.given.get_mut().unwrap_or_else(|e| e.into_inner()); + let mut bytes = 0; + let mut by_heap: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for &(index, start, tiles) in &given.runs { + by_heap.entry(index).or_default().push((start, tiles)); + bytes += u64::from(tiles) * TILE; + } + for (index, runs) in by_heap { + give_back(index, &runs); + } + STATS[0].fetch_sub(1, Ordering::Relaxed); + STATS[1].fetch_sub(self.full, Ordering::Relaxed); + STATS[2].fetch_sub(bytes, Ordering::Relaxed); + } +} + +/// Keeps a two-dimensional shader view from the levels before `first` of a +/// texture of `levels` levels: it starts at `first` if it started before +/// it, and shows as many levels fewer. A sample then lands on the first +/// level that has memory instead of reading zeros from one that has none; +/// level numbers and sizes a shader asks for count from that level. +pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) { + if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || first >= levels { + return; + } + // SAFETY: a 2D view's member of the union. + let view = unsafe { &mut desc.Anonymous.Texture2D }; + if first <= view.MostDetailedMip { + return; + } + let fewer = first - view.MostDetailedMip; + view.MostDetailedMip = first; + if view.MipLevels != u32::MAX { + view.MipLevels = view.MipLevels.saturating_sub(fewer).max(1); + } +} + +/// For the log, with the texture queue's line: what this saves, and what +/// the mapping calls cost since the line before. +pub(crate) fn status() { + static BEFORE: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + if s[4] == 0 { + return; + } + let calls = s[6] - BEFORE[0].swap(s[6], Ordering::Relaxed); + let micros = s[7] - BEFORE[1].swap(s[7], Ordering::Relaxed); + tracing::info!( + "textures with levels on demand: {} alive ({} made so far), {} MB of the card given to {} levels in all, \ + {} MB of the card not allocated for levels the title does not hold ({} MB if every level had memory); \ + the pool's heaps {} MB ({} given back to the card so far); since the line before: {} calls of \ + UpdateTileMappings in {} microseconds; in all {} calls, {} microseconds; {} uploads left a held \ + level without memory (no room on the card, or no heap), {} uploads were recorded again for one", + s[0], + s[4], + s[2] >> 20, + s[5], + s[1].saturating_sub(s[2]) >> 20, + s[1] >> 20, + s[3] >> 20, + s[8], + calls, + micros, + s[6], + s[7], + s[9], + s[10], + ); +} + +/// On the card, without the title: what levels on demand relies on, with +/// the pool and the mapping call of this module on a device of the test's +/// own. One test, one device: the pool is one for the process, and its +/// heaps belong to the device that made them. +/// +/// Run by name, alone, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored levels_on_demand --nocapture` +/// +/// It runs on the SOFTWARE adapter unless `VICTORY_TILES_TEST_CARD=1`: on +/// that adapter nothing reaches the card or its driver, so nothing it does +/// can reset the driver or touch the screen. Wherever it runs, the debug +/// layer is switched on if Windows has it (the optional feature "Graphics +/// Tools"), its messages are printed after every step, and the test stops +/// at the first error or lost device with the step's name, before +/// anything else is sent. On the card it does not run without the layer, +/// and no wait is longer than 1.5 s. +#[cfg(test)] +mod tests { + use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use super::*; + use crate::host::{compile, transition, warp_adapter}; + + const SIDE: u32 = 1024; + const LEVELS: u16 = 11; + + /// Two views of one texture read at the same place and level: the + /// first as the layer makes it for a texture whose level 0 has no + /// memory, the second as the title asked. + const LOOK: &str = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors = 2)), UAV(u0), StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT)" +Texture2D clamped : register(t0); +Texture2D whole : register(t1); +SamplerState nearest : register(s0); +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void look() { + float4 a = clamped.SampleLevel(nearest, float2(0.3, 0.3), 0); + float4 b = whole.SampleLevel(nearest, float2(0.3, 0.3), 0); + words.Store(0, (uint)(a.x * 255.0 + 0.5)); + words.Store(4, (uint)(b.x * 255.0 + 0.5)); +} +"#; + + /// Where each level of a texture lies in a buffer of all of them: its + /// place, its rows, the bytes of a row that are the level's own, and + /// the buffer's bytes. + struct Laid { + footprints: Vec, + rows: Vec, + wide: Vec, + total: u64, + } + + struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + event: HANDLE, + submitted: u64, + /// The debug layer's messages, if Windows has the layer. + messages: Option, + /// What the test is doing, for the message when it stops. + step: &'static str, + /// On the card, not on the software adapter. + card: bool, + } + + impl Rig { + /// The software adapter, or the default one with + /// `VICTORY_TILES_TEST_CARD=1`; `None` without one, without tiled + /// resources of tier 2, or on the card without the debug layer. + fn new() -> Option { + // SAFETY: plain object creation on a device of our own. + unsafe { + let card = std::env::var_os("VICTORY_TILES_TEST_CARD").is_some_and(|v| v == "1"); + // The debug layer, before the device is made: a call that + // is not well formed is then refused and named by the + // runtime, not handed to the driver. + let mut layer: Option = None; + let layered = D3D12GetDebugInterface(&mut layer).is_ok() && layer.is_some(); + layer.iter().for_each(|l| l.EnableDebugLayer()); + if card && !layered { + eprintln!("no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it"); + return None; + } + let mut device: Option = None; + if card { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } else { + let adapter = warp_adapter().ok()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } + let device = device?; + let messages = device.cast::().ok(); + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .ok()?; + eprintln!( + "levels on demand, {}: tiled resources tier {}, debug layer {}", + if card { "ON THE CARD" } else { "on the software adapter" }, + options.TiledResourcesTier.0, + if messages.is_some() { "on" } else { "not installed" } + ); + if options.TiledResourcesTier.0 < 2 { + return None; + } + 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()?; + Some(Rig { + device, + queue, + allocator, + list, + fence, + event, + submitted: 0, + messages, + step: "making the device", + card, + }) + } + } + + /// Prints what the debug layer said since the last call; the first + /// error among it (as `host.rs` `log_messages` reads them). + fn said(&self) -> Option { + let queue = self.messages.as_ref()?; + let mut first_error = None; + // SAFETY: each message is read into a buffer of the size the + // queue reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + eprintln!("D3D12 says (severity {}, id {}): {text}", m.Severity.0, m.ID.0); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } + } + } + queue.ClearStoredMessages(); + } + first_error + } + + /// Stops the test, naming the step, if the device is lost or the + /// debug layer reported an error: nothing more is sent after it. + fn check(&self, what: &str) { + let error = self.said(); + // SAFETY: a plain query. + let removed = unsafe { self.device.GetDeviceRemovedReason() }; + assert!(removed.is_ok(), "{}, {what}: the device is lost: {removed:?}", self.step); + assert!(error.is_none(), "{}, {what}: the debug layer reports an error: {}", self.step, error.unwrap_or_default()); + } + + /// Gives tiles as a submission would, and stops if the mapping + /// call was refused. + fn give(&self, tiled: &Tiled, texture: &ID3D12Resource, levels: u32) { + tiled.give_on(&self.queue, &self.device, texture, levels, levels); + self.check("tiles given"); + } + + /// Records with `record`, runs the list behind what is already on + /// the queue (tile mappings among it), waits for the card and + /// opens the list again. + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) { + record(&self.list); + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + // Never without end: a step is a few copies of a few + // megabytes. On the card the limit stays under Windows' own + // two seconds; the software adapter, which compiles its + // shader on first use and resets nothing, gets longer. + let limit = if self.card { 1500 } else { 20_000 }; + let waited = WaitForSingleObject(self.event, limit); + self.check("a submission"); + assert!( + waited == WAIT_OBJECT_0, + "{}: a submission did not finish within {limit} ms; stopped before another is sent", + self.step + ); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + fn buffer(&self, kind: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES, bytes: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + 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 out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + /// A square texture description of `side` texels and `levels` + /// levels; `reserved`: in the layout a texture without memory of + /// its own must have. + fn desc(format: DXGI_FORMAT, side: u32, levels: u16, reserved: bool) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(side), + Height: side, + DepthOrArraySize: 1, + MipLevels: levels, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN }, + ..Default::default() + } + } + + /// A texture without memory, in the state copies into it need, and + /// how the card cuts it. + fn reserved(&self, desc: &D3D12_RESOURCE_DESC) -> (ID3D12Resource, Tiled) { + let mut made: Option = None; + // SAFETY: plain creation; a texture that is no target has no clear value. + let asked = unsafe { + self.device + .CreateReservedResource(desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + }; + // The layer's reason first, if it refused. + self.check("a texture without memory made"); + asked.expect("a reserved texture"); + let texture = made.expect("a reserved texture"); + let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)).expect("the card says how it cuts the texture"); + (texture, tiled) + } + + fn footprints(&self, desc: &D3D12_RESOURCE_DESC) -> Laid { + let levels = usize::from(desc.MipLevels); + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels]; + let mut rows = vec![0u32; levels]; + let mut wide = vec![0u64; levels]; + let mut total = 0u64; + // SAFETY: outputs for `levels` subresources. + unsafe { + self.device.GetCopyableFootprints( + desc, + 0, + levels as u32, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + Some(wide.as_mut_ptr()), + Some(&mut total), + ); + } + Laid { + footprints, + rows, + wide, + total, + } + } + + /// An upload buffer of `total` bytes in which the bytes of each + /// level are `byte(level)`. + fn filled(&self, layout: &Laid, byte: impl Fn(usize) -> u8) -> ID3D12Resource { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let upload = self.buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, layout.total); + // SAFETY: the buffer is `total` bytes; each level's rows lie inside it. + unsafe { + let mut data = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let len = rows[level] as usize * f.Footprint.RowPitch as usize; + std::slice::from_raw_parts_mut(data.cast::().add(f.Offset as usize), len).fill(byte(level)); + } + upload.Unmap(0, None); + } + upload + } + + /// Copies every level of `texture` from `upload`, then every level + /// back, and gives for each level the first sixteen bytes read of + /// its first row and of the row and column half way (another tile + /// of a level of several). + fn round_trip( + &mut self, + texture: &ID3D12Resource, + layout: &Laid, + upload: Option<&ID3D12Resource>, + ) -> Vec<[Vec; 2]> { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let back = self.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, layout.total); + self.run(|list| { + // SAFETY: an open list; the texture and buffers outlive the run. + unsafe { + if let Some(upload) = upload { + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&sub(texture, level as u32), 0, 0, 0, &placed(upload, *f), None); + } + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&placed(&back, *f), 0, 0, 0, &sub(texture, level as u32), None); + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + }); + let mut read = Vec::new(); + // SAFETY: a read-back buffer of `total` bytes the finished list copied into. + unsafe { + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let pitch = f.Footprint.RowPitch as usize; + let len = rows[level] as usize * pitch; + let bytes = std::slice::from_raw_parts(data.cast::().cast_const().add(f.Offset as usize), len); + // The bytes of a row that are the level's own (its + // blocks or texels; the rest of the pitch is padding). + let own = layout.wide[level] as usize; + let wide = own.min(len).min(16); + let first = bytes[..wide].to_vec(); + let middle = (rows[level] as usize / 2) * pitch + ((own / 2) & !15); + let far = if rows[level] >= 2 && own >= 32 && middle + wide <= len { + bytes[middle..middle + wide].to_vec() + } else { + first.clone() + }; + read.push([first, far]); + } + back.Unmap(0, None); + } + read + } + } + + fn sub(texture: &ID3D12Resource, index: u32) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: index }, + } + } + + fn placed(buffer: &ID3D12Resource, footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + } + } + + fn all(bytes: &[Vec; 2], want: u8) -> bool { + bytes.iter().all(|part| part.iter().all(|&b| b == want)) + } + + /// The levels from `first` on, a bit a level. + fn from_level(first: u32) -> u32 { + (u32::MAX << first) & ((1 << u32::from(LEVELS)) - 1) + } + + /// (i) Levels arrive one by one: after each step every level with + /// tiles reads back its own bytes and every level without reads zeros. + fn levels_arrive(rig: &mut Rig, format: DXGI_FORMAT) { + rig.step = if format == DXGI_FORMAT_BC7_UNORM { "step 1, levels arrive (BC7)" } else { "step 1, levels arrive (BC3)" }; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + // (The card packs the levels smaller than a tile into shared + // tiles; the software adapter may give each its own.) + eprintln!( + "format {}: {} levels with tiles of their own ({:?} tiles), {} tiles for the packed ones", + format.0, + tiled.standard.len(), + tiled.standard, + tiled.packed + ); + assert!(!rig.card || tiled.packed > 0, "on the card a 1024 texture has levels smaller than a tile"); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + for first in [3u32, 1, 0] { + // Ahead of the list on the queue, as at a submission. + rig.give(&tiled, &texture, from_level(first)); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", format.0); + } + } + assert!(tiled.whole()); + assert_eq!(tiled.first_shown(), Some(0)); + } + + /// (ii) A copy on the card into a level without tiles is dropped; the + /// same copy in a list that runs after the level was given lands. + fn a_card_copy_lands_after_the_give(rig: &mut Rig) { + rig.step = "step 2, a copy on the card into a level without tiles"; + let format = DXGI_FORMAT_BC7_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + // The last level with tiles of its own, and a texture of its size + // with every byte 0x5a to copy from. + let level = tiled.standard.len() as u32 - 1; + let source_desc = Rig::desc(format, SIDE >> level, 1, false); + let source_layout = rig.footprints(&source_desc); + let source_bytes = rig.filled(&source_layout, |_| 0x5a); + let mut made: Option = None; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + // SAFETY: plain texture creation. + unsafe { + rig.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + } + let source = made.unwrap(); + rig.run(|list| { + // SAFETY: an open list and live resources. + unsafe { + list.CopyTextureRegion(&sub(&source, 0), 0, 0, 0, &placed(&source_bytes, source_layout.footprints[0]), None); + list.ResourceBarrier(&[transition(&source, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + // No tiles yet: this copy goes nowhere. + list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None); + } + }); + let before = rig.round_trip(&texture, &layout, None); + assert!(all(&before[level as usize], 0), "a copy into a level without tiles left {:?}", before[level as usize]); + // As `texture.rs` `card_writes` has it: the give at the list's + // submission, the copy in the list. + assert_ne!(tiled.claim(tiled.with_level(level)), 0, "the level is new"); + rig.give(&tiled, &texture, tiled.with_level(level)); + rig.run(|list| { + // SAFETY: as above. + unsafe { list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) }; + }); + let after = rig.round_trip(&texture, &layout, None); + assert!(all(&after[level as usize], 0x5a), "the copy after the give left {:?}", after[level as usize]); + assert_eq!(tiled.claim(tiled.with_level(level)), 0, "claimed once"); + } + + /// (iii) Tiles a texture gave back go to the next one, which reads + /// what was written into it and zeros where it has no tiles; what a + /// level given and not written reads is printed (the reason no level + /// is given outside a list that writes it). + fn a_reused_tile_reads_as_written(rig: &mut Rig) { + rig.step = "step 3, a reused tile"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (first, first_tiles) = rig.reserved(&desc); + let level = first_tiles.standard.len() as u32 - 1; + rig.give(&first_tiles, &first, 1 << level); + let upload = rig.filled(&layout, |_| 0xa5); + let read = rig.round_trip(&first, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0xa5)); + let runs = first_tiles.given.lock().unwrap().runs.clone(); + drop(first_tiles); + drop(first); + let (second, second_tiles) = rig.reserved(&desc); + rig.give(&second_tiles, &second, 1 << level); + let reused = second_tiles.given.lock().unwrap().runs == runs; + let unwritten = rig.round_trip(&second, &layout, None); + eprintln!( + "a level given tiles and not written reads {:?} (its tiles are the first texture's: {reused})", + &unwritten[level as usize][0][..4] + ); + let upload = rig.filled(&layout, |_| 0x3c); + let read = rig.round_trip(&second, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0x3c), "the reused level reads {:?}", read[level as usize]); + assert!(all(&read[0], 0), "level 0 has no tiles and reads {:?}", read[0]); + } + + /// (iv) A level whose tiles come from several runs of the heap (single + /// free tiles between taken ones) reads as written in every tile. + fn a_level_on_several_ranges(rig: &mut Rig) { + rig.step = "step 4, a level on several ranges of the heap"; + // Three single tiles; the first and the last go back, the middle + // one stays taken. + let singles: Vec<_> = (0..3).map(|_| take(&rig.device, 1).expect("a tile")).collect(); + give_back(singles[0].1, &singles[0].2); + give_back(singles[2].1, &singles[2].2); + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Level 1 of a 1024 texture: four tiles. + assert!(tiled.standard.len() > 1 && tiled.standard[1] >= 2); + rig.give(&tiled, &texture, 1 << 1); + let runs = tiled.given.lock().unwrap().runs.len(); + eprintln!("level 1 ({} tiles) was mapped on {runs} ranges", tiled.standard[1]); + assert!(runs >= 2, "the single free tiles were not used first"); + let upload = rig.filled(&layout, |_| 0x77); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + assert!(all(&read[1], 0x77), "level 1 reads {:?}", read[1]); + give_back(singles[1].1, &singles[1].2); + } + + /// (v) A view made by [`show_from`] of a texture whose level 0 has no + /// tiles returns level 1's colour for a sample at level 0; the view as + /// the title asked returns zero. + fn the_view_starts_at_the_first_level_with_tiles(rig: &mut Rig) -> Option<()> { + rig.step = "step 5, the view from the first level with tiles"; + let cs = compile(LOOK, s!("look"), s!("cs_5_1")).ok()?; + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Every level but the largest; each level's bytes are sixteen + // times its number plus one. + rig.give(&tiled, &texture, from_level(1)); + assert_eq!(tiled.first_shown(), Some(1)); + let upload = rig.filled(&layout, |level| (level as u8 + 1) * 16); + rig.round_trip(&texture, &layout, Some(&upload)); + // SAFETY: plain object creation; the views are made in a heap + // that lives to the end of the function, of a live texture. + let (root, pipeline, views, words, back) = unsafe { + let root: ID3D12RootSignature = rig.device.CreateRootSignature(0, &cs[..]).ok()?; + let pipeline: ID3D12PipelineState = rig + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + let views: ID3D12DescriptorHeap = rig + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let as_asked = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + let mut shown = as_asked; + show_from(&mut shown, tiled.first_shown()?, u32::from(LEVELS)); + assert_eq!(shown.Anonymous.Texture2D.MostDetailedMip, 1); + let step = rig.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + rig.device.CreateShaderResourceView(&texture, Some(&raw const shown), at); + at.ptr += step; + rig.device.CreateShaderResourceView(&texture, Some(&raw const as_asked), at); + let words = rig.buffer( + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + 256, + ); + let back = rig.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, 256); + (root, pipeline, views, words, back) + }; + // Before the one dispatch: the pipeline and both views are sound. + rig.check("the pipeline and the views made"); + rig.run(|list| { + // SAFETY: an open list and live objects. + unsafe { + list.ResourceBarrier(&[transition(&texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetComputeRootDescriptorTable(0, views.GetGPUDescriptorHandleForHeapStart()); + list.SetComputeRootUnorderedAccessView(1, words.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&words, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&back, 0, &words, 0, 16); + } + }); + // SAFETY: a read-back buffer the finished list copied sixteen bytes into. + let read = unsafe { + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let read = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + back.Unmap(0, None); + read + }; + eprintln!("a sample at level 0: {} through the view from level 1, {} through the view as asked", read[0], read[1]); + assert_eq!(read[0], 32, "the view from the first level with tiles reads level 1"); + assert_eq!(read[1], 0, "the view from level 0 reads a level without tiles"); + Some(()) + } + + fn a_full_card_keeps_new_levels_waiting(rig: &mut Rig) { + rig.step = "step 6, no room on the card: held levels wait, and get their tiles when asked again"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + let read_as_given = |rig: &mut Rig, what: &str| { + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "{what}: level {level} reads {bytes:?}, wanted {want}"); + } + }; + // No room: nothing is given, the held levels are said to wait, + // nothing is shown, every level reads zeros. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false); + rig.check("an upload without room"); + assert!(!changed && waiting, "without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), 0, "without room no tile is given"); + assert_eq!(tiled.first_shown(), None); + read_as_given(rig, "without room"); + // Asked again with room: the same levels get theirs. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true); + rig.check("the upload again, with room"); + assert!(changed && !waiting, "with room: changed {changed}, waiting {waiting}"); + assert!(tiled.has_tiles(3) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "with room"); + // More levels held and no room again: the ones that have tiles + // are brought up to date, the new ones wait, the view stays. + let before = tiled.given_bytes(); + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false); + rig.check("more levels held, without room"); + assert!(!changed && waiting, "more levels without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), before); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "more levels without room"); + // The card's own write is not kept waiting, and brings only its + // own level: level 1 still waits although it is held. + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(&rig.queue, &rig.device, &texture, 1 << 0); + rig.check("the card's own write, without room"); + assert!(changed && tiled.has_tiles(0) && !tiled.has_tiles(1) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(0)); + assert_eq!(tiled.claim(1 << 0), 0, "a level with tiles is not claimed again"); + // With room everything held gets its tiles. + let (_, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true); + rig.check("the last upload, with room"); + assert!(!waiting && tiled.whole()); + read_as_given(rig, "everything given"); + } + + fn a_claim_given_up_is_made_again(rig: &mut Rig) { + rig.step = "step 7, a claim whose zeros never landed is given up"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (_texture, tiled) = rig.reserved(&desc); + let level = tiled.with_level(2); + assert_eq!(tiled.claim(level), level, "the level is new"); + assert_eq!(tiled.claim(level), 0, "claimed once"); + // The list that claimed it was reset without being submitted. + tiled.unclaim(level); + assert_eq!(tiled.claim(level), level, "claimed again after it was given up"); + // The small levels the card packs together are claimed together. + let small = tiled.with_level(u32::from(LEVELS) - 1); + assert!(!rig.card || small.count_ones() > 1, "on the card a 1024 texture has several levels in one tile"); + assert_eq!(tiled.claim(1 << (u32::from(LEVELS) - 1)), 1 << (u32::from(LEVELS) - 1)); + tiled.unclaim(small); + assert_eq!(tiled.claim(small), small); + } + + /// On the software adapter unless `VICTORY_TILES_TEST_CARD=1`. + #[test] + #[ignore = "on the card: run it by name with --ignored --nocapture"] + fn levels_on_demand_on_the_card() { + let Some(mut rig) = Rig::new() else { + eprintln!("no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped"); + return; + }; + rig.check("the device made"); + levels_arrive(&mut rig, DXGI_FORMAT_BC7_UNORM); + levels_arrive(&mut rig, DXGI_FORMAT_BC3_UNORM); + a_card_copy_lands_after_the_give(&mut rig); + a_reused_tile_reads_as_written(&mut rig); + a_level_on_several_ranges(&mut rig); + a_full_card_keeps_new_levels_waiting(&mut rig); + a_claim_given_up_is_made_again(&mut rig); + if the_view_starts_at_the_first_level_with_tiles(&mut rig).is_none() { + eprintln!("the view test's shader or objects could not be made; that part was skipped"); + } + rig.step = "the end"; + rig.check("every step done"); + eprintln!( + "all steps passed {}", + if rig.card { "ON THE CARD" } else { "on the software adapter; VICTORY_TILES_TEST_CARD=1 is the run on the card" } + ); + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + eprintln!( + "{} calls of UpdateTileMappings took {} microseconds in all ({} a call); the pool's heaps {} MB, {} given back", + s[6], + s[7], + s[7] / s[6].max(1), + s[3] >> 20, + s[8] + ); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 60089a7e..bc7d3be8 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -14,11 +14,14 @@ //! wholly uncommitted are skipped while they remain so; one query can //! confirm a whole region, including ordinary reservations between views. //! -//! shortcut: writes into physical pages through another view (xmem's -//! `write_physical`, DirectStorage's page destinations) are not seen at -//! the guarded addresses; they go to the texture pool, whose textures are -//! hashed, not guarded. A system call writing into a guarded block fails -//! (none is known to). +//! Writes into physical pages through another view are seen too: the +//! runtime tells us the views of the pages it wrote itself ([`writing`], +//! xmem's `write_physical` and DirectStorage's page destinations), and a +//! write by the title through any view of a guarded page faults like one +//! at the guarded address (the guard makes every view of the page +//! read-only, [`open`] gives them all back; not a page of more than +//! [`MANY_VIEWS`] views). A +//! system call writing into a guarded block fails (none is known to). use std::collections::{BTreeMap, BTreeSet}; use std::sync::Mutex; @@ -218,6 +221,12 @@ pub(crate) fn wrote(at: usize, len: usize) { } j.asked += 1; let now = j.asked; + // The asking that stands moves with it: `asked` and `writes` give it as + // "now", and a page noted written after "now" stays stale for every + // copy that takes it (copied at `now`, written at `now + 1`): copied + // again at every refresh, and a reason to settle flights + // (fxceless/victory-fork#410). + j.ahead_asked = now; for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { j.written.insert(page, now); } @@ -379,12 +388,17 @@ struct Guards { /// Blocks already copied as zeros. While they remain wholly uncommitted, /// the copy can skip hundreds of MB of failing kernel reads per world frame. absent: BTreeSet, + /// Blocks whose physical page was guarded together with its other views + /// (those views' blocks are in it too): a write to one opens them all. + /// A write range can be huge (`fread`), so only these are looked up. + aliased: BTreeSet, } static GUARDS: Mutex = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + aliased: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -508,8 +522,77 @@ fn is_view(start: usize, end: usize) -> bool { /// Makes blocks `[from, to)` read-only and notes them guarded and clean; /// block by block if they span views, leaving out any that fail, and -/// noting those not committed (unmapped) absent. +/// noting those not committed (unmapped) absent. The same physical pages +/// at every other view of them are made read-only too: a write through +/// one of those is this memory written, and only a fault can say so. +/// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before. fn protect(g: &mut Guards, from: usize, to: usize) { + protect_here(g, from, to); + if !view_guard() { + return; + } + for (base, bytes) in crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) { + let first = (base / BLOCK).max(from); + let last = (base.saturating_add(bytes).div_ceil(BLOCK)).min(to); + for block in first..last { + let shown = crate::inplace::pages_of(block * BLOCK); + // One view (nothing else to guard), or the page the title shows + // wherever it has nothing (thousands of views): each view of + // that one is guarded by itself. + if shown.len() < 2 || shown.len() > MANY_VIEWS { + continue; + } + #[cfg(feature = "diagnostics")] + ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for alias in shown { + let alias = alias / BLOCK; + g.aliased.insert(alias); + if alias != block { + protect_alias(g, alias); + } + } + } + } +} + +/// Views of one page past which its views are not guarded together. +pub(crate) const MANY_VIEWS: usize = 64; + +/// Whether all the views of a guarded page are guarded together +/// (`VICTORY_VIEW_GUARD`). +fn view_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_GUARD").is_none_or(|v| v != "0")) +} + +/// Diagnostics: blocks guarded together with their other views, blocks +/// opened because another view of theirs was written, and blocks opened +/// because a view of theirs was mapped; since the start. +#[cfg(feature = "diagnostics")] +pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Makes `block` read-only: another view of pages a copy has just taken +/// through its own view, so that a write through this one faults too. It is +/// not noted clean. The copies of title memory at this view have not taken +/// the pages: noted clean, the block would not be reported written at their +/// next check and they would keep the bytes from before the write (`guard` +/// reports a block that is read-only and not clean as written, then notes it +/// clean). A block that is clean stays so: had the pages been written since +/// its copies took them, `open` would have opened it. +fn protect_alias(g: &mut Guards, block: usize) { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + if g.protected.contains(&block) { + return; + } + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + if unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0 { + g.protected.insert(block); + } +} + +/// [`protect`] for one range, without the other views of its pages. +fn protect_here(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; @@ -557,8 +640,31 @@ fn uncommitted_end(block: usize) -> usize { } /// Gives write access back to the guarded blocks of `[start, end)` and -/// notes them written; true if any was guarded. +/// notes them written; true if any was guarded. The same physical pages at +/// every other view of them are opened too: the write that faulted (or is +/// ours, `crate::host::copy_mapped`) goes through one view, and every +/// guard over the pages must copy them again. fn open(g: &mut Guards, start: usize, end: usize) -> bool { + let any = open_here(g, start, end); + if start >= end || g.aliased.is_empty() { + return any; + } + let aliased: Vec = g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + for alias in crate::inplace::pages_of(block * BLOCK) { + if alias / BLOCK != block && open_here(g, alias, alias.saturating_add(BLOCK)) { + #[cfg(feature = "diagnostics")] + ALIASES[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + g.aliased.remove(&(alias / BLOCK)); + } + } + any +} + +/// [`open`] for one range, without the other views of its pages. +fn open_here(g: &mut Guards, start: usize, end: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; let blocks: Vec = g .protected @@ -586,6 +692,98 @@ pub fn writing(at: usize, len: usize) { crate::descriptor::host::remapped(at, len); } +/// What `VICTORY_PAGE_WRITES` asks to be done with a write the guards do +/// not see once its bytes are there ([`title_memory_written`]), as bits: +/// 1, the guarded blocks under it are opened and count as written (host +/// copies of buffers and textures read through tables take them again); +/// 2, the placed textures picked by index that lie under it are due again; +/// 4, both also for reads to plain addresses when they have finished. +/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1 +/// alone. `slots`: bit 2 alone. `all`: everything. +pub(crate) fn page_writes() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) { + Ok("1") => 3, + Ok("guards") => 1, + Ok("slots") => 2, + Ok("all") => 7, + _ => 0, + }) +} + +/// Since the start: writes into physical pages through the runtime's own +/// views that landed at addresses the title has mapped (one for each run +/// of addresses); their bytes; guarded blocks that lay under them (host +/// copies that would otherwise keep the bytes from before); reads to +/// plain addresses that finished. +pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The bytes of a write the guards do not see are there: title memory +/// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages +/// through a view of the runtime's own, and this is an address where the +/// title has those pages mapped (no title address faulted, nothing was +/// mapped or unmapped; the shortcut this file's header names). Otherwise a +/// read to a plain address has finished, of which [`writing`] was told +/// before it began. +/// +/// Upstream's c75fdba does the same for its trackers (its `Writing` marks +/// the pages once more when dropped; page destinations are reported at +/// each address showing them). Here it is counted always and acted on as +/// [`page_writes`] says. Called without the runtime's page-table lock; +/// takes the guards' lock, then, alone, the lock of the ranges kept for +/// the texture pass. +pub fn title_memory_written(at: usize, len: usize, pages: bool) { + use std::sync::atomic::Ordering::Relaxed; + if len == 0 { + return; + } + let mode = page_writes(); + let end = at.saturating_add(len); + if pages { + WRITTEN[0].fetch_add(1, Relaxed); + WRITTEN[1].fetch_add(len as u64, Relaxed); + } else { + WRITTEN[3].fetch_add(1, Relaxed); + if mode & 4 == 0 { + return; + } + } + { + let mut g = guards(); + let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64; + if pages { + WRITTEN[2].fetch_add(guarded, Relaxed); + } + if mode & 1 != 0 && guarded != 0 { + open(&mut g, at, end); + } + } + // A placed texture there changed with no descriptor written. + crate::descriptor::host::page_written(at, len); +} + +/// The runtime mapped a view of the physical bytes `[offset, offset + len)` +/// of `section` (`crate::inplace::title_memory_view`): the view is +/// writable, so the same bytes guarded at another view must be checked +/// again — and are, the pages noted written, which also has the next check +/// guard the new view (`protect`). +pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { + if !view_guard() { + return; + } + let ranges = crate::inplace::views_of_section(section, offset, len); + if ranges.is_empty() { + return; + } + let mut g = guards(); + for &(at, n) in &ranges { + if open_here(&mut g, at, at.saturating_add(n)) { + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } +} + /// Held shared by a read of title memory in place, and alone by the runtime /// while it changes what title memory shows. /// @@ -657,6 +855,10 @@ pub fn title_memory_remapped(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); } + let aliased: Vec = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + } } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -1046,6 +1248,154 @@ mod tests { title_memory_remapped(p, 3 * BLOCK); } + /// A pagefile section mapped twice: two views of the same physical + /// pages, the second left for the test; the section handle, the two + /// addresses. + fn two_views(bytes: usize) -> (usize, usize, usize) { + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, + }; + // SAFETY: a fresh pagefile section, mapped twice; the views keep + // the section alive and the handle is closed by the caller. + unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + bytes as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + assert_ne!(one, 0); + assert_ne!(two, 0); + crate::inplace::title_memory_view(one, bytes, section as usize, 0); + crate::inplace::title_memory_view(two, bytes, section as usize, 0); + (section as usize, one, two) + } + } + + /// The section of [`two_views`] is closed and its views unmapped; the + /// guard is told they are gone first. + fn drop_views(section: usize, views: &[usize], bytes: usize) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile}; + for &view in views { + title_memory_remapped(view, bytes); + // SAFETY: a view of the section mapped by `two_views`. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }) + }; + } + // SAFETY: the section's last reference. + unsafe { CloseHandle(section as *mut std::ffi::c_void) }; + } + + /// The title wrote the pages of a guarded texture through another view + /// of them: the fault at that view is the guard's to see, and the + /// guarded view's next check reports the pages written. + #[test] + fn a_write_through_another_view_is_reported_at_the_guarded_one() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + // The first check takes it in (and every view of its pages). + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + // Writing through the other view faults into the handler, which + // opens that view and the guarded one: the next check sees it. + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((other + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A view of guarded pages is mapped anew: it is writable, so the + /// guarded view checks its pages again (and guards the new view). + #[test] + fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + title_memory_remapped(other, SIZE); + crate::inplace::title_memory_view(other, SIZE, section, 0); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A write of the runtime's own, told at one view of the pages + /// (`writing`): the other views' next checks report the pages written. + #[test] + fn a_write_told_at_one_view_is_reported_at_the_others() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + writing(other + BLOCK, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + // Half a page and the next: both blocks, not just the first's. + writing(other + BLOCK / 2, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + drop_views(section, &[guarded, other], SIZE); + } + + /// Both views of the pages are checked, each for a copy of its own + /// (the title shows one physical page at several addresses, and each + /// address has its host copy): a write through either is reported at + /// both, whichever is checked first. Guarding the pages for the first + /// view's check must not note the second view clean, or its copy would + /// keep the bytes from before the write. + #[test] + fn a_write_is_reported_at_every_checked_view() { + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet"); + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((two + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second"); + // SAFETY: the first view, as above. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)])); + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new())); + assert_eq!(guard(two, two + SIZE), Some(Vec::new())); + drop_views(section, &[one, two], SIZE); + } + + /// A page shown in more than `MANY_VIEWS` views is guarded at each by + /// itself: the others stay writable, and nothing looks through them all. + #[test] + fn a_page_of_many_views_is_guarded_one_view_at_a_time() { + let (section, one, two) = two_views(BLOCK); + let filler = one + (1 << 45); + for n in 0..MANY_VIEWS { + crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0); + } + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + assert!(writable(two), "another view of it is left alone"); + // SAFETY: the guarded view, opened by the handler. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + title_memory_remapped(filler, MANY_VIEWS * BLOCK); + drop_views(section, &[one, two], BLOCK); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 23bbccf5..abda4a65 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -36,6 +36,19 @@ fn host_gpu_failed(what: &str) -> ! { unreachable!("the process has ended") } +/// The offline warm-up: see `victory_gpu::shader_cache::warm`. +pub fn warm_shader(container: &[u8]) -> Result { + #[cfg(windows)] + { + victory_gpu::shader_cache::warm(container) + } + #[cfg(not(windows))] + { + let _ = container; + Err("no shader cache on this host".into()) + } +} + /// 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`). diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 4c17b8e9..8208880e 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -863,8 +863,25 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return Err(fail(E_INVALIDARG, "source larger than destination")); } let size = request.source_size as usize; - return into_destination(request, size, |out| read_into(request, out).map(|()| size)) - .map_err(|hr| fail(hr, "copying")); + // A file read into a title address is the kernel's write, and the + // kernel does not fault into the GPU side's guard: a block guarded + // again between `kernel_will_write` and the read (the guard over all + // the views of a page protects other views from other threads) made + // the read fail with ERROR_INVALID_USER_BUFFER, and the title stops + // at the failed request (runs amd-C and amd-C2, seconds after the + // world's first frame). It is read beside and copied in: our copy + // faults into the guard like the title's own writes. + let bounce = options & (PAGE_DESTINATION | MEMORY_SOURCE) == 0; + return into_destination(request, size, |out| { + if !bounce { + return read_into(request, out).map(|()| size); + } + let mut data = vec![0; size]; + read_into(request, &mut data)?; + out.copy_from_slice(&data); + Ok(size) + }) + .map_err(|hr| fail(hr, "copying")); } let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; @@ -1034,13 +1051,22 @@ fn into_destination( fill: impl FnOnce(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { - // Raw reads land through the kernel, which does not fault into the - // GPU side's guard on title buffers; open them first. + // Opens the guarded blocks and tells the GPU side a placed texture + // there changes. `fill` writes from user mode (a file read is read + // beside first, see `execute`), so a block guarded again meanwhile + // faults into the guard instead of failing the write. victory_gpu::kernel_will_write(request.destination as usize, len); // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; - return fill(out).map(drop); + let filled = fill(out).map(drop); + // Said again now that the bytes are there (upstream's c75fdba holds + // the blocks open over the read and marks them once more at its + // end): a copy or a texture pass that took the memory while the + // read was under way took what was there before. Counted; acted on + // only with `VICTORY_PAGE_WRITES=all`. + victory_gpu::title_memory_written(request.destination as usize, len, false); + return filled; } let offset = (request.page_offset & 0xffff) as usize; // SAFETY: the title passes a page number per 64 KiB of destination, @@ -1054,20 +1080,33 @@ fn into_destination( // Consecutive pages of one allocation (the usual case): written in // place through one view. if let Some(mut window) = super::xmem::page_window(pages, offset, len) { - return fill(window.bytes()).map(drop); + let filled = fill(window.bytes()).map(drop); + drop(window); + // The title maps pages where the card reads them and has them + // filled afterwards: the GPU side's copies of those addresses + // learn of the bytes only from this (upstream c75fdba, fork PR + // #571). After a decode that failed part way too: what it wrote + // is there. + super::xmem::pages_written(pages, offset, len); + return filled; } let mut data = vec![0; len]; let n = fill(&mut data)?; - // A page the title has just made, or a view the host refuses for a moment (commit - // or address space short while a load maps many at once), can come right a little - // later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12, - // about 1.5 s in all). + // A page the title has just made, or a view the host refuses for a + // moment, comes right a little later: the write is tried again before + // the request fails (`VICTORY_DSTORAGE_RETRIES`, 12 tries, about 0.9 s + // in all; 0: not tried again, as before). Runs 175-178 lost 12 to 446 + // reads a launch here, all in one second of the loading; the one build + // that tried again (run 165) lost none of 13. static RETRIES: std::sync::OnceLock = std::sync::OnceLock::new(); let retries = *RETRIES.get_or_init(|| { - std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12) + std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12) }); + // Since the start: writes that succeeded on a later try, and writes + // given up. + static RETRIED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; let mut written = super::xmem::write_physical(pages, offset, &data[..n]); - let mut tries = 0; + let mut tries = 0u32; while !written && tries < retries { std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); tries += 1; @@ -1075,12 +1114,28 @@ fn into_destination( } if written { if tries > 0 { - tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry"); + let on_a_retry = RETRIED[0].fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + offset, + len, + tries, + on_a_retry, + given_up = RETRIED[1].load(Ordering::Relaxed), + "dstorage: a destination's physical pages written after a retry" + ); } + // As above, after the write that succeeded. + super::xmem::pages_written(pages, offset, n); Ok(()) } else { - let known = super::xmem::pages_known(pages, offset, len); - tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up"); + let given_up = RETRIED[1].fetch_add(1, Ordering::Relaxed) + 1; + tracing::warn!( + known = super::xmem::pages_known(pages, offset, len), + tries, + given_up, + on_a_retry = RETRIED[0].load(Ordering::Relaxed), + "dstorage: retries used up (VICTORY_DSTORAGE_RETRIES)" + ); // Said aloud: the title never reads a request's result // (it only polls for completion), so a destination left unwritten // is a model or texture that silently holds whatever its pages diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index 902c4a9f..d13c3bc2 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -519,7 +519,10 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination -// is opened first. +// is opened first. A block guarded again before the kernel writes it (the +// guard over all the views of a page protects other views from other +// threads) fails that `ReadFile`, and the title's retry opens it again; +// `fread` has no such retry and reads beside instead (see there). pub extern "system" fn ReadFile( file: *mut c_void, @@ -534,12 +537,38 @@ pub extern "system" fn ReadFile( ) } -/// The host CRT reads large requests straight into the caller's buffer. +/// The host CRT reads large requests straight into the caller's buffer +/// through the kernel, whose write fails on a guarded block instead of +/// faulting into the guard. So the bytes are read beside, a chunk at a time +/// (a caller may ask for far more than the file holds), and copied in from +/// user mode, where a guarded block faults into the guard like the title's +/// own writes. Returns the items read, as the CRT does; the bytes of a +/// partial last item are copied too, as the CRT leaves them. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { - victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); - host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( - buffer, size, count, stream, - ) + let read = host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize); + let total = size.saturating_mul(count); + if buffer.is_null() || total == 0 { + // The CRT's own checks and answer (EINVAL, or nothing to read). + return read(buffer, size, count, stream); + } + const CHUNK: usize = 1 << 20; + let mut beside = vec![0u8; total.min(CHUNK)]; + let mut done = 0; + while done < total { + let want = (total - done).min(CHUNK); + let n = read(beside.as_mut_ptr(), 1, want, stream); + if n > 0 { + victory_gpu::kernel_will_write(buffer as usize + done, n); + // SAFETY: the caller's buffer holds `size * count` bytes, and + // `done + n` is at most that. + unsafe { std::ptr::copy_nonoverlapping(beside.as_ptr(), buffer.add(done), n) }; + done += n; + } + if n < want { + break; + } + } + done / size } pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { @@ -751,6 +780,40 @@ mod tests { assert_eq!((&out, n), (b"0123456789", 10)); } + #[test] + fn fread_reads_beside_in_chunks() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + // Over two chunks, and not a whole number of 3-byte items. + let bytes: Vec = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect(); + std::fs::write(&path, &bytes).unwrap(); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + let open = || { + let f = _wfopen(w(&path.to_string_lossy()).as_ptr(), w("rb").as_ptr()); + assert!(!f.is_null()); + f + }; + + // Asked for far more than the file holds: the whole file, in items. + let f = open(); + let mut out = vec![0xaau8; bytes.len() + 64]; + let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f); + assert_eq!(items, bytes.len() / 3); + assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too"); + assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read"); + fclose(f); + + // Exact reads continue where the last one stopped. + let f = open(); + let mut a = vec![0u8; 1000]; + let mut b = vec![0u8; (1 << 20) + 5]; + assert_eq!(fread(a.as_mut_ptr(), 1000, 1, f), 1); + assert_eq!(fread(b.as_mut_ptr(), 1, b.len(), f), b.len()); + assert_eq!(a, bytes[..1000]); + assert_eq!(b, bytes[1000..1000 + b.len()]); + fclose(f); + } + fn text(v: &[u16]) -> String { String::from_utf16_lossy(&v[..v.len() - 1]) } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 6cb89fa8..838826e1 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -58,7 +58,7 @@ const KEYBOARD: usize = PADS + 1; const DEVICES: usize = PADS + 2; /// Readings kept per device for next/previous lookups. -const HISTORY: usize = 32; +const HISTORY: usize = 256; const POLL: Duration = Duration::from_millis(8); /// The keyboard's stand-in gamepad (virtual key, button); README lists it. diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5f717bfe..e8984593 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -364,12 +364,25 @@ struct Slice { index: usize, } +impl Slice { + /// The key in `Physical::shown` of the page `k` pages after this one. + fn key(&self, k: usize) -> (usize, usize) { + (Arc::as_ptr(&self.section) as usize, self.index + k) + } +} + #[derive(Default)] struct Physical { next_page: usize, pages: HashMap, /// Mapped views by address: their length and what they show. views: BTreeMap, + /// Where each page shows: by its section and its index there, the + /// address of that page in every view that shows it now ([`shown_at`]; + /// as upstream's c75fdba keeps it). The title maps pages where the + /// card reads them and has them filled afterwards by DirectStorage, + /// which writes through views of our own. + shown: HashMap<(usize, usize), Vec>, } static PHYSICAL: LazyLock> = LazyLock::new(|| { @@ -596,6 +609,58 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< }) } +/// The title addresses that show bytes `[offset, offset + len)` of `pages` +/// now, byte for byte, as runs (address, bytes) in address order: a write +/// to the pages through a view of our own ([`page_window`], +/// [`write_physical`]) lands there too, and nothing that watches those +/// addresses sees it (the GPU side's guards fault only on a write at the +/// guarded address itself). Empty if no view shows them. Byte for byte, +/// not by whole pages: the title packs several small textures into one +/// page and fills each with a request of its own. +pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { + let Some(end) = offset.checked_add(len) else { + return Vec::new(); + }; + let first = offset / PAGE; + let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else { + return Vec::new(); + }; + let mut pieces: Vec<(usize, usize)> = Vec::new(); + { + let physical = physical(); + for (i, page) in touched.iter().enumerate() { + let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else { + continue; + }; + // The bytes of this page that the write covers. + let lo = if i == 0 { offset % PAGE } else { 0 }; + let hi = (end - (first + i) * PAGE).min(PAGE); + pieces.extend(addresses.iter().map(|&at| (at + lo, hi - lo))); + } + } + pieces.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (at, bytes) in pieces { + match runs.last_mut() { + Some((start, n)) if *start + *n == at => *n += bytes, + _ => runs.push((at, bytes)), + } + } + runs +} + +/// Bytes `[offset, offset + len)` of `pages` have been written through a +/// view of our own: the GPU side is told at every title address that +/// shows them (`victory_gpu::title_memory_written`; what it does with it +/// is `VICTORY_PAGE_WRITES`' to say, and it counts either way). Call when +/// the bytes are there, and without the page table's lock ([`shown_at`] +/// takes and leaves it). +pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { + for (at, bytes) in shown_at(pages, offset, len) { + victory_gpu::title_memory_written(at, bytes, true); + } +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -746,6 +811,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { victory_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + for k in 0..len.div_ceil(PAGE) { + physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE); + } physical.views.insert(base, (len, slice)); true } @@ -824,6 +892,15 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { let Some((size, slice)) = physical.views.remove(&at) else { continue; }; + for k in 0..size.div_ceil(PAGE) { + let key = slice.key(k); + if let Some(addresses) = physical.shown.get_mut(&key) { + addresses.retain(|&a| a != at + k * PAGE); + if addresses.is_empty() { + physical.shown.remove(&key); + } + } + } victory_gpu::title_memory_remapped(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { @@ -1306,6 +1383,54 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + /// Pages say where the title has them mapped, byte for byte (after + /// fork PR #571's test; its runs are whole pages). + #[test] + fn pages_say_where_they_are_mapped() { + let pages = allocate(3); + let reserve = |n: usize| { + let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!at.is_null()); + at + }; + // `b` keeps a page unmapped at either end, so that no run at `b` + // ever touches one at `a`, wherever the host puts the two. + let (a, b) = (reserve(3), reserve(4)); + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere"); + // All three at `a`; the last two at `b`, from its second page on. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + let second = b.wrapping_byte_add(PAGE); + assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second); + let (a, second) = (a as usize, second as usize); + let sorted = |mut runs: Vec<(usize, usize)>| { + runs.sort_unstable(); + runs + }; + assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]); + // A request for part of a page names those bytes alone. + assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]); + // Across two pages, shown at two addresses each: one run at each. + assert_eq!( + shown_at(&pages, PAGE + 1, PAGE), + sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)]) + ); + // A page unmapped in the middle of a view: the rest still shows. + let middle = (a + PAGE) as *mut c_void; + assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle); + assert_eq!( + shown_at(&pages, 0, 3 * PAGE), + sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)]) + ); + // Too few pages for the bytes: nothing (the write fails too). + assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty()); + for (at, n) in [(a, 3), (second, 2)] { + let at = at as *mut c_void; + assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at); + } + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty()); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1)); diff --git a/crates/victory-shader/build.rs b/crates/victory-shader/build.rs new file mode 100644 index 00000000..b1021250 --- /dev/null +++ b/crates/victory-shader/build.rs @@ -0,0 +1,65 @@ +//! Fingerprint of the translator's own source, for the shader cache key +//! (`victory-gpu`'s `shader_cache`): a rebuilt executable whose translator did +//! not change keeps its cached translations. Also lists every `VICTORY_*` +//! switch the translator reads, whose values join the key at run time. +//! Reads only this crate's `src` folder; writes nothing but cargo directives. + +use std::path::{Path, PathBuf}; + +fn files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } +} + +/// FNV-1a, 64 bits, two lanes with different offsets: a mismatch only costs +/// a cache miss, so this need not be cryptographic. +fn fnv(state: &mut [u64; 2], bytes: &[u8]) { + for &b in bytes { + for (i, s) in state.iter_mut().enumerate() { + *s ^= u64::from(b) ^ (i as u64 * 0x9e); + *s = s.wrapping_mul(0x0000_0100_0000_01b3); + } + } +} + +fn main() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + println!("cargo:rerun-if-changed=src"); + println!("cargo:rerun-if-changed=Cargo.toml"); + let mut list = Vec::new(); + files(&src, &mut list); + list.sort(); + let mut state = [0xcbf2_9ce4_8422_2325u64, 0x8422_2325_cbf2_9ce4u64]; + let mut switches = std::collections::BTreeSet::new(); + for p in &list { + let rel = p.strip_prefix(&src).unwrap_or(p).to_string_lossy().replace('\\', "/"); + let text = std::fs::read(p).unwrap_or_default(); + fnv(&mut state, rel.as_bytes()); + fnv(&mut state, &(text.len() as u64).to_le_bytes()); + fnv(&mut state, &text); + let s = String::from_utf8_lossy(&text); + let mut rest = &s[..]; + while let Some(at) = rest.find("\"VICTORY_") { + let tail = &rest[at + 1..]; + let end = tail + .find(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')) + .unwrap_or(tail.len()); + if tail[end..].starts_with('"') { + switches.insert(tail[..end].to_string()); + } + rest = &tail[end..]; + } + } + println!("cargo:rustc-env=VICTORY_SHADER_SOURCE_HASH={:016x}{:016x}", state[0], state[1]); + let joined: Vec<_> = switches.into_iter().collect(); + println!("cargo:rustc-env=VICTORY_SHADER_SWITCHES={}", joined.join(",")); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5f2b298d..3f6f9ff0 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -188,6 +188,33 @@ pub fn shader_opt() -> u32 { *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) } +/// Everything a translation depends on besides the container: the +/// translator's own source (hashed at build time), the value of every +/// `VICTORY_*` switch it reads, the host facts the device hands it (widest +/// wave, view heap limit) and the settings above. The shader cache keys on +/// this instead of on the whole executable, so a rebuild that leaves the +/// translator alone keeps its translations. Call it after the device is made. +pub fn translation_fingerprint() -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(env!("VICTORY_SHADER_SOURCE_HASH").as_bytes()); + out.push(u8::from(cfg!(feature = "diagnostics"))); + out.push(u8::from(cfg!(debug_assertions))); + for name in env!("VICTORY_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) { + out.extend_from_slice(name.as_bytes()); + out.push(b'='); + if let Some(value) = std::env::var_os(name) { + out.extend_from_slice(value.as_encoded_bytes()); + } + out.push(0); + } + out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); + out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); + out.extend_from_slice(&loop_limit().to_le_bytes()); + out.push(group_sync()); + out.extend_from_slice(&shader_opt().to_le_bytes()); + out +} + /// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or /// unreadable. Pure, for testing. fn parse_shader_opt(value: Option<&str>) -> u32 { From a26859fc5f512e0db0d7522d3da821c038378ab7 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:46:49 -0500 Subject: [PATCH 02/16] The first room renders right: byte-copied descriptor records are mirrored, views off their copy's elements get their own bytes, card room for the first world frame, levels on demand run on the card - Descriptor records the title copies into its heap as bytes are mirrored before each submission (pull request #305 by Flyander, after upstream VIctory 86a5ed6), with a per-slot fingerprint so only records that changed are mirrored, the page read through the kernel, a switch (VICTORY_HEAP_SYNC=0) and a counter: about 40,000 records a frame on the test machine. - A buffer view off its copy's elements gets a copy of its own bytes (after upstream 86a5ed6; VICTORY_VIEW_OWN_COPY=0: refused as before). - Room on the card for the world's first-frame bursts: buffer copies (VICTORY_CARD_ROOM_FOR_BUFFERS, now on) and render targets (VICTORY_CARD_ROOM_FOR_TARGETS_MB, 3,072); a copy turned down gives its room up and is logged; the texture pass asks again every 32 MiB. 98 buffer copies made (945 MB) where earlier runs made 1; 25 MB compared on the processor a frame where it was 550 to 710. - Levels on demand: the fixes of pull request #747 by AscilCH. First run on a card (RTX 4070, VICTORY_LEVELS_ON_DEMAND=1): no device loss, 3.1 GB not allocated for levels the title does not hold. Still off by default. - The guarded blocks under storage writes into physical pages are opened by default (VICTORY_PAGE_WRITES=0: counted only). - Shaders: a program is translated with first-half interpolation pairs only if it was refused for one (with it on for every program 8,551 working pixel programs came out changed); parked lane-mask pairs, f64 conversions and sums, lane permutations: 14 more programs translate. - Counted, not fixed: an indirect compute pass asks for about 77,500 groups in x and is cut to 65,535. One five-minute game run of these changes on the test machine: no device loss, no failed request. This merged tree was built; its test suites were not run. Co-Authored-By: Claude Fable 5.2 --- README.md | 27 ++ crates/victory-gpu/src/descriptor.rs | 201 +++++++++++++++ crates/victory-gpu/src/descriptor/host.rs | 211 +++++++++++++++- crates/victory-gpu/src/draw.rs | 12 +- crates/victory-gpu/src/host.rs | 24 +- crates/victory-gpu/src/indirect.rs | 15 +- crates/victory-gpu/src/resource.rs | 40 ++- crates/victory-gpu/src/shadow.rs | 120 ++++++++- crates/victory-gpu/src/tiles.rs | 232 +++++++++++++++--- crates/victory-gpu/src/watch.rs | 71 +++++- crates/victory-shader/src/emit/lower.rs | 195 ++++++++++++++- crates/victory-shader/src/emit/mod.rs | 16 ++ .../victory-shader/src/emit/wave64_tests.rs | 82 ++++++- 13 files changed, 1188 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 8c99e406..f9830ff6 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,33 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, ### Newest (2026-11-25, later the same day) +**Update, the same night: the first room now renders right on the test +machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5 +frames a second): the picture work has caught up, the frame rate has not. +What did it, on top of the list below: +- Descriptor records the title copies into its heap as plain bytes are + mirrored before every submission (pull request #305 by Flyander, after + upstream VIctory 86a5ed6). Measured here: about 40,000 records a frame + that no call had announced; their host slots were empty or stale. +- A buffer view that does not start on an element of its buffer's host + copy gets a copy of its own bytes instead of being refused (after + upstream 86a5ed6): 3 to 6 such views a frame. +- Room on the card is kept for the render targets and buffer copies a + world makes in its first frame: 98 buffer copies are made (945 MB) where + the runs before made 1, and the processor no longer compares 550 to + 710 MB a frame looking for shader writes (25 MB now). +- Levels on demand ran on the card for the first time + (`VICTORY_LEVELS_ON_DEMAND=1`, still off by default; with the fixes of + pull request #747 by AscilCH): 3.1 GB of the card not allocated for + texture levels the title does not hold, no device loss. +- Guarded blocks under storage writes are opened by default; 14 more + shader programs translate; a program is translated with first-half + interpolation pairs only if it was refused for one (with that on for + every program, 8,551 working pixel programs came out changed). +- Known and counted, not fixed yet: an indirect compute pass asks for + about 77,500 thread groups in x where one dispatch runs 65,535 (the + rest is cut off). + Memory sync between the title's memory and the copies on the card: - **A write through one view of a physical page is seen by the copies taken through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 9305bf56..6aad6da0 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -59,6 +59,10 @@ pub(crate) struct Heap { host: std::sync::OnceLock>, #[cfg(windows)] pending: std::sync::Mutex>, + /// Changed pages of a placed shader-visible heap. Some titles copy + /// descriptor records into it as bytes, without a descriptor API call. + #[cfg(windows)] + written: Option, } pub(crate) fn heap<'a>(this: This) -> &'a Heap { @@ -155,6 +159,119 @@ fn mirror(handle: u64) { } } +/// Mirrors records copied directly into placed shader-visible heaps. Calls +/// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave +/// only write-watch pages to reveal which slots changed. +/// +/// Upstream VIctory 86a5ed6 does the same and counts 1,300 to 14,400 such +/// slots a frame in the world of the title this fork works on, against a +/// few hundred views made by calls; without it those host slots stayed +/// null, or went on showing what they showed before. +/// `VICTORY_HEAP_SYNC=0`: not done, as before. [`SYNCED`] counts. +#[cfg(windows)] +pub(crate) fn sync_heaps() { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) { + return; + } + let started = std::time::Instant::now(); + let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); + let mut page_bytes: Vec = Vec::new(); + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(start, end, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(written), Some(step)) = + (heap.host.get(), &heap.written, increment(heap.desc.kind)) + else { + continue; + }; + let step = u64::from(step); + // Capped host heaps have no counterparts for the title slots reserved + // for per-draw tables; raw writes there must not be mirrored. + let mirrored_count = heap.desc.count.min(host.count()); + for (range_from, range_end) in written.take(start as usize, end as usize) { + let mut page = range_from & !(crate::watch::PAGE - 1); + while page < range_end { + let from = page.max(range_from); + let to = (page + crate::watch::PAGE).min(range_end); + // The page's records are read through the kernel, into a + // copy: a page the title unmaps meanwhile fails the read + // where 2,048 reads in place would fault. + page_bytes.resize(to - from, 0); + if crate::host::read_into(from as *const u8, &mut page_bytes) { + pages += 1; + let slots = changed_slots(from, to, start as usize, step, mirrored_count); + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left + // to the range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page_bytes.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // Only a record that is not the one last seen there + // (`HostHeap::mirror_copied`). + if host.mirror_copied(index as u32, handle, record) { + mirrored += 1; + } + } + } + page += crate::watch::PAGE; + } + } + } + drop(heaps); + for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) { + count.fetch_add(n, Relaxed); + } +} + +/// Since the last frame line, of [`sync_heaps`]: changed pages of placed +/// shader-visible heaps looked at, slots on them, slots whose record was +/// not the one last seen (mirrored), and the microseconds it took. +#[cfg(windows)] +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// With the frame line: what [`sync_heaps`] did per frame over `frames`. +/// Nothing while no heap page changed. +#[cfg(windows)] +pub(crate) fn sync_line(frames: f64) { + let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + if pages == 0 { + return; + } + tracing::info!( + "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ + {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.2} ms", + pages as f64 / frames, + looked as f64 / frames, + mirrored as f64 / frames, + micros as f64 / 1000.0 / frames + ); +} + +/// Title descriptor slots in a changed byte range that have host counterparts. +/// `range_end` is exclusive. +#[cfg(windows)] +fn changed_slots( + range_from: usize, + range_end: usize, + heap_start: usize, + step: u64, + mirrored_count: u32, +) -> std::ops::Range { + let from = (range_from - heap_start) as u64; + let to = (range_end - heap_start) as u64; + let first = from / step; + let last = to.div_ceil(step).min(u64::from(mirrored_count)); + first.min(last)..last +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] @@ -970,6 +1087,10 @@ pub(crate) extern "system" fn create_heap( host: std::sync::OnceLock::new(), #[cfg(windows)] pending: Default::default(), + #[cfg(windows)] + written: (placed && visible) + .then(|| crate::watch::track(start as usize, size as usize, true)) + .flatten(), }); #[cfg(windows)] if visible { @@ -1027,6 +1148,34 @@ mod tests { create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) } + #[cfg(windows)] + #[test] + fn raw_heap_sync_stops_before_dynamic_host_slots() { + let start = 0x1000usize; + let step = 32; + let capped = 5; + assert_eq!( + changed_slots( + start + 3 * step + 4, + start + 4 * step + 8, + start, + step as u64, + capped + ), + 3..5 + ); + assert_eq!( + changed_slots( + start + 6 * step, + start + 9 * step, + start, + step as u64, + capped + ), + 5..5 + ); + } + #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); @@ -1053,6 +1202,58 @@ mod tests { assert_eq!(create(bad, none, &mut h), E_INVALIDARG); } + /// A descriptor copied into a placed heap as bytes is mirrored before + /// the next submission, even though no descriptor method saw the copy. + #[cfg(windows)] + #[test] + fn records_copied_as_bytes_are_made_at_the_next_sync() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let memory = unsafe { + VirtualAlloc( + std::ptr::null(), + crate::watch::PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + }; + assert!(!memory.is_null()); + let desc = HeapDesc { + kind: SAMPLERS, + count: 64, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let placement = Placement { + address: memory as u64, + size: 64 * 16, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, placement, &mut h), S_OK); + if let Some(host) = heap(h).host() { + let mut elsewhere = [0u64; 2]; + let source = elsewhere.as_mut_ptr() as u64; + let sampler = [21, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0]; + create_sampler(std::ptr::null(), &sampler, source); + // SAFETY: the heap slot and source both hold 16 descriptor bytes. + unsafe { + std::ptr::copy_nonoverlapping( + source as *const u8, + memory.cast::().add(5 * 16), + 16, + ) + }; + assert!(!host.made(5)); + sync_heaps(); + assert!(host.made(5)); + } + slot:: u32>(h, 0x10)(h); + // SAFETY: this allocation belongs to the test. + unsafe { VirtualFree(memory, 0, MEM_RELEASE) }; + } + #[test] fn views_survive_copies() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 49e4ca1d..861106a1 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -26,6 +26,10 @@ pub(crate) struct HostHeap { sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex>, + /// A fingerprint of the record each slot held when the pass over + /// records copied in as bytes last looked at it + /// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use. + copied: Mutex>, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource @@ -947,6 +951,7 @@ impl HostHeap { dynamic: extra, sampler, made: Mutex::new(vec![0; count as usize]), + copied: Mutex::new(Vec::new()), kept: Mutex::new(vec![None; (count + extra) as usize]), next: Mutex::new((0, vec![false; DYNAMIC as usize])), free: std::sync::atomic::AtomicU32::new(DYNAMIC), @@ -1789,6 +1794,45 @@ impl HostHeap { } } + /// For a slot on a page of the title's heap that changed with no call + /// (`super::sync_heaps`: the title copies records into its heap as + /// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at + /// `handle` are not the ones this last saw there. True if it did. + /// + /// The page says only that something on it was written, and `mirror` + /// by itself would take every buffer or placed-texture record on it for + /// newly written each time (it leaves such a slot unmade until a draw + /// or a pass uses it): the texture queue's entry for the slot would + /// start again, and the buffer pass would look at 2,048 slots for one + /// that changed. + /// `record`: the record's bytes as the caller read them (through the + /// kernel, which fails on a page the title unmapped meanwhile where a + /// read in place would fault: the title unmaps heap pages too). + pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool { + if index >= self.count { + return false; + } + let n = record.len(); + // Never 0, which is "never looked at". + let print = u64::from_le_bytes(blake3::hash(record).as_bytes()[..8].try_into().unwrap_or([1; 8])) | 1; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + let Some(last) = copied.get_mut(index as usize) else { + return false; + }; + // A slot never looked at that holds nothing: as it was. + if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) { + return false; + } + *last = print; + } + self.mirror(index, handle, false); + true + } + /// Makes host slot `index` from the record the title has at `handle` /// if it changed since, and returns the view recorded there. Buffer /// views are made only for draws (`for_draw`), which also copy their @@ -1874,6 +1918,16 @@ impl HostHeap { Some(view) } + /// Whether slot `index` is backed by a made host descriptor (tests). + #[cfg(test)] + pub(crate) fn made(&self, index: u32) -> bool { + self.made + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(|&key| key != 0) + } + /// Whether host slot `index` shows `buffer`; `None` if it shows no /// resource (diagnostics: a buffer view's slot must show the host copy /// that is brought up to date for it). @@ -2041,6 +2095,18 @@ pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc Option<(u64, u64)> { /// The host resource a slot made by [`make`] views, if any. type Kept = Option; +/// Whether a buffer view off its buffer's elements gets a copy of its own +/// bytes (`VICTORY_VIEW_OWN_COPY=0`: it is refused and reads zeros, as +/// before). +fn own_copy_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_OWN_COPY").is_none_or(|v| v != "0")) +} + +/// The title memory (start, bytes) of a buffer view that cannot be made on +/// the host copy of its buffer: `count` elements of `element` bytes from +/// element `first` of the buffer at `base`, which lies `offset` bytes into +/// that copy, where `offset` is not a whole number of elements and the view +/// cannot be a raw view of the same bytes either ([`raw_window`]: +/// `unknown`, the view has no format, and `stride` is its structure's). +/// The host counts a view's first element from its buffer's start, so such +/// a view has no host view there; it is made on a copy of its own bytes +/// (`crate::shadow::exact`), where it starts at element 0. `None`: the +/// view is made on its buffer's copy, as every other. +fn own_bytes(offset: u64, base: u64, first: u64, count: u32, element: u64, stride: u32, unknown: bool) -> Option<(u64, u64)> { + own_bytes_if(own_copy_on(), offset, base, first, count, element, stride, unknown) +} + +#[allow(clippy::too_many_arguments)] +fn own_bytes_if( + on: bool, + offset: u64, + base: u64, + first: u64, + count: u32, + element: u64, + stride: u32, + unknown: bool, +) -> Option<(u64, u64)> { + if !on || element == 0 || count == 0 || offset.is_multiple_of(element) { + return None; + } + if unknown && raw_window(offset, first, count, stride).is_some() { + return None; + } + let start = base.checked_add(first.checked_mul(element)?)?; + Some((start, u64::from(count) * element)) +} + +/// Of a buffer view: its first element, its elements, the bytes of one (a +/// raw view's: 4), its structure's stride, and whether it has no format. +/// As [`buffer_srv`] and [`buffer_uav`] read them from the same words. +fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => (d[..10].try_into().ok()?, *unordered), + _ => return None, + }; + if unordered { + let d = uav_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(d.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + Some((b.FirstElement, b.NumElements, element, b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } else { + let d = srv_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + Some((b.FirstElement, b.NumElements, element_size(&d), b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } +} + /// A structured buffer view (`first`, `count` elements of `stride` bytes, /// `offset` bytes into its host copy) as a raw view of the same bytes: /// its first dword and its dwords. Translated shaders read untyped buffers @@ -2140,6 +2280,22 @@ fn buffer_srv( ) -> Option { let shadow = crate::shadow::find(address, len)?; let offset = shadow.offset(address); + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, offset) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(offset, address, b.FirstElement, b.NumElements, element_size(&desc), b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, 0) + } + None => (shadow, offset), + } + }; // A structured view as a raw view of the same bytes (see `raw_window`). // SAFETY: a buffer view's union member. let structured = unsafe { desc.Anonymous.Buffer }; @@ -2211,6 +2367,29 @@ fn buffer_uav( at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option { let shadow = crate::shadow::find(address, len)?; + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, own) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(shadow.offset(address), address, b.FirstElement, b.NumElements, element, b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, true) + } + None => (shadow, false), + } + }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { @@ -2226,7 +2405,7 @@ fn buffer_uav( } else { crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; - let offset = shadow.offset(address); + let offset = if own { 0 } else { shadow.offset(address) }; // A structured view as a raw view of the same bytes (see `raw_window`). let window = (desc.Format == DXGI_FORMAT_UNKNOWN) .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) @@ -3292,3 +3471,33 @@ mod tests { assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } } + +#[cfg(test)] +mod own_copy_tests { + use super::own_bytes_if; + + /// A buffer view gets a copy of its own bytes only when it has no host + /// view on its buffer's copy: off that copy's elements, and not a + /// structured view that can be a raw view of the same bytes. + #[test] + fn a_view_off_its_copys_elements_gets_its_own_bytes() { + let base = 0xd_9000_0000u64; + // On an element: the buffer's copy (the two cases of every run's + // log are the ones below). + assert_eq!(own_bytes_if(true, 24, base, 3, 10, 12, 0, false), None); + assert_eq!(own_bytes_if(true, 0, base, 0, 10, 12, 0, false), None); + // A typed view of 12-byte elements, 5,222,240 bytes into its copy + // (8 past an element): its own bytes, from its first element. + assert_eq!(own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), Some((base + 36, 120))); + // A structured view of 32-byte elements 8 bytes in: not on 16, so + // no raw view of the copy either. + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 32, 32, true), Some((base + 64, 128))); + // The same 16 bytes in: off its elements, but a raw view of the + // copy's bytes does (as before). + assert_eq!(own_bytes_if(true, 16, base, 2, 4, 32, 32, true), None); + // No elements, no size, or the switch off: as before. + assert_eq!(own_bytes_if(true, 8, base, 2, 0, 32, 32, true), None); + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 0, 0, false), None); + assert_eq!(own_bytes_if(false, 8, base, 2, 4, 32, 32, true), None); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ee74cc47..d9768e10 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1698,7 +1698,12 @@ impl State { // makes room again: so the slots are still looked at (the pass // returned here, and a slot whose texture had been streamed out // kept its host copy for as long as the card was full). - let room = crate::resource::room(); + let mut room = crate::resource::room(); + // Bytes uploaded by this pass since the card was last asked + // whether it has room: asked again every 32 MiB (a pass may upload + // 192 MB and more, and one asking a pass let the queue run some + // 400 MB past its line while the world loaded: run 193). + let mut since_asked = 0u64; if !room { HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); once!("textures picked by index: the card has no room for more; they wait"); @@ -1962,6 +1967,11 @@ impl State { }; crate::texture::unstage(resource); SPENT.fetch_add(bytes, Ordering::Relaxed); + since_asked += bytes; + if room && since_asked >= 32 << 20 { + since_asked = 0; + room = crate::resource::room(); + } HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); match memory { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6559af14..39f4f337 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1270,6 +1270,11 @@ pub(crate) fn dred_on() -> bool { /// budget buffers, a run late). static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Since the last frame line: the largest group count in x an indirect +/// compute record asked for, and the records that asked for more than the +/// 65,535 one dispatch runs (cut to that: the groups past it do not run). +static COMPUTE_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). @@ -3990,6 +3995,9 @@ impl Host { self.settle(&mut submitted, why); } } + // Descriptors the title copied into placed heaps directly, before + // command lists that index those slots are submitted. + crate::descriptor::sync_heaps(); let behind = late && flying(); // Before this submission counts as started: what the sweep lets go // of is named by no list, and nothing runs now (behind flights the @@ -5116,7 +5124,12 @@ impl HostList { let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); - for k in 0..3 { + // And of its indirect compute records: the largest x asked + // for, and how many asked for more than a dispatch runs. + let (widest, cut) = (words.add(3).read_volatile(), words.add(4).read_volatile()); + COMPUTE_GROUPS[0].fetch_max(u64::from(widest), Ordering::Relaxed); + COMPUTE_GROUPS[1].fetch_add(u64::from(cut), Ordering::Relaxed); + for k in 0..5 { words.add(k).write_volatile(0); } }))); @@ -5799,6 +5812,13 @@ impl Meter { tracing::info!( "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" ); + let compute_widest = COMPUTE_GROUPS[0].swap(0, Ordering::Relaxed); + let compute_cut = COMPUTE_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect compute dispatches: the largest group count in x asked for {compute_widest} (run: at most 65535), {compute_cut:.1} records per frame asked for more and were cut to that" + ); + crate::shadow::exact_line(frames); + crate::descriptor::sync_line(frames); late_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); @@ -5892,7 +5912,7 @@ impl Meter { let [kept, dropped, slots, uploaded] = [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); tracing::info!( - "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)", + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)", bytes >> 20, if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, if mode & 4 != 0 { "told as well" } else { "counted only" }, diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 321cc63a..4088599c 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -74,7 +74,20 @@ void main(uint3 id : SV_DispatchThreadID) { cost = count * instances; draw_counts = uint2(count, instances); } else if (kind == 2) { - uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + uint3 asked = src_args.Load3(src_at); + // Diagnostics, in the budget buffer's words after the mesh ones: + // the largest x a compute record asked for, and the records that + // asked for more groups in x than one dispatch runs (they are cut + // to 65,535 below, so the groups past it never run). Not the + // garbage of a slot nothing wrote. + if (asked.x <= (1u << 24) && asked.y <= 64u && asked.z <= 64u) { + uint noted; + budget.InterlockedMax(12, asked.x, noted); + if (asked.x > 65535u) { + budget.InterlockedAdd(16, 1u, noted); + } + } + uint3 g = min(asked, uint3(65535u, 65535u, 65535u)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index d701973c..244a76cc 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1433,12 +1433,48 @@ pub(crate) fn room() -> bool { } match crate::host::host().and_then(|h| h.video_memory()) { // What is kept for card copies of title buffers not made yet - // counts as used (`crate::shadow::card_room_kept`; 0 by default). - Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(), + // (`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 + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + } None => filled < WITHOUT_BUDGET, } } +/// The bytes of the card's memory the texture queue leaves free for +/// render targets and other host copies the host itself writes that are +/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as +/// before) less what such copies hold now. +/// +/// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255 +/// to 2,352 MB right after its first frame, 2,800 to 3,100 MB two minutes +/// on, none of them idle (run 198's census). They are made with no room +/// test, in the same frame as the card copies of title buffers (762 MB), +/// after the texture queue has filled the card to its line with textures +/// written while the world loaded (7.3 GB of them at the first world frame +/// of run 193, of which 2.3 GB were let go again within 13 seconds). The +/// card then stood at 99 to 100.5 % of its budget, buffer copies were +/// turned down for good (31 of 95 made: the frame 355 ms where 95 give +/// 238), and the queue was refused from the first world frame on. With +/// their room kept, the queue stops that much earlier while the world +/// loads and gets it back as the targets are made. +#[cfg(windows)] +pub(crate) fn targets_room_kept() -> u64 { + use std::sync::atomic::Ordering::Relaxed; + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(3072 << 20, |mb| mb.min(8192) << 20) + }); + // 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)); + most.saturating_sub(targets) +} + /// [`room`] as it was at most a tenth of a second ago, for a question /// asked of many textures a frame ([`room`] asks the system each time). #[cfg(windows)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index f47de440..2ce495a3 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -181,11 +181,27 @@ static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; /// used, and a copy may be made up to nine tenths of the budget: the room /// it takes was kept for it. After the burst what is kept is what the /// burst left of the limit (87 MB of 1,024 in run 189). +/// +/// On by default from the build after run 199 +/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies +/// and the world's render targets (+1,603 MB) arrive in the same first +/// world frame and raced for the 448 MB left under the line, and a copy +/// turned down is not asked for again (`lookup` asks once), while its room +/// went on being kept (616 MB to the end of the run). So now: the texture +/// queue also keeps room for the targets (`resource::targets_room_kept`), +/// a copy is made up to 97 hundredths of the budget (its room was kept), +/// and the room of a copy turned down is given up ([`CARD_REFUSED`]). fn card_room_kept_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1")) + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0")) } +/// Title buffers big enough for a copy in the card's memory that were +/// turned down for want of room, since the start, and their bytes: their +/// copies stay in the PC's memory for as long as the title keeps the +/// buffers, so no room is kept for them any more. +static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + /// The bytes of the card's memory the texture queue leaves free for card /// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with /// the switch off or without card copies. @@ -193,7 +209,7 @@ pub(crate) fn card_room_kept() -> u64 { if !card_room_kept_on() || !cards() { return 0; } - card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed)) + card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) } /// The copies in the card's memory. @@ -248,10 +264,30 @@ fn card_for(size: u64) -> Option { // shrinks by the copies' bytes, at most `card_limits`' second number. // (With `card_room_kept_on` the texture queue kept this copy's room // free, and the copy may go up to the queue's own line.) - let tenths = if card_room_kept_on() { 9 } else { 8 }; + let hundredths = if card_room_kept_on() { 97 } else { 80 }; if let Some([budget, used, ..]) = host.video_memory() - && used + size > budget / 10 * tenths + && used + size > budget / 100 * hundredths { + // Said, with the numbers it was decided by: run 193 made 31 copies + // of 95 and no line named the others. The first 64, then every + // 32nd. + let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1; + let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size; + if n <= 64 || n.is_multiple_of(32) { + tracing::info!( + "no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \ + {} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}", + size >> 10, + used >> 20, + budget >> 20, + (budget / 100 * hundredths) >> 20, + CARD_BYTES[0].load(Ordering::Relaxed) >> 20, + most >> 20, + n, + bytes >> 20, + crate::frame::current() + ); + } return None; } if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { @@ -3550,6 +3586,82 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option, u64)>)> = Mutex::new((0, BTreeMap::new())); + +/// Since the last frame line: askings for such copies, and copies made. +static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// A copy of the title memory `[address, address + len)` that starts at +/// `address` itself: for a buffer view whose bytes do not start on an +/// element of the copy its buffer has (`descriptor/host.rs` `own_bytes`). +/// A host view counts its first element from its buffer's start; a console +/// view starts at any address, and the title places views at ring +/// positions inside its big GPU heap. Such a view was refused and its slot +/// read zeros ("buffer view not on an element of its host copy", in every +/// run; upstream VIctory 86a5ed6 found its meshlet culling constants and +/// colour-bake parameter blocks among them and gives each a copy of its +/// own bytes, as here). +/// +/// The copy is brought up to date and written back like any other (a list +/// refreshes the copy its view's slot shows, `buffer_copy`). Kept by +/// (start, bytes) for as long as a list or a slot holds it; of the others, +/// those not asked for lately go once there are many (ring positions +/// change every frame). +pub(crate) fn exact(address: u64, len: u64) -> Option> { + /// Copies kept before the idle ones are looked for, and the askings an + /// idle one stays for. + const MANY: usize = 256; + const LATELY: u64 = 512; + if len == 0 { + return None; + } + EXACT_STATS[0].fetch_add(1, Ordering::Relaxed); + let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner()); + let (tick, map) = &mut *guard; + *tick += 1; + let now = *tick; + if let Some((shadow, used)) = map.get_mut(&(address, len)) { + *used = now; + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + return Some(shadow.clone()); + } + if map.len() >= MANY { + // Held by the map alone (no list), its buffer by the copy alone (no + // slot shows it), and not asked for lately. + map.retain(|_, (shadow, used)| { + Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now + }); + } + let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; + crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len)); + map.insert((address, len), (shadow.clone(), now)); + EXACT_STATS[1].fetch_add(1, Ordering::Relaxed); + Some(shadow) +} + +/// With the frame line: the buffer views that got a copy of their own +/// bytes ([`exact`]), per frame over `frames`, and the copies kept now. +/// Nothing while there are none. +pub(crate) fn exact_line(frames: f64) { + let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed)); + if asked == 0 { + return; + } + let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len(); + tracing::info!( + "buffer views off their copy's elements (they were refused and read zeros; VICTORY_VIEW_OWN_COPY=0 refuses them again): \ + {:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept", + asked as f64 / frames, + made as f64 / frames + ); +} + #[cfg(test)] mod window_tests { use super::{WINDOW, cover, grid, holder, longest_tail, tail_of, window_of}; diff --git a/crates/victory-gpu/src/tiles.rs b/crates/victory-gpu/src/tiles.rs index a8b98f63..6d3c3d8d 100644 --- a/crates/victory-gpu/src/tiles.rs +++ b/crates/victory-gpu/src/tiles.rs @@ -105,18 +105,19 @@ pub(crate) fn wanted() -> bool { }) } +fn parse_floor(value: Option<&str>) -> u64 { + value + .and_then(|v| v.trim().parse::().ok()) + .map_or(1 << 20, |kb| kb.max(64).saturating_mul(1024)) +} + /// The bytes from which a texture is made this way: a megabyte, or /// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not /// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six /// tiles at most, and most of the calls for nothing.) pub(crate) fn floor() -> u64 { static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); - *BYTES.get_or_init(|| { - std::env::var("VICTORY_LEVELS_MIN_KB") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .map_or(1 << 20, |kb| kb.max(64) << 10) - }) + *BYTES.get_or_init(|| parse_floor(std::env::var("VICTORY_LEVELS_MIN_KB").ok().as_deref())) } /// The bytes of the tiles given to textures now: the card's memory they @@ -304,14 +305,18 @@ impl Tiled { } let mut standard = Vec::with_capacity(standard_levels as usize); for tiling in &tilings[..standard_levels as usize] { - let tiles = tiling.WidthInTiles * u32::from(tiling.HeightInTiles) * u32::from(tiling.DepthInTiles); + let tiles = tiling + .WidthInTiles + .checked_mul(u32::from(tiling.HeightInTiles)) + .and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles))) + .unwrap_or(0); if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { return None; } standard.push(tiles); } let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; - if packed_tiles > HEAP_TILES { + if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES { return None; } let full = u64::from(total) * TILE; @@ -366,13 +371,16 @@ impl Tiled { held: u32, room: bool, ) -> (bool, bool) { + let held = held & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); self.held.store(held, Ordering::Relaxed); let card = self.card.load(Ordering::Relaxed); let named = held | card; // The levels the card itself writes are few and are not kept // waiting: a write of the card's into no memory is lost. - let changed = self.give_on(queue, device, texture, named, if room { named } else { card }); - (changed, self.without(named) != 0) + let changed = self.give_locked(&mut given, queue, device, texture, named, if room { named } else { card }); + let missing = self.without_locked(&given, named) != 0; + (changed, missing) } /// At the submission of a list in which the card itself writes the @@ -397,12 +405,25 @@ impl Tiled { texture: &ID3D12Resource, levels: u32, ) -> bool { - let card = self.card.fetch_or(levels, Ordering::Relaxed) | levels; - let changed = self.give_on(queue, device, texture, card | self.held.load(Ordering::Relaxed), levels); - // A level that got no tiles (no heap could be had): the list's - // zeros and its write went nowhere, so the next list that writes - // the level sends its zeros again. - let without = self.without(levels); + let levels = levels & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let prev = self.card.load(Ordering::Relaxed); + let changed = self.give_locked( + &mut given, + queue, + device, + texture, + prev | levels | self.held.load(Ordering::Relaxed), + levels, + ); + // Only levels that actually received tiles (or already had them) saw + // the card's write; a level that got no tiles saw its zeros and write + // dropped, so neither `card` nor `claimed` should keep it. + let without = self.without_locked(&given, levels); + let backed = levels & !without; + if backed != 0 { + self.card.fetch_or(backed, Ordering::Relaxed); + } if without != 0 { self.unclaim(without); } @@ -446,6 +467,10 @@ impl Tiled { /// Of `levels` (a bit a level), the ones that have no tiles now. pub(crate) fn without(&self, levels: u32) -> u32 { let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.without_locked(&given, levels) + } + + fn without_locked(&self, given: &Given, levels: u32) -> u32 { let first_packed = self.standard.len() as u32; let mut without = 0; for level in 0..self.levels.min(32) { @@ -469,6 +494,7 @@ impl Tiled { /// Returns whether the first level a view may show changed /// ([`Tiled::first_shown`]): the caller has the texture's slots made /// again. + #[cfg(test)] pub(crate) fn give_on( &self, queue: &ID3D12CommandQueue, @@ -476,10 +502,22 @@ impl Tiled { texture: &ID3D12Resource, named: u32, may: u32, + ) -> bool { + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.give_locked(&mut given, queue, device, texture, named, may) + } + + fn give_locked( + &self, + given: &mut Given, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, ) -> bool { let has = |level: u32| level < 32 && named & (1 << level) != 0; let now = |level: u32| level < 32 && named & may & (1 << level) != 0; - let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); let first_packed = self.standard.len() as u32; // (subresource, tiles, the level if it has tiles of its own) to map now. let mut wanted: Vec<(u32, u32, Option)> = Vec::new(); @@ -607,24 +645,40 @@ impl Drop for Tiled { } } -/// Keeps a two-dimensional shader view from the levels before `first` of a -/// texture of `levels` levels: it starts at `first` if it started before -/// it, and shows as many levels fewer. A sample then lands on the first -/// level that has memory instead of reading zeros from one that has none; -/// level numbers and sizes a shader asks for count from that level. +/// Keeps a two-dimensional shader view (2D or 2D array) from the levels +/// before `first` of a texture of `levels` levels: it starts at `first` if +/// it started before it, shows as many levels fewer (clamped to the +/// remaining levels), and reduces `ResourceMinLODClamp` by the same shift so +/// the effective minimum LOD stays at the same resource level. pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) { - if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || first >= levels { + if first >= levels { return; } - // SAFETY: a 2D view's member of the union. - let view = unsafe { &mut desc.Anonymous.Texture2D }; - if first <= view.MostDetailedMip { - return; - } - let fewer = first - view.MostDetailedMip; - view.MostDetailedMip = first; - if view.MipLevels != u32::MAX { - view.MipLevels = view.MipLevels.saturating_sub(fewer).max(1); + let clamp = |most: &mut u32, mips: &mut u32, min_lod: &mut f32| { + if first <= *most { + return; + } + let fewer = first - *most; + *most = first; + if *mips != u32::MAX { + *mips = mips.saturating_sub(fewer).clamp(1, levels - first); + } + if *min_lod > 0.0 { + *min_lod = (*min_lod - fewer as f32).max(0.0); + } + }; + match desc.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => { + // SAFETY: `ViewDimension` selects `Texture2D`. + let view = unsafe { &mut desc.Anonymous.Texture2D }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: `ViewDimension` selects `Texture2DArray`. + let view = unsafe { &mut desc.Anonymous.Texture2DArray }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + } + _ => {} } } @@ -1416,4 +1470,118 @@ void look() { s[8] ); } + + #[test] + fn floor_saturates_instead_of_wrapping() { + assert_eq!(parse_floor(None), 1 << 20); + assert_eq!(parse_floor(Some("0")), 64 << 10); + assert_eq!(parse_floor(Some("2048")), 2048 << 10); + assert_eq!(parse_floor(Some(&(1u64 << 54).to_string())), u64::MAX); + assert_eq!(parse_floor(Some(&u64::MAX.to_string())), u64::MAX); + } + + #[test] + fn show_from_clamps_2d_and_2d_array_and_adjusts_min_lod() { + let mut srv2d = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 12, + PlaneSlice: 0, + ResourceMinLODClamp: 3.5, + }, + }, + }; + show_from(&mut srv2d, 3, 11); + // SAFETY: `ViewDimension` is `TEXTURE2D`. + let v2d = unsafe { srv2d.Anonymous.Texture2D }; + assert_eq!(v2d.MostDetailedMip, 3); + // Clamped to remaining levels (11 - 3 = 8), not 12 - 3 = 9. + assert_eq!(v2d.MipLevels, 8); + assert_eq!(v2d.ResourceMinLODClamp, 0.5); + + let mut srv_arr = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: 6, + FirstArraySlice: 0, + ArraySize: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 1.5, + }, + }, + }; + show_from(&mut srv_arr, 2, 11); + // SAFETY: `ViewDimension` is `TEXTURE2DARRAY`. + let varr = unsafe { srv_arr.Anonymous.Texture2DArray }; + assert_eq!(varr.MostDetailedMip, 2); + assert_eq!(varr.MipLevels, 4); + assert_eq!(varr.ResourceMinLODClamp, 0.0); + } + + #[test] + fn card_wrote_failure_does_not_poison_card_mask() { + let Some(host) = host() else { + return; + }; + // A dummy live resource (never mapped because `take()` rejects `HEAP_TILES + 1`). + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = Rig::desc(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 2, false); + let mut tex: Option = None; + // SAFETY: plain texture creation on the host device. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut tex, + ) + .unwrap(); + } + let tex = tex.unwrap(); + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(TILE, Ordering::Relaxed); + let mut tiled = Tiled { + // Level 0 demands > HEAP_TILES so `take()` fails deterministically. + standard: vec![HEAP_TILES + 1, 1], + packed: 0, + levels: 2, + full: TILE, + given: Mutex::new(Given { + levels: vec![false, false], + packed: false, + runs: Vec::new(), + }), + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + claimed: AtomicU32::new(0), + }; + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0); + assert!(!changed); + assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`"); + assert_eq!(tiled.first_shown(), None); + assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed"); + // Even if level 0 later becomes allocatable, an upload with `room == false` + // that does not hold level 0 must not treat level 0 as card-owned. + tiled.standard[0] = 1; + let (changed, waiting) = tiled.uploaded_on(host.queue(), &host.device, &tex, 1 << 1, false); + assert!(!changed && waiting); + assert!(!tiled.has_tiles(0)); + assert_eq!(tiled.given_bytes(), 0); + } } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index bc7d3be8..9bfcb0a5 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -33,6 +33,27 @@ pub(crate) const PAGE: usize = 64 << 10; /// The kernel's page, the unit of its answers. const KERNEL_PAGE: usize = 4096; +/// A title-memory range whose changed pages another subsystem needs to read. +pub(crate) struct Tracked { + start: usize, + end: usize, + seen: Mutex>, +} + +/// Tracks a runtime GPU-memory range, including physical-page views when +/// `views` is true. Other process memory is not tracked. +pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { + let end = start.checked_add(len)?; + if len == 0 || writes(start, end, views).is_none() { + return None; + } + Some(Tracked { + start, + end, + seen: Mutex::default(), + }) +} + struct Journal { /// Numbers the askings; 0 is "never". asked: u64, @@ -377,6 +398,42 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve )) } +impl Tracked { + /// Takes changed pages of `[from, to)`, cut to the tracked range. A + /// partial page stays changed so a later take can read its other bytes. + pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + let (from, to) = (from.max(self.start), to.min(self.end)); + if from >= to { + return Vec::new(); + } + let Some((_, pages)) = writes(from, to, true) else { + return Vec::new(); + }; + let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (page, write) in pages { + if seen.get(&page).is_some_and(|&last| last >= write) { + continue; + } + let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); + if start >= end { + continue; + } + // Keep partial pages dirty: the caller has not taken the rest. + if (page * PAGE).max(self.start) >= from + && ((page + 1) * PAGE).min(self.end) <= to + { + seen.insert(page, write); + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), + } + } + ranges + } +} + /// Guarded blocks of view memory. const BLOCK: usize = PAGE; @@ -698,16 +755,22 @@ pub fn writing(at: usize, len: usize) { /// copies of buffers and textures read through tables take them again); /// 2, the placed textures picked by index that lie under it are due again; /// 4, both also for reads to plain addresses when they have finished. -/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1 -/// alone. `slots`: bit 2 alone. `all`: everything. +/// Unset or `guards`: bit 1 alone. `0`: nothing, counted only (the default +/// until run 199). `1`: bits 1 and 2. `slots`: bit 2 alone. `all`: +/// everything. +/// (Bit 1 by default: in every run 10,000 to 50,000 guarded blocks of host +/// copies lay under such writes and kept the bytes from before; runs 197 +/// and 198 opened them, 9,766 and 10,796 blocks, with nothing worse for +/// it. Bit 2 makes texture slots due and is the one that flooded the +/// queue in an earlier form: still asked for by name.) pub(crate) fn page_writes() -> u8 { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) { + Ok("0") => 0, Ok("1") => 3, - Ok("guards") => 1, Ok("slots") => 2, Ok("all") => 7, - _ => 0, + _ => 1, }) } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index bef2e3c4..63c4de74 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1016,6 +1016,26 @@ fn own_bits_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) } +/// The refusal of a first half of an interpolation whose result is read +/// as data ([`Lower::interp`]). +pub(super) const FIRST_HALF: &str = "the first half of an interpolation"; + +thread_local! { + /// Whether first halves of interpolations are evaluated as the pair + /// they start ([`with_first_half_pairs`]). + static FIRST_HALF_PAIRS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `translate` with first halves of interpolations evaluated as the +/// pair they start: the translation of a program refused with +/// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before). +pub(super) fn with_first_half_pairs(translate: impl FnOnce() -> R) -> R { + let before = FIRST_HALF_PAIRS.replace(true); + let result = translate(); + FIRST_HALF_PAIRS.set(before); + result +} + pub(super) fn host_max_wave() -> u32 { #[cfg(test)] if let Some(lanes) = TEST_HOST_WAVE.get() { @@ -1497,7 +1517,9 @@ impl<'a> Lower<'a> { // the other half of its dst, PS_DeferredTextured): evaluated as the pair it // starts. Approximate for those other bits (P0 + i P10 on the console); a // first half only the second half reads is gone before lowering. - if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { + // Only in the second translation of a program the first + // one refused for it ([`with_first_half_pairs`]). + if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { for (_, i) in &x.io.interps { if let Interp::Interpolated { first, .. } = i { for s in first { @@ -2083,8 +2105,9 @@ impl<'a> Lower<'a> { if !every { if halves { need(self.cur_ir); + return Err(WHERE); } - return Err(WHERE); + return Ok(self.half_sum_present(x)); } let c = self.cur; let i32t = self.s.t.i32; @@ -2112,6 +2135,61 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::Or, first, total)) } + /// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past + /// the end of the data returns early): the console runs the sum in every lane, a lane + /// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds + /// that run's partial sum, the lanes that left included. A lane reads its partner run's + /// sum from the first lane of that run that is here, and +0 where none is (every lane of + /// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left. + fn half_sum_present(&mut self, x: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let here = self.s.m.bool(true); + let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); + // The lanes of the run of `size` lanes at `base` that are here, from bit 0. + let present = |l: &mut Self, base: V, size: u32| -> V { + let upper = l.s.m.cmp(c, pred::IUGE, base, k32); + let word = l.s.m.select(c, upper, bhi, blo); + let at = l.s.m.bin(c, Bin::And, base, k31); + let bits = l.s.m.bin(c, Bin::LShr, word, at); + if size >= 32 { + bits + } else { + let m = l.s.m.i32((1u32 << size) - 1); + l.s.m.bin(c, Bin::And, bits, m) + } + }; + let mut sum = x; + for step in 0..6u32 { + let size = 1u32 << step; + let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1))); + let other = self.s.m.bin(c, Bin::Xor, lane, bit); + let base = self.s.m.bin(c, Bin::And, other, run); + let bits = present(self, base, size); + // FirstbitLo (dx.op 32): the run's first lane that is here + let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let any = self.s.m.cmp(c, pred::NE, bits, zero); + let first = self.s.m.select(c, any, first, zero); + let from = self.s.m.bin(c, Bin::Add, base, first); + let theirs = self.read_lane(sum, from); + let theirs = self.s.m.select(c, any, theirs, zero); + sum = self.add_halves(sum, theirs); + } + let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1)); + let lane0 = self.s.m.bin(c, Bin::And, blo, one); + let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero); + let first = self.read_lane(x, zero); + let first = self.s.m.select(c, lane0, first, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + self.s.m.bin(c, Bin::Or, first, sum) + } + fn run(mut self) -> Result { let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); @@ -5617,6 +5695,18 @@ impl<'a> Lower<'a> { .find_map(|(s, _)| use_of(*s)) }; let use_at = use_of(site).or_else(twin); + // A descriptor nothing uses as one, whose size the code reads all the same (a + // texture picked from the heap by an index in a constant buffer, its width and + // height turned into a texel size; a buffer tested for being empty by its record + // count): the kind from its dwords and its used-resource entry. + let unused = if use_at.is_none() { + self.unused_descriptor_kind(inst, site, code, count) + } else { + None + }; + let (first, props, image, uav, used) = if let Some(kind) = unused { + kind + } else { let Some((at, first)) = use_at else { // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only // copies its dwords and compares them, lane against first lane, and every load @@ -5726,6 +5816,9 @@ impl<'a> Lower<'a> { } _ => return Err("a scalar memory read as data"), }; + (first, props, image, uav, used) + }; + let src = Source::Loaded { load: site, first }; let h = self.handle(site, &src, false, props)?; let c = self.cur; let i32t = self.s.t.i32; @@ -5793,8 +5886,10 @@ impl<'a> Lower<'a> { inst.write(Reg::S(code + first + k)) .is_some_and(|v| self.computed_with(v, 6)) }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) if first == 0 - && computed + && (computed || unused.is_some()) && let Some((lo, hi)) = self.view_address(site) { words.extend([(0, lo), (1, hi)]); @@ -5817,6 +5912,67 @@ impl<'a> Lower<'a> { Ok(()) } + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose dwords the code reads: the first dword, the handle properties, + /// the image kind (none for a buffer), whether it is an unordered view, and its + /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four + /// as a raw view's where the code reads its record count (dword 2); none for anything + /// else (a constant buffer, a sampler, a buffer whose address alone is read). + // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's + // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of + // another kind would answer its own sizes. + #[allow(clippy::type_complexity)] + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(u8, (u32, u32), Option, bool, Option<&'a UsedResource>)> { + // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases + // `descriptor_data` handles on their own. + if self.x.res.lane_copied.contains(&site) + || self.x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }) + { + return None; + } + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + // width (dwords 1-2), height (2), levels (3), depth (4) + 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => { + Some((0, (2 | u, 0x409), Some(2), uav, used)) + } + // the record count + 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => { + Some((0, (11 | u, 0), None, uav, used)) + } + _ => None, + } + } + /// `s_load_dword*` from the program's constant table. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { @@ -7115,12 +7271,6 @@ impl<'a> Lower<'a> { let r = self.read_lane(x, from); int(self, r) } - "v_cvt_f32_f64" => { - let (lo, hi) = self.f64_pair(inst, 0)?; - let bits = self.f64_to_f32_bits(lo, hi); - let r = self.as_float(bits); - float(self, r) - } "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { let mut a = s(self, 0)?; @@ -7138,6 +7288,12 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. @@ -8902,7 +9058,26 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { - return Err("the first half of an interpolation"); + // The first half of a pair: its second half interpolates the + // attribute itself, so nothing needs this half's partial sum. + // But an f16 second half that writes the high half of the + // register this one wrote keeps the low half as it was (the + // console compiler reuses the register; the low half is not + // read), so the register needs a value: 0. + let name = inst.name(); + if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" { + let dst = match &inst.fields { + Fields::Vintrp { dst, .. } => Some(*dst), + Fields::Valu(v) => v.dst, + _ => None, + }; + if let Some(Operand::Vector { reg, .. }) = dst { + let zero = self.s.m.i32(0); + self.write(inst, Reg::V(reg), zero, None); + return Ok(()); + } + } + return Err(FIRST_HALF); }; let name = inst.name(); let (dst, src) = match &inst.fields { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 3f6f9ff0..5217df8d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -297,7 +297,23 @@ pub struct UserData { /// Translates the vertex, pixel, compute or mesh program of a console /// shader container. +/// +/// A program refused because the first half of an interpolation is read as +/// data is translated once more with first halves evaluated as the pair +/// they start (`lower::with_first_half_pairs`), and only such a program: +/// with that on for every program, 8,551 pixel programs of the title that +/// already translated came out changed (an extra evaluation in each), for +/// the sake of 9 that did not translate. pub fn translate(container: &[u8]) -> Result { + match translate_plain(container) { + Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => { + lower::with_first_half_pairs(|| translate_plain(container)) + } + other => other, + } +} + +fn translate_plain(container: &[u8]) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index db82f33b..55cc55de 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -95,10 +95,20 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { /// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet) -> Result { + lowered_on(native, p, wide, 32) +} + +/// [`lowered`] for a host whose waves have at most `host_wave` lanes. +fn lowered_on( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet, + host_wave: u32, +) -> Result { 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(32)); + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); let lowered = lower::lower(&lower::Parts { native, p, @@ -199,6 +209,76 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } +/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a +/// thread past the end of the data): on the console they add +0, and after each step of the +/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the +/// lanes that are here read each partner run's sum from a lane of it that is here. +#[test] +fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { + let mut words = vec![ + 0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay + 0, // s_cbranch_execz to the end (filled in below) + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + // past every word after it, to the program's end + words[1] = 0xBF88_0000 | (words.len() as u32 - 2); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_on(&native, &p, &HashSet::new(), 64).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 wide = |h: u16| { + if h == 0 { + 0.0 + } else { + f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13) + } + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = false; + for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] { + let terms: Vec = (0..64u32) + .map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 }) + .collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); + } + let Some(got) = on_the_card(&shader, [stay, 0]) else { + return; + }; + ran = true; + // (the high half is lane 0's term's: zero) + assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]); + } + if ran { + eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case"); + } +} + /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 /// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The /// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the From 9376fd60c0ba0e76a74c39b49b1407dbac0a64c7 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:30:11 -0500 Subject: [PATCH 03/16] Frame rate, processor side: a cheap fingerprint in the descriptor sync, draw-table slots left to their draws, no failing write-watch calls; card fetches inside their flights (off by default) - Descriptor sync: a multiply-and-fold fingerprint of a record in place of BLAKE3 (35 to 42 ms a frame over 250,000 to 300,000 records), and slots that draws read through tables lately are left to their draws (VICTORY_HEAP_SYNC_TABLES=1 mirrors them too): the pass over the heap went from 70-220 ms a frame to about 3. - Write watch: no kernel asking for memory the guards already hold as view memory (pull request #670 by Jonirulah). - Card copies' flagged pieces can come down inside their own flights (pull request #648 by Jonirulah; VICTORY_CARD_FETCH_INFLIGHT=1, off by default). One game run with it on: no device loss, the copy-back thread's fetch wait 181 -> 0 ms a frame, the card busier; no frame-time gain claimed. - Logging: the heap pass's texture part and buffer slots; indirect compute dispatches over 65,535 groups. - README: what was measured, and that pull request #220 with VICTORY_INDIRECT_WINDOW=1 lost the device twice here and is not in. One five-minute game run of this tree's source on an RTX 4070: no device loss; the frame is still 250 to 380 ms (the card is the limit). This merged tree was built; its test suites were not run. Co-Authored-By: Claude Fable 5.2 --- README.md | 14 + crates/victory-gpu/src/copystat.rs | 12 + crates/victory-gpu/src/descriptor.rs | 3 +- crates/victory-gpu/src/descriptor/host.rs | 77 ++- crates/victory-gpu/src/draw.rs | 7 + crates/victory-gpu/src/host.rs | 579 +++++++++++++++++++++- crates/victory-gpu/src/indirect.rs | 101 ++++ crates/victory-gpu/src/shadow.rs | 200 +++++++- crates/victory-gpu/src/watch.rs | 53 +- 9 files changed, 1030 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index f9830ff6..443c6b11 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,20 @@ What did it, on top of the list below: shader programs translate; a program is translated with first-half interpolation pairs only if it was refused for one (with that on for every program, 8,551 working pixel programs came out changed). +- Frame rate, first cuts on the processor side: the descriptor sync uses a + cheap fingerprint and leaves draw-table slots to their draws (the pass + over the heap went from 70-220 ms a frame to about 3), and memory the + guards already hold is not asked of the write watch (pull request #670 + by Jonirulah). Card copies' pieces can come down inside their own + flights (pull request #648 by Jonirulah, `VICTORY_CARD_FETCH_INFLIGHT=1`, + off by default: the copy-back thread's wait went from 181 ms a frame to + 0 here, but the card got busier, so no gain is claimed yet). The frame is + still 250 to 380 ms: the card is the limit now, most of it the + per-record clamp before each of some 6,700 indirect draws a frame. +- Tried and NOT in this tree: pull request #220 (cheaper indirect draws) + with `VICTORY_INDIRECT_WINDOW=1` cut the card's time from about 100-150 + to 35-80 ms a frame here, and lost the device twice (once with a page + fault on the card after 160 s). Do not turn windows on with it yet. - Known and counted, not fixed yet: an indirect compute pass asks for about 77,500 thread groups in x where one dispatch runs 65,535 (the rest is cut off). diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index ba56d635..cae74b24 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -127,6 +127,12 @@ pub(crate) enum C { WaitsForGroups, WaitsForBuffers, IndirectBounded, + /// `watch::writes` kernel askings that failed (the range is not + /// write-watched: view memory or not watchable). + WatchFailed, + /// `watch::writes` askings not made because the range's first block is + /// already known to be guarded view memory (no kernel call). + WatchKnownView, } const COUNTERS: usize = 80; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; @@ -1264,6 +1270,12 @@ pub(crate) fn log(frames: f64) { longest as f64 / 1e3 ); } + tracing::info!( + " write-watch askings per frame that failed in the kernel: {:.0}; not made because the range \ + is known guarded view memory: {:.0} (VICTORY_VIEW_ASK=1 asks the kernel anyway)", + c[C::WatchFailed as usize], + c[C::WatchKnownView as usize], + ); tracing::info!( " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 6aad6da0..2ea083e7 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -247,10 +247,11 @@ pub(crate) fn sync_line(frames: f64) { } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ - {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.2} ms", + {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.0} left to the \n draws that read them through tables (VICTORY_HEAP_SYNC_TABLES=1 mirrors those too), {:.2} ms", pages as f64 / frames, looked as f64 / frames, mirrored as f64 / frames, + host::COPIED_TABLED.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames, micros as f64 / 1000.0 / frames ); } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 861106a1..21cc1948 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1812,9 +1812,26 @@ impl HostHeap { if index >= self.count { return false; } + // A slot draws read through a table lately is left to its draws, + // as the passes over slots picked by index leave it + // (`texture_slots_remapped`, `slots_written_under`): the title + // writes its per-draw tables into the same heap every frame, and + // each draw makes what its table shows in a slot of its own. Those + // were most of the 26,000 to 43,000 records a frame this pass + // mirrored in run 200 and in the play session after it, each then + // made and brought up to date once more by the pass over buffer + // views (some 50 ms a frame). `VICTORY_HEAP_SYNC_TABLES=1`: they + // are mirrored too, as in run 200. + if !sync_tables() && self.tabled_lately(index, crate::frame::current()) { + COPIED_TABLED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return false; + } let n = record.len(); - // Never 0, which is "never looked at". - let print = u64::from_le_bytes(blake3::hash(record).as_bytes()[..8].try_into().unwrap_or([1; 8])) | 1; + // Never 0, which is "never looked at". (A multiply-and-fold over + // the record's words: BLAKE3 here was most of the 35 to 42 ms a + // frame this pass took over some 250,000 to 300,000 records, run + // 200.) + let print = record_print(record) | 1; { let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); if copied.is_empty() { @@ -2140,6 +2157,37 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { /// The host resource a slot made by [`make`] views, if any. type Kept = Option; +/// Whether the pass over records copied in as bytes also mirrors slots +/// that draws read through tables lately (`VICTORY_HEAP_SYNC_TABLES=1`; +/// off by default: [`HostHeap::mirror_copied`]). +fn sync_tables() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC_TABLES").is_some_and(|v| v == "1")) +} + +/// Since the last frame line: slots on changed heap pages that +/// [`HostHeap::mirror_copied`] left to their draws (tables' slots). +pub(crate) static COPIED_TABLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A 64-bit fingerprint of a descriptor record's bytes (16 or 32 of them): +/// equal records give equal prints, and two different records the same +/// print about once in 2^64. Not a hash anyone can attack: the records +/// are our own. +fn record_print(record: &[u8]) -> u64 { + const K: u64 = 0x9e37_79b9_7f4a_7c15; + let mut h = K ^ record.len() as u64; + let mut words = record.chunks_exact(8); + for word in &mut words { + let w = u64::from_le_bytes(word.try_into().unwrap_or([0; 8])); + h = (h ^ w).wrapping_mul(K); + h ^= h >> 29; + } + for &b in words.remainder() { + h = (h ^ u64::from(b)).wrapping_mul(K); + } + h ^ (h >> 32) +} + /// Whether a buffer view off its buffer's elements gets a copy of its own /// bytes (`VICTORY_VIEW_OWN_COPY=0`: it is refused and reads zeros, as /// before). @@ -3472,6 +3520,31 @@ mod tests { } } +#[cfg(test)] +mod record_print_tests { + use super::record_print; + + /// Equal records print alike; a record that differs in any one byte, + /// or in its length, prints otherwise. + #[test] + fn a_record_that_changed_prints_otherwise() { + let record: Vec = (0..32u8).map(|i| i.wrapping_mul(37).wrapping_add(5)).collect(); + let print = record_print(&record); + assert_eq!(print, record_print(&record.clone())); + for at in 0..32 { + for bit in 0..8 { + let mut other = record.clone(); + other[at] ^= 1 << bit; + assert_ne!(record_print(&other), print, "byte {at} bit {bit}"); + } + } + assert_ne!(record_print(&record[..16]), print); + assert_ne!(record_print(&[0u8; 32]), record_print(&[0u8; 16])); + // A record of zeros is told from "never looked at" by the caller's `| 1`. + assert_ne!(record_print(&[0u8; 32]) | 1, 0); + } +} + #[cfg(test)] mod own_copy_tests { use super::own_bytes_if; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d9768e10..9ba0c2fb 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -363,6 +363,10 @@ pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); /// index ([`State::heap_buffers`]), and the microseconds they took. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Of [`HEAP_BUFFER_MICROS`], the microseconds of the pass over textures +/// picked by index that runs inside it (`heap_textures`), and the buffer +/// slots the pass over buffer views looked at; since the last frame line. +pub(crate) static HEAP_PASS_PARTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; /// Textures brought up to date for shaders that pick them by index /// ([`State::heap_textures`]), the bytes of their memory, and the slots /// still waiting. @@ -1415,6 +1419,7 @@ impl State { // it is named below. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); for (n, &index) in slots.iter().enumerate() { ranges.remove(&index); let Some(handle) = heap.handle(index) else { @@ -1493,7 +1498,9 @@ impl State { } shadow.refresh(list, *from, to - from); } + let textures_began = std::time::Instant::now(); self.heap_textures(list, heap, host); + HEAP_PASS_PARTS[0].fetch_add(textures_began.elapsed().as_micros() as u64, Ordering::Relaxed); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); static LOGGED: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 39f4f337..78a43cb8 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1492,6 +1492,34 @@ struct CardWork { taken: u32, /// Plans made and not done with (`Host::card_done`). out: u32, + /// The fetch inside flights ([`inflight_fetch`]), if it is on and was + /// made. + inflight: Option, +} + +/// What the fetch inside flights needs ([`inflight_fetch`], [`CARD_FETCH`]). +struct CardInflight { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// PC memory, mapped (buffer, mapping, bytes): dword 0 the counter of + /// tickets, then one dword per dword of `CardWork::differs`, the entry + /// of that piece. + table: (ID3D12Resource, usize, u64), + /// PC memory, mapped (buffer, mapping, slots of [`INFLIGHT_SLOT`] + /// bytes): where the pieces come down. + fetched: (ID3D12Resource, usize, u32), + /// Every ticket below it belongs to a landed flight: its slot may be + /// written over. Raised by the thread that lands flights; read when a + /// compare's list is recorded (an older value only gives fewer slots). + landed: u32, + /// What fetches the old way brought (copy, offsets, and the highest + /// send whose lists were surely on the queue ahead of the fetch: its + /// order of the queue less one). A flight sent at or before that ran + /// ahead of the fetch, so the CPU's side holds those bytes as the card + /// had them after the flight, or newer: the flight's own slot is older + /// there and is not merged there. Dropped once every flight sent up to + /// it has landed. + brought: Vec<(std::sync::Arc, usize, usize, u64)>, } // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only @@ -1548,6 +1576,147 @@ void main(uint3 id : SV_DispatchThreadID) { } "#; +/// Whether the pieces a flight's compare flags come down to the PC inside +/// the flight itself (`VICTORY_CARD_FETCH_INFLIGHT=1`; off by default, and +/// only with [`relay`]). +/// +/// With the relay the thread that lands flights fetched the flagged pieces +/// with a list of its own on the host's queue, the one the submitting +/// thread keeps filling: the fetch ran behind every flight sent meanwhile. +/// Measured on an RTX 3070 Laptop: 140.9 ms a frame of that thread waiting +/// for fetches, for 63 pieces (3.2 MB) in about five fetches, some 28 ms a +/// fetch spent queued behind newer flights; and the submitting thread +/// waited 81.7 ms a frame in "title memory read" settles for that thread. +/// +/// With the switch the compare's list does the fetch: right behind the +/// compare, [`CARD_FETCH`] copies each piece it flagged into a slot of a +/// buffer in the PC's memory ([`CardInflight`]), so when the flight's fence +/// is reached its bytes are there, and the landing merges them +/// (`Shadow::card_merge_relay`) with no list, signal or wait of its own. +/// The merge's "fetched after" is the flight's own send number +/// (`CardPlan::sent_as`): see [`Host::relay_card_back`] for why that is +/// exact and when a landing falls back to the old fetch. +fn inflight_fetch() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_CARD_FETCH_INFLIGHT").is_some_and(|v| v == "1")) +} + +/// The bytes of the PC's memory pieces fetched inside flights go to +/// ([`inflight_fetch`]; `VICTORY_CARD_FETCH_INFLIGHT_MB`, 64): 1,024 slots +/// ([`inflight_slots`]). A flight whose flagged pieces find no free slot +/// lands the old way. +fn inflight_fetch_bytes() -> u64 { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_FETCH_INFLIGHT_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(64).max(1) << 20 + }) +} + +/// A slot of [`CARD_FETCH`]: a 64 KiB piece as the compare cuts it, widened +/// to 16 bytes at both ends (one more 16-byte step where the copy does not +/// start at a multiple of 16 in its piece). +pub(crate) const INFLIGHT_SLOT: u64 = (64 << 10) + 16; + +/// The slots for `bytes` asked of [`inflight_fetch_bytes`]: one per 64 KiB, +/// rounded down to a power of two (at least 1, at most 2^15: the shader's +/// byte offsets into the slots are 32-bit), so that +/// `ticket % slots` runs on without a jump when the 32-bit ticket wraps +/// (2^32 is a multiple of it; with 1,023 slots it would jump by 4 and two +/// tickets in the air could share a slot). The buffer is `slots` times +/// [`INFLIGHT_SLOT`], a little over `bytes`. +pub(crate) fn inflight_slots(bytes: u64) -> u32 { + let wanted = (bytes >> 16).clamp(1, 1 << 15); + 1u32 << (63 - wanted.leading_zeros()) +} + +/// [`CARD_FETCH`]'s table entry for a piece the compare did not flag. +pub(crate) const INFLIGHT_NONE: u32 = 0xffff_ffff; + +/// Where piece `i` of `span` starts in its [`CARD_FETCH`] slot, as an +/// offset of the copy: the compare's lower bound of the piece, widened down +/// to 16 bytes (`CARD_COMPARE`, before clamping to the declared range). +/// What `Shadow::card_piece` gives for the piece lies at or above it, and +/// within [`INFLIGHT_SLOT`] of it. +pub(crate) fn inflight_piece_from(span: &crate::shadow::CardSpan, i: u32) -> usize { + let lo = (span.first + i) as usize * 65536; + let lo = lo.saturating_sub(span.skew as usize); + lo & !15 +} + +/// Whether the ticket `k` of [`CARD_FETCH`]'s counter gets a slot, with +/// every ticket below `floor` landed and `slots` slots: the slot is +/// `k % slots`. The tickets of flights still in the air are at or above +/// `floor` (they are taken in the queue's order and flights land in that +/// order), so two that get a slot are fewer than `slots` apart and never +/// share one. The arithmetic of the shader, for the tests. +pub(crate) fn inflight_gets_slot(k: u32, floor: u32, slots: u32) -> bool { + k.wrapping_sub(floor) < slots +} + +/// The fetch inside a flight ([`inflight_fetch`]), run in the compare's list +/// right behind the compare of a declared range (a UAV barrier between): +/// one group per piece (looping where a range has more than 65,535); where +/// `differs` flags the piece, its first thread takes a ticket of the +/// counter (`table`'s dword 0) and, if [`inflight_gets_slot`], the group +/// copies the piece, cut and widened as the compare hashes it, into slot +/// `ticket % slots` of `fetched`. Every piece's entry in `table` (dword 1 + +/// its dword in `differs`) is written: the ticket, also one that got no +/// slot (the landing repeats the test with the plan's `landed`), or +/// [`INFLIGHT_NONE`]. +pub(crate) const CARD_FETCH: &str = r#" +#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)" +#define SLOT 65552u +#define NONE 0xffffffffu +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 (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint landed; // every ticket below it is landed + uint slots; // slots of `fetched` + uint groups; // groups dispatched +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer differs : register(u0); +RWByteAddressBuffer table : register(u1); +RWByteAddressBuffer fetched : register(u2); +groupshared uint ticket; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) { + [loop] + for (uint i = group.x; i < pieces; i += groups) { + if (t == 0u) { + uint entry = NONE; + if (differs.Load(out_at + i * 4u) != 0u) { + uint k; + table.InterlockedAdd(0, 1u, k); + entry = k; + } + table.Store(4u + out_at + i * 4u, entry); + ticket = entry; + } + GroupMemoryBarrierWithGroupSync(); + uint k = ticket; + GroupMemoryBarrierWithGroupSync(); + if (k != NONE && (k - landed) < slots) { + uint piece = first + i; + 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 into = (k % slots) * SLOT; + [loop] + for (uint at = lo + t * 16u; at < hi; at += 1024u) { + fetched.Store4(into + (at - lo), now.Load4(at)); + } + } + } +} +"#; + /// 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 @@ -1606,6 +1775,15 @@ struct CardPlan { /// The lists of ours the plan recorded (whether the compare, the /// list), given back by `Host::card_done`. lists: Vec<(bool, Prelude)>, + /// With [`relay`], the number of this plan's send of changed ranges + /// (`QUEUE_ORDER`); else 0. + sent_as: u64, + /// Whether the compare's list fetches the flagged pieces itself + /// ([`inflight_fetch`]): every compared range has its [`CARD_FETCH`]. + inflight: bool, + /// The `CardInflight::landed` its [`CARD_FETCH`] was told: which of its + /// tickets got a slot ([`inflight_gets_slot`]). + inflight_landed: u32, } /// One piece of submission-time work, in recorded order. @@ -1863,6 +2041,86 @@ static QUEUE_ORDER: Mutex = Mutex::new(0); /// copies' pieces, microseconds of landing in all. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; +/// Since the last frame-rate line, with [`inflight_fetch`]: pieces merged +/// from the slots their flights fetched them to, their bytes, landings that +/// went the old way because a plan's pieces overflowed the slots, and +/// landings that fetched the old way (for any reason, overflow too). +static INFLIGHT_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// After a fetch the old way taken with the queue's count at `after`, for +/// plans whose highest send is `landed`: up to which send the notes of +/// sends to card copies may go (`crate::shadow::relay_fetched`). +/// +/// Without [`inflight_fetch`] every later merge is of a later fetch, whose +/// count is `after` or more: notes up to `after` are of no use, as before. +/// With it, a flight still in the air, sent before the fetch, merges its +/// own slot with "fetched after" its own send, which may be below `after`: +/// it needs the notes of the sends between, or it takes the title's bytes +/// that went up in them for its shaders' writes and puts its older card +/// bytes over them. (Flights 5, 6, 7 in the air; 5 lands the old way with +/// the count at 7; a title byte went up in send 7 into a piece 6's shaders +/// write; 6 lands from its slot, which holds that byte from before send 7.) +/// So the mark goes only to the landed plans' highest send: every flight +/// still to land was sent after it, and every later fetch the old way +/// takes a count at least that high. (`CardInflight::brought` is another +/// matter: the card's bytes the fetch put in the CPU's side, not the +/// title's.) +pub(crate) fn fallback_fetched_mark(inflight: bool, after: u64, landed: Option) -> u64 { + match (inflight, landed) { + (false, _) => after, + (true, Some(landed)) => landed.min(after), + (true, None) => 0, + } +} + +/// The landed mark of [`CARD_FETCH`]'s tickets after ticket `k` landed: one +/// past `k` if that is ahead of `landed`, in wrapping order (tickets in the +/// air are always within 2^31 of the mark), else `landed`. +pub(crate) fn inflight_raise(landed: u32, k: u32) -> u32 { + let next = k.wrapping_add(1); + if (next.wrapping_sub(landed) as i32) > 0 { next } else { landed } +} + +/// With [`inflight_fetch`], after a landing merged (either way): the tickets +/// these plans' fetches took are landed, and their slots may be written +/// over. Plans land in the line's order and tickets are taken in the +/// queue's (a UAV barrier opens every compare's list), so every ticket of a +/// plan in the air is ahead of these. +/// +/// The counter is never reset and wraps after 2^32 tickets: the mark is +/// raised in wrapping order ([`inflight_raise`]), and the slots are a power +/// of two, so `k % slots` runs on across the wrap. shortcut: ticket +/// 0xffff_ffff reads as [`INFLIGHT_NONE`]; a flagged piece that draws it +/// copies nothing and its landing goes the old way, once every 2^32. +fn inflight_tickets_landed(plans: &[&CardPlan]) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + let dwords = (work.differs.2 / 4) as usize; + let Some(inflight) = work.inflight.as_mut() else { + return; + }; + // SAFETY: the mapping of the tickets; these plans' fetches have run. + let table = unsafe { std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords) }; + for plan in plans.iter().filter(|p| p.inflight) { + for r in plan.ranges.iter().filter(|r| r.compared) { + for p in 0..r.span.pieces { + if let Some(&k) = table.get((r.at + p) as usize) + && k != INFLIGHT_NONE + { + inflight.landed = inflight_raise(inflight.landed, k); + } + } + } + } + // Every flight still to land was sent after these: what fetches the old + // way brought up to them concerns none of them. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + inflight.brought.retain(|b| b.3 > last); + } +} + /// Of the line's things in order (a flight: the value signalled on the /// host's fence behind it; a write or a signal behind a flight: `None`): /// how many, from the front, can be landed when the card has reached @@ -2571,6 +2829,18 @@ fn late_line(frames: f64) { r[3] / 1000.0, r[4] / 1000.0, ); + if inflight_fetch() { + let i: Vec = INFLIGHT_STATS.iter().map(|i| i.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "card copies' pieces fetched inside their flights per frame (VICTORY_CARD_FETCH_INFLIGHT=1): {:.1} pieces \ + ({:.2} MB) merged with no fetch of their own; {:.1} landings fetched the old way (the wait above), {:.1} of \ + them because a flight's pieces overflowed the slots", + i[0], + i[1] / (1 << 20) as f64, + i[3], + i[2], + ); + } } if late_exact() { let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); @@ -3066,10 +3336,83 @@ impl Host { fetched: None, taken: 0, out: 0, + inflight: if inflight_fetch() { self.make_card_inflight(RESULTS) } else { None }, }) } } + /// [`CardInflight`] for `results` bytes of the compare's results; `None` + /// (and the old fetch) if the shader or the memory cannot be had. + fn make_card_inflight(&self, results: u64) -> Option { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let made = (|| -> windows::core::Result { + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + CARD_FETCH.as_ptr().cast(), + CARD_FETCH.len(), + windows::core::s!("card fetch in flight"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let slots = inflight_slots(inflight_fetch_bytes()); + let (table, table_data) = self.shared_buffer(4 + results).ok_or_else(windows::core::Error::empty)?; + name(&table, || "card fetch in flight: tickets".into()); + let fetched_bytes = u64::from(slots) * INFLIGHT_SLOT; + let (fetched, fetched_data) = self.shared_buffer(fetched_bytes).ok_or_else(windows::core::Error::empty)?; + name(&fetched, || "card fetch in flight: pieces".into()); + // SAFETY: the mapping holds the counter; nothing of ours ran + // on the card with it yet. + unsafe { table_data.cast::().write_volatile(0) }; + // SAFETY: the blob's own bytes; the root signature is inside + // the shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.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(CardInflight { + root, + pso, + table: (table, table_data as usize, 4 + results), + fetched: (fetched, fetched_data as usize, slots), + landed: 0, + brought: Vec::new(), + }) + } + })(); + match made { + Ok(inflight) => { + tracing::info!( + slots = inflight.fetched.2, + "card copies' flagged pieces come down inside their flights (VICTORY_CARD_FETCH_INFLIGHT=1)" + ); + Some(inflight) + } + Err(e) => { + tracing::warn!(error = %e, "no fetch inside flights (VICTORY_CARD_FETCH_INFLIGHT=1): pieces are fetched the old way"); + None + } + } + } + /// Before a submission's lists run, for copies in the card's memory /// ([`crate::shadow::cards`]): what changed on their CPU side since /// the last submission goes to their card side (a list of ours, run @@ -3209,6 +3552,9 @@ impl Host { check: None, _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), lists: used, + sent_as, + inflight: false, + inflight_landed: 0, }; // Each byte once, as the copy-back joins the declared ranges. The // results go behind those of plans still in the air. @@ -3278,6 +3624,40 @@ impl Host { list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } + // The fetch inside the flight (`inflight_fetch`): behind + // every compare of the list, the pieces they flagged go + // to slots in the PC's memory. + if flown && let Some(inflight) = &work.inflight { + 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(&inflight.root); + list.SetPipelineState(&inflight.pso); + list.SetComputeRootUnorderedAccessView(2, work.differs.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, inflight.table.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(4, inflight.fetched.0.GetGPUVirtualAddress()); + let mut every = true; + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(_), size)) = r.shadow.card_sides() else { + every = false; + continue; + }; + let groups = r.span.pieces.clamp(1, 65535); + let constants = + [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, inflight.landed, inflight.fetched.2, groups]; + list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.Dispatch(groups, 1, 1); + } + plan.inflight = every; + plan.inflight_landed = inflight.landed; + } list.Close()?; list.cast() })() @@ -3350,7 +3730,18 @@ impl Host { /// whatever was sent meanwhile, so it may bring a later flight's /// bytes, which that flight's landing then finds merged already; and /// nothing is sent back up. + /// + /// With [`inflight_fetch`] the pieces are first looked for where the + /// flights' own compare lists put them ([`Host::relay_card_inflight`]); + /// only a landing that cannot take them from there fetches, as here. fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + if inflight_fetch() { + let landed = self.relay_card_inflight(plans); + inflight_tickets_landed(plans); + if landed { + return; + } + } 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)) @@ -3392,10 +3783,22 @@ impl Host { } } if pieces.is_empty() { + if inflight_fetch() { + // The next merge may be of a flight in the air now, with + // bytes from when it ran: only sends up to these plans' are + // older than it. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + crate::shadow::relay_fetched(last); + } + return; + } // Nothing to fetch: every send so far is older than the next fetch. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); return; } + if inflight_fetch() { + INFLIGHT_STATS[3].fetch_add(1, Ordering::Relaxed); + } if fetch.is_none() { *fetch = self.make_relay_fetch(); } @@ -3441,6 +3844,17 @@ impl Host { Ok(after) => after, Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), }; + // This fetch may bring bytes of flights in the air now: their own + // slots are older than what it puts in the CPU's side there + // (`relay_card_inflight`). Sends up to `after` are numbered, and the + // submission numbered `after` may not have its lists on the queue + // yet; every one before it has (the submission lock). + if inflight_fetch() + && after > 1 + && let Some(inflight) = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|w| w.inflight.as_mut()) + { + inflight.brought.extend(pieces.iter().map(|(shadow, lo, hi, _)| (shadow.clone(), *lo, *hi, after - 1))); + } let us = waiting.elapsed().as_micros() as u64; RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); { @@ -3461,8 +3875,161 @@ impl Host { written += merged; } COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); - // 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 the + // fetch inside flights only those up to these plans' are + // (`fallback_fetched_mark`). + let landed = plans.iter().map(|p| p.sent_as).max(); + crate::shadow::relay_fetched(fallback_fetched_mark(inflight_fetch(), after, landed)); + } + + /// [`Host::relay_card_back`] with [`inflight_fetch`]: the pieces these + /// plans' compares flagged are taken from the slots their own compare + /// lists copied them to ([`CARD_FETCH`]) and merged, plan by plan in the + /// line's order, with no list or wait of ours. `false` (nothing merged) + /// if any plan cannot land so; the caller then lands them all the old + /// way, as without the switch. + /// + /// The merge's "fetched after" (`Shadow::card_merge_relay`) is the + /// plan's own `sent_as`. `QUEUE_ORDER` is raised only in + /// `Host::card_before`, under the submission lock, and that lock is held + /// until the submission's lists and its compare's list are on the queue + /// behind its sync list: so when the compare's list ran, the card had + /// received exactly the sends 1..=`sent_as` of title bytes and no later + /// one, which is what the merge's skip of later sends asks. (The old + /// fetch, by contrast, ran whenever it reached the queue, and took the + /// count at its own ExecuteCommandLists.) + /// + /// When a landing goes the old way instead, all of it does: a fetch the + /// old way brings the card's bytes as they are now, newer than the slots + /// of plans in the air then, and merging an older slot after it would + /// put a flight's bytes back over a later flight's. For the same reason + /// the bytes such a fetch brought (`CardInflight::brought`) are left + /// out of the slots of flights whose lists were on the queue ahead of + /// it: the CPU's side holds what the card held after them there. The + /// rest of their slots is merged, newer than anything merged there + /// before. (Left out whole, a flight sent before such a fetch would have + /// had to land the old way, its fetch taking a later count still: one + /// overflow kept every landing on the old way while flights were in + /// the air.) Plans land in the line's order, each plan's slot as it was + /// right behind its own lists, so every merge here is of bytes at least + /// as new as the CPU's side holds. + /// + /// shortcut: all or nothing per landing, and a plan whose pieces overflow + /// the slots lands the old way for all its pieces, not only the ones + /// left out. + fn relay_card_inflight(&self, plans: &[&CardPlan]) -> bool { + use std::sync::Arc; + type Piece = (Arc, usize, usize, usize, u64); + let mut pieces: Vec = Vec::new(); + { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_ref() else { + return false; + }; + let Some(inflight) = &work.inflight else { + return false; + }; + let dwords = (work.differs.2 / 4) as usize; + // SAFETY: the mappings of the results and the tickets. The + // compares and fetches of these plans have run, and their dwords + // are given to no other plan before these are done with + // (`card_done`). + let (differs, table) = unsafe { + ( + std::slice::from_raw_parts(work.differs.1 as *const u32, dwords), + std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords), + ) + }; + let slots = inflight.fetched.2; + for plan in plans { + if plan.ranges.is_empty() { + continue; + } + if !plan.inflight || plan.ranges.iter().any(|r| !r.compared) { + return false; + } + // Pieces (copy, number) the compare flagged, with their ticket. + let mut tickets: std::collections::HashMap<(usize, u32), u32> = std::collections::HashMap::new(); + let mut flags: Vec<(usize, u32, bool)> = Vec::new(); + for r in &plan.ranges { + let copy = Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + let at = (r.at + p) as usize; + let (Some(&flag), Some(&entry)) = (differs.get(at), table.get(at)) else { + return false; + }; + if flag != 0 { + if entry == INFLIGHT_NONE { + return false; + } + if !inflight_gets_slot(entry, plan.inflight_landed, slots) { + INFLIGHT_STATS[2].fetch_add(1, Ordering::Relaxed); + return false; + } + tickets.insert((copy, r.span.first + p), entry); + } + flags.push((copy, r.span.first + p, flag != 0)); + } + } + let fetched = flagged_pieces(&flags); + let mut seen = std::collections::HashSet::new(); + for r in &plan.ranges { + let copy = Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + let piece = r.span.first + p; + if !fetched.contains(&(copy, piece)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo >= hi || !seen.insert((copy, lo, hi)) { + continue; + } + let from = inflight_piece_from(&r.span, p); + let Some(&k) = tickets.get(&(copy, piece)) else { + return false; + }; + if lo < from || (hi - from) as u64 > INFLIGHT_SLOT { + return false; + } + let slot = inflight.fetched.1 + (k % slots) as usize * INFLIGHT_SLOT as usize; + // Bytes a fetch the old way brought after this flight ran. + let newer: Vec<(usize, usize)> = inflight + .brought + .iter() + .filter(|b| b.3 >= plan.sent_as && Arc::ptr_eq(&b.0, &r.shadow) && b.1 < hi && b.2 > lo) + .map(|b| (b.1, b.2)) + .collect(); + for (a, b) in crate::shadow::outside(lo, hi, newer) { + pieces.push((r.shadow.clone(), a, b, slot + (a - from), plan.sent_as)); + } + } + } + } + } + // Outside the lock: no slot of these plans is written over before + // their tickets are landed (`inflight_tickets_landed`, after this). + let mut title = Vec::new(); + let (mut written, mut bytes) = (0, 0u64); + for (shadow, lo, hi, at, after) in &pieces { + // SAFETY: inside the mapping of the slots (checked above); the + // copy into it ran in the plan's flight, which the card has run. + let gpu = unsafe { std::slice::from_raw_parts(*at as *const u8, hi - lo) }; + written += shadow.card_merge_relay(*lo, gpu, *after, &mut title); + bytes += (hi - lo) as u64; + } + for plan in plans { + for r in &plan.ranges { + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + INFLIGHT_STATS[0].fetch_add(pieces.len() as u64, Ordering::Relaxed); + INFLIGHT_STATS[1].fetch_add(bytes, Ordering::Relaxed); + // The next merge is of a later plan, or a fetch the old way sent now. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + crate::shadow::relay_fetched(last); + } + true } /// [`relay`], on the thread that lands flights: `items` are the first @@ -5817,6 +6384,14 @@ impl Meter { tracing::info!( "indirect compute dispatches: the largest group count in x asked for {compute_widest} (run: at most 65535), {compute_cut:.1} records per frame asked for more and were cut to that" ); + { + let [texture_us, slots] = [0, 1].map(|i| crate::draw::HEAP_PASS_PARTS[i].swap(0, Ordering::Relaxed)); + tracing::info!( + "the pass over the heap per frame (the frame line's \"heap buffers ... ms\" is both parts): {:.1} ms in its pass over textures picked by index; {:.0} buffer slots looked at by its pass over buffer views", + texture_us as f64 / 1e3 / frames, + slots as f64 / frames + ); + } crate::shadow::exact_line(frames); crate::descriptor::sync_line(frames); late_line(frames); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 4088599c..3005031c 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -733,6 +733,107 @@ void main() { assert_eq!(run(&mut warp, 2), [0, 0, 0]); } + /// The fetch inside flights (`crate::host::CARD_FETCH`), on the software + /// adapter, in one list behind the compare as `Host::card_before` + /// records it: each flagged piece takes a ticket and, while it is + /// within the slots of the lowest ticket in the air, its bytes go to + /// its slot; an unflagged piece's entry says so; a ticket past the + /// slots is written but copies nothing. + #[test] + fn warp_card_fetch_copies_flagged_pieces_to_their_slots() { + use crate::host::{CARD_COMPARE, CARD_FETCH, INFLIGHT_NONE, INFLIGHT_SLOT}; + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, CARD_COMPARE).expect("the card compare must compile on WARP"); + let fetch = compile_cs(&warp.device, CARD_FETCH).expect("the card fetch must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + // The copy starts 40 bytes into its piece 0: piece 0 is short, the + // others straddle title pieces and start off a multiple of 16. + const SKEW: u32 = 40; + 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 + 1)); + let (_differs, _, differs_gpu) = warp.shared_buffer(64); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(4 + 64); + let slots = 1u32; + let (_fetched, fetched_ptr, fetched_gpu) = warp.shared_buffer(INFLIGHT_SLOT * u64::from(slots)); + let content: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mappings hold what is written. + unsafe { + std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size); + table_ptr.cast::().write_volatile(0); + } + let pieces = PIECES + 1; + let run = |warp: &mut WarpHarness, mode: u32, landed: u32| -> Vec { + // SAFETY: our open list, live buffers, the shaders' own root + // signatures; the mappings hold what is read and written. + unsafe { + 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(1, 1, 1); + if mode == 2 { + warp.list.ResourceBarrier(&[uav_barrier()]); + warp.list.SetComputeRootSignature(&fetch.root); + warp.list.SetPipelineState(&fetch.pso); + // Two groups for four pieces: the loop over pieces. + let constants = [0u32, SKEW, size as u32, pieces, 0, landed, slots, 2]; + 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, table_gpu); + warp.list.SetComputeRootUnorderedAccessView(4, fetched_gpu); + warp.list.Dispatch(2, 1, 1); + } + } + warp.submit_and_wait(); + // SAFETY: as above. + (0..=pieces as usize).map(|i| unsafe { table_ptr.cast::().add(i).read_volatile() }).collect() + }; + // SAFETY (each): inside the mapping of the copy. + let set = |at: usize, value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // SAFETY (each): the slot's mapping holds `INFLIGHT_SLOT` bytes. + let slot = |len: usize| unsafe { std::slice::from_raw_parts(fetched_ptr, len).to_vec() }; + run(&mut warp, 0, 0); + // Piece 2 of the copy (title piece 2: bytes 2 * 64 KiB - 40 on), its + // slot from the multiple of 16 below to the one above its end. + let from = 2 * PIECE - SKEW as usize; + let widened = from & !15; + assert_ne!(widened, from); + set(from + 100, content[from + 100] ^ 0x40); + let table = run(&mut warp, 2, 0); + assert_eq!(table, [1, INFLIGHT_NONE, INFLIGHT_NONE, 0, INFLIGHT_NONE]); + let mut wanted = content[widened..widened + INFLIGHT_SLOT as usize].to_vec(); + wanted[from + 100 - widened] ^= 0x40; + assert_eq!(slot(INFLIGHT_SLOT as usize), wanted, "piece 2 in slot 0"); + // Two pieces flagged with one slot, ticket 0 not landed: tickets 1 + // and 2 get none and the slot keeps what it held. + set(5, content[5] ^ 1); + set(PIECE + 7, content[PIECE + 7] ^ 1); + let table = run(&mut warp, 2, 0); + assert_eq!(table[0], 3); + let mut tickets = [table[1], table[2]]; + tickets.sort_unstable(); + assert_eq!(tickets, [1, 2]); + assert_eq!(&table[3..], [INFLIGHT_NONE, INFLIGHT_NONE]); + assert_eq!(slot(INFLIGHT_SLOT as usize), wanted); + // Every ticket up to 2 landed: the next one, 3, gets slot 0. Piece + // 0 starts at the copy's start. + set(9, content[9] ^ 2); + let table = run(&mut warp, 2, 3); + assert_eq!(table, [4, 3, INFLIGHT_NONE, INFLIGHT_NONE, INFLIGHT_NONE]); + let mut piece0 = content[..PIECE - SKEW as usize].to_vec(); + piece0[5] ^= 1; + piece0[9] ^= 2; + assert_eq!(slot(PIECE - SKEW as usize), piece0); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 2ce495a3..756462d0 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -521,6 +521,107 @@ mod card_tests { } } + /// The fetch inside flights (`CARD_FETCH` in host.rs) copies each piece + /// from `inflight_piece_from` on: what the merge takes of the piece lies + /// in that slot. + #[test] + fn a_piece_fetched_in_flight_fits_its_slot() { + let slot = crate::host::INFLIGHT_SLOT as usize; + for start in [0usize, 4096, 7, PIECE - 16, PIECE - 3, 3 * PIECE + 0x1f09, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + let at = crate::host::inflight_piece_from(&span, i); + assert_eq!(at % 16, 0); + assert!(lo >= at && hi - at <= slot, "{start:#x} {from} {to} piece {i}: {lo}..{hi} from {at}"); + } + } + } + } + + /// The slots are a power of two, one per 64 KiB asked, within the + /// shader's 32-bit offsets. + #[test] + fn inflight_slots_are_a_power_of_two() { + use crate::host::{INFLIGHT_SLOT, inflight_slots}; + assert_eq!(inflight_slots(64 << 20), 1024); + assert_eq!(inflight_slots(100 << 20), 1024); + assert_eq!(inflight_slots(1), 1); + assert_eq!(inflight_slots(1 << 20), 16); + let most = inflight_slots(u64::MAX); + assert!(most.is_power_of_two() && u64::from(most) * INFLIGHT_SLOT <= 1 << 32); + } + + /// Tickets drawn and landed in order, the mark raised as the landing + /// raises it (every ticket a landed flight drew), through the counter's + /// wrap with the slots the default gives: no two tickets in the air + /// that got a slot share one, slots are still given after the wrap, and + /// the mark follows the counter. + #[test] + fn inflight_tickets_never_share_a_slot_across_the_wrap() { + use crate::host::{inflight_gets_slot, inflight_raise, inflight_slots}; + let slots = inflight_slots(64 << 20); + let mut landed = u32::MAX - 3000; + let mut next = landed; + // Flights of 1 to 700 flagged pieces, up to three in the air: + // (tickets drawn, those that got a slot). + let mut air: std::collections::VecDeque<(Vec, Vec)> = Default::default(); + let mut after_wrap = 0; + for flight in 0..40u32 { + let drawn: Vec = (0..1 + flight * 37 % 700).map(|i| next.wrapping_add(i)).collect(); + next = next.wrapping_add(drawn.len() as u32); + let slotted: Vec = drawn.iter().copied().filter(|&k| inflight_gets_slot(k, landed, slots)).collect(); + after_wrap += slotted.iter().filter(|&&k| k < 1 << 20).count(); + air.push_back((drawn, slotted)); + let mut used: Vec = air.iter().flat_map(|a| a.1.iter()).map(|k| k % slots).collect(); + let n = used.len(); + used.sort_unstable(); + used.dedup(); + assert_eq!(used.len(), n, "flight {flight}: two tickets in the air share a slot"); + if air.len() == 3 + && let Some((drawn, _)) = air.pop_front() + { + for k in drawn { + landed = inflight_raise(landed, k); + } + } + } + while let Some((drawn, _)) = air.pop_front() { + for k in drawn { + landed = inflight_raise(landed, k); + } + } + assert!(next < 1 << 20, "the counter wrapped"); + assert!(after_wrap > 0, "slots after the wrap"); + assert_eq!(landed, next); + // Raised in wrapping order, never back. + assert_eq!(inflight_raise(u32::MAX - 1, u32::MAX), 0); + assert_eq!(inflight_raise(5, 2), 5); + assert_eq!(inflight_raise(u32::MAX - 1, 3), 4); + assert!(!inflight_gets_slot(3, 4, 8)); + } + + /// Flights 5, 6, 7 in the air with the fetch inside flights: 5 lands + /// the old way with the queue's count at 7. The title's byte that went + /// up in send 7 must still be told apart when 6 lands from its slot + /// (its merge leaves out sends after 6), so send 7's note must outlive + /// the mark (`card_dirty` keeps notes above it, `card_merge_relay` + /// leaves out those above its "fetched after"). + #[test] + fn a_fetch_the_old_way_keeps_the_notes_flights_in_the_air_need() { + use crate::host::fallback_fetched_mark; + let notes = [5u64, 6, 7]; + let mark = fallback_fetched_mark(true, 7, Some(5)); + let kept: Vec = notes.iter().copied().filter(|&s| s > mark).collect(); + assert!(kept.iter().any(|&s| s > 6), "send 7's note was dropped before flight 6 merged"); + assert_eq!(mark, 5); + // Without the switch every later merge fetches after 7: as before. + assert_eq!(fallback_fetched_mark(false, 7, Some(5)), 7); + assert_eq!(fallback_fetched_mark(true, 7, None), 0); + } + /// Changed ranges are joined where they overlap or touch, and only there. #[test] fn ranges_join_where_they_touch() { @@ -649,7 +750,7 @@ fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { } /// `[from, to)` without the ranges of `skip`, in order. -fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { +pub(crate) fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { skip.sort_unstable(); let mut out = Vec::new(); let mut at = from; @@ -3768,6 +3869,103 @@ mod window_tests { } } +#[cfg(test)] +mod card_merge_tests { + use super::{Card, Shadow}; + use std::sync::Mutex; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + + /// A plain buffer on the software adapter: what a copy's `buffer` and + /// its card's `staging` are; the merge never touches them. + fn warp_buffer() -> Option { + // SAFETY: plain DXGI and D3D12 creation calls on the software adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut device).ok()?; + let device = device?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 64 << 10, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .ok()?; + buffer + } + } + + /// The mixed landing the fetch inside flights must survive, on a real + /// copy in the card's memory and its merge (`Shadow::card_merge_relay`): + /// flights 5, 6, 7 in the air; 5 lands the old way with the queue's + /// count at 7; the title wrote a byte that went up in send 7 into a + /// piece flight 6's shaders write; 6 then lands from its own slot, which + /// holds that byte as it was before send 7. The notes of sends are + /// dropped as `card_dirty` drops them, below the mark the old-way fetch + /// sets (`crate::host::fallback_fetched_mark`): with the mark at the + /// landed plans' send the title's byte survives and the shader's write + /// lands; with the mark at the fetch's count (as before the fix) the + /// title's byte is put back to the card's older one. + #[test] + fn a_title_byte_sent_after_a_flight_survives_its_slot() { + let (Some(buffer), Some(staging)) = (warp_buffer(), warp_buffer()) else { + return; + }; + const LEN: usize = 64 << 10; + let (title_byte, shader_byte) = (100usize, 200usize); + let content: Vec = (0..LEN).map(|i| (i * 7 + 3) as u8).collect(); + let land = |mark: u64| -> Vec { + let mut title = content.clone(); + let mut side = content.clone(); + // The title's byte, refreshed into the CPU's side and sent up in send 7. + title[title_byte] ^= 0x5a; + side[title_byte] = title[title_byte]; + let mut shadow = Shadow::new(buffer.clone(), side.as_mut_ptr(), 0, title.as_ptr() as u64, LEN as u64); + shadow.card = Some(Card { + staging: staging.clone(), + before: Mutex::new(None), + dirty: Mutex::default(), + sent: Mutex::new(vec![(title_byte, title_byte + 1, 7)]), + // 0: no card bytes counted (`Drop` takes them off again). + size: 0, + }); + // As `card_dirty` with the mark set by the old-way fetch. + if let Some(card) = &shadow.card { + card.sent.lock().unwrap().retain(|s| s.2 > mark); + } + // Flight 6's slot: the card's bytes behind its lists, before send 7. + let mut slot = content.clone(); + slot[shader_byte] ^= 0xc3; + let written = shadow.card_merge_relay(0, &slot, 6, &mut Vec::new()); + assert!(written > 0); + drop(shadow); + title + }; + let fixed = land(crate::host::fallback_fetched_mark(true, 7, Some(5))); + assert_eq!(fixed[title_byte], content[title_byte] ^ 0x5a, "the title's byte was lost"); + assert_eq!(fixed[shader_byte], content[shader_byte] ^ 0xc3, "the shader's write did not land"); + // The mark at the fetch's count: the note of send 7 is gone and the + // older card byte is taken for a shader's write. + let before = land(7); + assert_eq!(before[title_byte], content[title_byte]); + } +} + /// 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 { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 9bfcb0a5..02d066f2 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -351,17 +351,31 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let mut granularity = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); + // View memory the guards already hold cannot be write-watched: the + // kernel asking would only fail. Copies of it are flushed many times a + // frame, each time paying that failed call before the guards answer. + let known_view = guarded && known_view(first * PAGE); // SAFETY: the answer buffer holds `count` entries. - let failed = unsafe { - GetWriteWatch( - WRITE_WATCH_FLAG_RESET, - (first * PAGE) as *const _, - (last - first) * PAGE, - j.found.as_mut_ptr().cast(), - &mut count, - &mut granularity, - ) - } != 0; + let failed = known_view + || unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + #[cfg(feature = "diagnostics")] + crate::copystat::add( + if known_view { + crate::copystat::C::WatchKnownView + } else { + crate::copystat::C::WatchFailed + }, + failed as u64, + ); let guarded = if failed { count = 0; if !guarded { @@ -437,6 +451,25 @@ impl Tracked { /// Guarded blocks of view memory. const BLOCK: usize = PAGE; +/// Whether the block holding `start` is view memory the guards already +/// hold (read-only by our hand, or noted absent): asking the kernel's write +/// watch about it can only fail. `VICTORY_VIEW_ASK=1` (or +/// `VICTORY_GUARD_ASK=1`) asks the kernel anyway, as before. +fn known_view(start: usize) -> bool { + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + let ask = *ASK.get_or_init(|| { + ["VICTORY_VIEW_ASK", "VICTORY_GUARD_ASK"] + .iter() + .any(|n| std::env::var_os(n).is_some_and(|v| v == "1")) + }); + if ask { + return false; + } + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) +} + struct Guards { /// Blocks we made read-only. protected: BTreeSet, From f85101b6095e8cf3cecf8f0647cc7f5428daa177 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:20:49 -0500 Subject: [PATCH 04/16] Frame rate, second night: a submit thread of the layer's own, a copy queue for fetches, indirect draw windows made safer, a profiler; all behind switches - VICTORY_ASYNC_SUBMIT=1: submissions are prepared and sent by a thread of the layer, in order, instead of by the title's render thread; the queue's line stays open while its head is prepared. - VICTORY_QUEUE2=1: fetches of what shaders wrote to copies in the card's memory go to a copy queue, with the fix for a piece fetched beside a later flight (fetched again when that flight lands). - Pull request #220 (cheaper indirect draws) is in, its windows off by default; a draw record of 2^23 vertices an instance or more runs empty (its window checker found one list drawing 90 such records). - Fills of upload memory and read-only title buffer copies no longer wait for flights; each is checked against what the flights then wrote, and the first mismatch turns the waiting back on (VICTORY_FILL_WAIT=1). - Up to 512 idle host lists and the texture staging buffers are reused. - VICTORY_MERGE_GAP / VICTORY_MERGE_RUNS (off / 512 by default; the gap form is not exact, see its comment). - VICTORY_PROFILE=1 (diagnostics builds): a sampling profiler inside the layer. - README: what was measured, the history of the device losses with windows, and what is still open (frame rate dips; cause not known). Measured on an RTX 4070 in the first room: about 3.5-4 frames a second before, 6-7 with all the switches, defaults about 4.5-5. Five runs with windows on since the fix, no device loss. This merged tree was built; its whole test suite was not run (the tests around flights, queues, indirect draws and the copy queue were, on the development tree). Co-Authored-By: Claude Fable 5.2 --- README.md | 43 +- crates/victory-gpu/src/draw.rs | 29 +- crates/victory-gpu/src/host.rs | 1242 ++++++++- crates/victory-gpu/src/indirect.rs | 937 ++++++- crates/victory-gpu/src/indirect/bench.rs | 502 ++++ crates/victory-gpu/src/lib.rs | 4 + crates/victory-gpu/src/list.rs | 9 +- crates/victory-gpu/src/profile.rs | 2961 ++++++++++++++++++++++ crates/victory-gpu/src/profile/tests.rs | 1005 ++++++++ crates/victory-gpu/src/queue.rs | 140 +- crates/victory-gpu/src/queue2.rs | 1047 ++++++++ crates/victory-gpu/src/shadow.rs | 46 +- crates/victory-gpu/src/texture.rs | 68 +- 13 files changed, 7868 insertions(+), 165 deletions(-) create mode 100644 crates/victory-gpu/src/indirect/bench.rs create mode 100644 crates/victory-gpu/src/profile.rs create mode 100644 crates/victory-gpu/src/profile/tests.rs create mode 100644 crates/victory-gpu/src/queue2.rs diff --git a/README.md b/README.md index 443c6b11..1f9fdd09 100644 --- a/README.md +++ b/README.md @@ -79,10 +79,45 @@ What did it, on top of the list below: 0 here, but the card got busier, so no gain is claimed yet). The frame is still 250 to 380 ms: the card is the limit now, most of it the per-record clamp before each of some 6,700 indirect draws a frame. -- Tried and NOT in this tree: pull request #220 (cheaper indirect draws) - with `VICTORY_INDIRECT_WINDOW=1` cut the card's time from about 100-150 - to 35-80 ms a frame here, and lost the device twice (once with a page - fault on the card after 160 s). Do not turn windows on with it yet. +- Pull request #220 (cheaper indirect draws) is IN this tree now, its + windows off by default (`VICTORY_INDIRECT_WINDOW=1`). History, so nobody + repeats it: with windows on it lost the device three times here. Its own + checker (`VICTORY_INDIRECT_WINDOW_CHECK=1`) then showed one list drawing + 90 records of 2^24 vertices from a window, where the per-draw path lets + eight through; a record of 2^23 vertices an instance or more now runs + empty. Since that fix: five runs with windows on, no device loss, the + card's time per frame roughly halved. One loss after the fix had the + in-flight fetch (#648) on as well; do not combine the two. The in-flight + fetch itself measured slower here in two runs and stays off. +- Frame rate, second night (an RTX 4070; the first room went from about + 3.5-4 to 6-7 frames a second with ALL of the switches below; the + defaults are unchanged and give about 4.5-5): + - `VICTORY_ASYNC_SUBMIT=1`: submissions are prepared and sent by a + thread of the layer, not by the title's render thread, which a + profile showed inside the submit path for 257 of 292 ms a frame. + - `VICTORY_QUEUE2=1`: fetches of what shaders wrote go to a copy queue + (brought back, with the fix for a piece fetched beside a later + flight); the copy-back thread's wait fell from about 125 to 7 ms a + frame. + - `VICTORY_INDIRECT_WINDOW=1`: see above. + - `VICTORY_TEXTURE_NO_WAIT=1`: a texture refresh no longer waits while + the title remaps memory; the loading phase had 5 readings over a + second where it had 18. + - `VICTORY_MERGE_GAP=64 VICTORY_MERGE_RUNS=4096`: title bytes put in + under flights' shader writes are joined over small gaps (NOT exact: + read the comment at `merge_gap` before using it). + - On by default: fills of upload memory and read-only buffer copies no + longer wait for flights and are checked against what the flights then + wrote (`VICTORY_FILL_WAIT=1` waits as before; no mismatch in any run + so far); up to 512 idle host lists and texture staging buffers are + reused instead of made and freed every frame. + - `VICTORY_PROFILE=1` (diagnostics builds): a sampling profiler inside + the layer; it is how the above was found. + Still open: the frame rate dips (5-second readings of 300-500 ms among + 150-215); in some of them texture uploads are 3-5 times the usual, in + others nothing logged stands out. Not shader compiles (checked: 4-9 + first uses and no waiting in those readings). A per-frame logger is the + next step. - Known and counted, not fixed yet: an indirect compute pass asks for about 77,500 thread groups in x where one dispatch runs 65,535 (the rest is cut off). diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 9ba0c2fb..ca67721e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -155,7 +155,9 @@ const WINDOW_MOST: u64 = 64; /// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at /// most, never past the buffer) into /// the list's scratch buffer in one pass, and the draws that follow read -/// their record there with no pass of ours, until one of these: a compute +/// their record there with no pass of ours and no barrier (the scratch +/// buffer stays readable as arguments until the next clamp), until one of +/// these: a compute /// dispatch, a direct draw, an indirect call with a count buffer or more /// than one record, a draw whose shaders can store to buffers, a record /// outside the window, another host list. @@ -2973,9 +2975,25 @@ impl State { .as_ref() .filter(|w| same(w) && offset >= w.base) .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) - .map(|w| (w.scratch.clone(), offset - w.base)); + .map(|w| (w.scratch.clone(), offset - w.base, w.step)); let (bounded, at) = match hit { - Some(hit) => hit, + Some((scratch, at, step)) => { + // Diagnostics of windows: the record clamped again and + // compared (`crate::indirect::window_check`). + if crate::indirect::window_check() + && crate::indirect::check_hit( + list, + (&args.buffer, offset), + (kind, step), + &scratch, + at, + ) + { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + (scratch, at) + } None => { // A record a short step after the last window's last one // (the same step as that window's, if it had one): the @@ -3039,7 +3057,6 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &bounded); why("prepare failed"); return false; } @@ -3065,7 +3082,9 @@ impl State { if kind == MESH { self.mesh_scissor(list, false); } - crate::indirect::done(list, &bounded); + // The scratch buffer stays readable as arguments: the next draw of + // 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); } else { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 78a43cb8..ecf79d5e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -789,11 +789,18 @@ pub(crate) struct HostList { /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, /// The work its indirect executions may still do (`indirect`): a - /// shader-writable word, zeroed when the list is submitted. + /// shader-writable word, zeroed when the list is submitted, and after + /// it what the clamp notes about mesh records. In memory the CPU maps. budget: OnceLock>, + /// The same words in the card's own memory ([`card_budget`]), which the + /// clamp uses instead when there is one: zeroed in the list before its + /// first clamp, its notes copied to `budget` when the list closes. + card_budget: OnceLock>, /// Device-local scratch buffer for clamped indirect arguments (`indirect`), /// grown to the largest indirect execution recorded on the list. indirect_args: Mutex>, + /// The buffers of `crate::indirect::window_check`, made at its first use. + window_check: OnceLock>, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -1270,10 +1277,15 @@ pub(crate) fn dred_on() -> bool { /// budget buffers, a run late). static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; -/// Since the last frame line: the largest group count in x an indirect -/// compute record asked for, and the records that asked for more than the -/// 65,535 one dispatch runs (cut to that: the groups past it do not run). -static COMPUTE_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +/// Whether a list's indirect-work budget lives in the card's own memory +/// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as +/// before). The clamp charges it with atomics, at least two in a row for +/// every clamp; in mapped memory on a card of its own each of them +/// crosses the bus. +fn card_budget() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0")) +} /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics @@ -1835,8 +1847,14 @@ struct Deferred { /// memory they go to, the bytes of a row, the rows, the title's row /// pitch. backs: Vec<(ID3D12Resource, usize, [usize; 3])>, - /// Whether a step zeroes the indirect-work budget. + /// 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, + /// The indirect scratch buffer (`HostList::indirect_args`, by its + /// interface pointer) that a clamp in this recording left readable as + /// indirect arguments; 0 if none. It stays readable until the next + /// clamp into it ([`HostList::indirect_state`]). + indirect_readable: usize, } impl Deferred { @@ -2143,9 +2161,99 @@ fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(us flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() } +/// Whether pieces fetched on a copy queue beside later flights are fetched +/// again when those flights land (`VICTORY_QUEUE2_REFETCH=0`: not, as +/// before; on by default with `VICTORY_QUEUE2` bit 1). +fn refetch() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE2_REFETCH").is_none_or(|v| v != "0")) +} + +/// With fetches on a copy queue (`crate::queue2`, bit 1): the pieces (copy, +/// piece number) a fetch brought down while later submissions may have been +/// running, each with the number of the last submission started when the +/// fetch had run ([`STARTED`]). +/// +/// Such a fetch stands behind the flights being landed and nothing else, +/// so it runs beside whatever was sent after them. A later flight that +/// writes the piece (a buffer cleared and filled again) may be half way +/// through it: the bytes that come down are neither the earlier flight's +/// nor the later one's, and they go into title memory. If the later flight +/// leaves the piece as the earlier one left it (a still scene does, every +/// frame), its own compare finds the stored hash unchanged and flags +/// nothing: title memory kept the half-written bytes until the piece next +/// changed. On the direct queue a fetch only ever sees whole flights. +/// +/// So a flight that declared such a piece and had started before the fetch +/// had run fetches it at its own landing whatever its compare says +/// ([`fetched_beside`]); that fetch stands behind the flight, and is noted +/// here in turn if still later flights were in the air. Between the two +/// landings title memory may hold the half-written bytes, as it does on +/// the console, where the title reads the memory the card is writing: what +/// the title is promised is the piece as the flight left it once that +/// flight's fence is signalled, and the landing comes before the signal. +static BESIDE: Mutex>> = Mutex::new(None); + +/// Since the last frame-rate line: pieces fetched because an earlier fetch +/// of them ran beside their flight ([`BESIDE`]), and pieces noted there. +static BESIDE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`BESIDE`]: whether the flight numbered `number` (among the submissions +/// started) must fetch a piece that an earlier landing's fetch brought +/// down when submissions up to `started` had been started: it had started +/// by then, so it may have been writing the piece under that fetch. +fn fetched_beside(started: Option, number: u64) -> bool { + started.is_some_and(|started| started >= number) +} + +/// [`BESIDE`], after a landing of flights up to number `landed` whose +/// fetch brought `fetched` down while submissions up to `started` had +/// been started: what is noted of the pieces afterwards, and how many were +/// noted now. A note is done with once every submission it names has +/// landed (each fetched the piece again if it declared it); the pieces +/// just fetched are noted if anything later than the flights landed had +/// started. +fn note_beside(noted: &mut std::collections::HashMap<(usize, u32), u64>, fetched: &[(usize, u32)], landed: u64, started: u64) -> u64 { + noted.retain(|_, upto| *upto > landed); + if started <= landed { + return 0; + } + for piece in fetched { + noted.insert(*piece, started); + } + fetched.len() as u64 +} + #[cfg(test)] mod relay_tests { - use super::{flagged_pieces, landable}; + use super::{fetched_beside, flagged_pieces, landable, note_beside}; + + /// A piece fetched on the copy queue while a later flight was in the + /// air is fetched again by that flight, and by no flight sent after + /// the fetch had run; the note goes when its flights have landed. + #[test] + fn a_piece_fetched_beside_a_later_flight_is_fetched_again_by_it() { + let mut noted = std::collections::HashMap::new(); + let (a, p) = (0x1000usize, 7u32); + // Flight 5 lands; its fetch ran while 6 and 7 had started. + assert_eq!(note_beside(&mut noted, &[(a, p)], 5, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 6)); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 8 was sent after the fetch had run: its compare decides. + assert!(!fetched_beside(noted.get(&(a, p)).copied(), 8)); + // Another piece was never noted. + assert!(!fetched_beside(noted.get(&(a, p + 1)).copied(), 6)); + // Flight 6 lands and fetches it again, with 7 still in the air and + // nothing newer: the note stays for 7. + assert_eq!(note_beside(&mut noted, &[(a, p)], 6, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 7 lands with nothing behind it: nothing is noted any more. + assert_eq!(note_beside(&mut noted, &[(a, p)], 7, 7), 0); + assert!(noted.is_empty()); + // A fetch with nothing later in the air notes nothing. + assert_eq!(note_beside(&mut noted, &[(a, p)], 9, 9), 0); + assert!(noted.is_empty()); + } /// Two flights and what follows each: nothing of the second lands /// before the card has run it, and nothing behind a flight lands @@ -2376,16 +2484,41 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op match step { &Step::Copy(dst, src, len) => { if touches(written, src, src + len) || touches(written, dst, dst + len) { + // A copy that only READS where flights may write is + // not waited for either, and checked like a fill + // (`fill_ahead`): run 210 looked at 197 such waits + // (20,480 bytes out of the 174 MB buffer into a small + // buffer of its own, four a frame, 43 to 60 ms a + // frame) and neither side had other bytes after + // one. A copy INTO such a range still waits. + if !touches(written, dst, dst + len) && fill_ahead::on() { + if count { + fill_ahead::read(src, len); + } + continue; + } if count { LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + fill_check::blocked_copy(written, dst, src, len); } return Some(WHY_READ); } } &Step::Fill(_, src, len) => { if touches(written, src, src + len) { + // Not waited for, and checked when the flights land + // (`fill_ahead`). + if fill_ahead::on() { + if count { + fill_ahead::read(src, len); + } + continue; + } if count { LATE_STATS[16].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + fill_check::blocked(written, src, len); } return Some(WHY_READ); } @@ -2407,6 +2540,367 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op None } +/// Fills of upload memory (a constant buffer a table names, copied into +/// the list's own memory when the list is submitted) that read title memory +/// flights "may write" are no longer waited for; what the flights then +/// write is checked against them, and the first fill that read bytes a +/// flight changed afterwards turns the waiting back on for good. +/// +/// Why: a flight declares every range its shaders can store to, and the +/// title has an unordered view over the whole of its 174 MB buffer, whose +/// copy is in the card's memory. Its per-draw constants lie in the same +/// buffer, at new addresses every frame. So the first such fill of a frame +/// waited until those flights had landed: one wait a frame, 56 to 95 ms of +/// the submitting thread standing still (runs 202 and 206; 145 ms while +/// the world loaded in 208), the largest single wait of the frame. Run 208 +/// looked at every one of them: 44 fills of 480 bytes, and after the wait +/// the bytes were the same 44 times. +/// +/// What it risks, and how it is bounded: a fill that reads bytes a flight +/// in the air is about to change takes the old bytes, and the lists of +/// that one submission draw with them. `wrote` sees it when the flight +/// lands (the bytes going into title memory are compared with the ones +/// there, over every fill that read ahead of them) and from then on fills +/// wait as before. `VICTORY_FILL_WAIT=1`: they wait from the start. +mod fill_ahead { + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + use std::sync::{Mutex, OnceLock}; + + /// Fills are looked up by the 64 KiB of title memory they read. + const PIECE: usize = 1 << 16; + /// A fill is checked against flights that land this many frames after + /// it at most (flights are settled at 256 lists in the air, and by + /// every present that waits). + const KEEP: u64 = 16; + + /// A flight changed bytes a fill had read ahead of it: fills wait. + static WAIT: AtomicBool = AtomicBool::new(false); + /// Since the last frame line: fills that read ahead; landings' writes + /// that touched one's piece. Since the start: fills that read bytes a + /// flight then changed. + static COUNT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + #[derive(Default)] + struct Piece { + /// The frame its old fills were last dropped in. + pruned: u64, + /// From, to, frame, and the number of the last submission started + /// when it read: the flights in the air then have that number or + /// a lower one, and only their writes can be ones it missed. + fills: Vec<(usize, usize, u64, u64)>, + } + + /// The lowest submission number among the flights the landing thread + /// is landing now; 0: not known (a landing by another way), and then + /// every write counts. (Run 211: a read of frame 1381 was taken for + /// missed because shaders wrote the same 80 bytes in frame 1397, in a + /// flight sent sixteen frames after it.) + static LANDING: AtomicU64 = AtomicU64::new(0); + + pub(super) fn landing(first: u64) { + LANDING.store(first, Relaxed); + } + + static READ: Mutex>> = Mutex::new(None); + + pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_WAIT").is_none_or(|v| v != "1")) && !WAIT.load(Relaxed) + } + + /// A fill reads `len` bytes at `src` ahead of flights that may write + /// them. + pub(super) fn read(src: usize, len: usize) { + if len == 0 { + return; + } + COUNT[0].fetch_add(1, Relaxed); + let frame = crate::frame::current(); + let mut read = READ.lock().unwrap_or_else(|e| e.into_inner()); + let map = read.get_or_insert_with(HashMap::new); + for piece in src / PIECE..=(src + len - 1) / PIECE { + let p = map.entry(piece).or_default(); + if p.pruned != frame { + p.pruned = frame; + p.fills.retain(|f| f.2 + KEEP >= frame); + } + p.fills.push((src, src + len, frame, super::STARTED.load(Relaxed))); + } + } + + /// A landing is about to put `new` into title memory at `at`: bytes + /// shaders wrote, merged into the title's. + pub(crate) fn wrote(at: usize, new: &[u8]) { + if new.is_empty() || WAIT.load(Relaxed) { + return; + } + let frame = crate::frame::current(); + let landing = LANDING.load(Relaxed); + let hits: Vec<(usize, usize, u64)> = { + let read = READ.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = read.as_ref() else { return }; + let end = at + new.len(); + (at / PIECE..=(end - 1) / PIECE) + .filter_map(|piece| map.get(&piece)) + .flat_map(|p| p.fills.iter().copied()) + .filter(|f| f.0 < end && f.1 > at && f.2 + KEEP >= frame && (landing == 0 || landing <= f.3)) + .map(|f| (f.0, f.1, f.2)) + .collect() + }; + if hits.is_empty() { + return; + } + COUNT[1].fetch_add(1, Relaxed); + let mut now = Vec::new(); + for (from, to, read_in) in hits { + let (a, b) = (from.max(at), to.min(at + new.len())); + now.clear(); + now.resize(b - a, 0); + // Title memory as it is, which is what the fill read unless the + // title wrote it since; not there: nothing to say. + if !super::read_into(a as *const u8, &mut now) || now[..] == new[a - at..b - at] { + continue; + } + let n = COUNT[2].fetch_add(1, Relaxed) + 1; + let first = now.iter().zip(&new[a - at..b - at]).position(|(x, y)| x != y).unwrap_or(0); + if !WAIT.swap(true, Relaxed) { + tracing::warn!( + "a fill of upload memory read {} bytes at {from:#x} in frame {read_in} ahead of a flight whose shaders changed \ + them (first at {:#x}, landed in frame {frame}): the lists of that submission drew with the bytes from before. \ + Fills wait for flights again from here on, as with VICTORY_FILL_WAIT=1 ({n} such fills)", + to - from, + a + first + ); + } + return; + } + } + + /// With the frame line. + pub(super) fn line(frames: f64) { + let [ahead, looked] = [0, 1].map(|i| COUNT[i].swap(0, Relaxed)); + if ahead == 0 && looked == 0 { + return; + } + let kept = { + let frame = crate::frame::current(); + let mut read = READ.lock().unwrap_or_else(|e| e.into_inner()); + read.as_mut().map_or(0, |map| { + map.retain(|_, p| { + p.fills.retain(|f| f.2 + KEEP >= frame); + !p.fills.is_empty() + }); + map.values().map(|p| p.fills.len()).sum::() + }) + }; + tracing::info!( + "fills of upload memory that read title memory flights may write, not waited for (VICTORY_FILL_WAIT=1 waits): {:.1} per \ + frame; {:.1} landings' writes per frame fell in the same 64 KiB as one and were compared with it; fills that read \ + bytes a flight then changed, since the start: {}{}; {kept} fills kept to check", + ahead as f64 / frames, + looked as f64 / frames, + COUNT[2].load(Relaxed), + if WAIT.load(Relaxed) { " (fills wait again)" } else { "" } + ); + } +} + +pub(crate) use fill_ahead::wrote as shaders_write; + +/// Diagnostics: the fills of upload memory that made a submission wait for +/// flights (`blocked_by`), which one they are, and whether the wait was +/// needed: the bytes the fill reads are kept when it blocks and compared +/// with what it reads once the flights have landed. +/// +/// Runs 202 and 206: one such wait a frame, 56 to 95 ms of the submitting +/// thread standing still, the largest single wait of the frame. The ranges +/// flights "may write" are whole views shaders can store to; if the bytes +/// a fill reads never change under the wait, the wait is for nothing. +#[cfg(feature = "diagnostics")] +mod fill_check { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + + /// The fill waited for now: source, length, its bytes when it blocked. + static PENDING: Mutex)>> = Mutex::new(None); + /// Fills that blocked by (source page, length): how often. + static SEEN: Mutex> = Mutex::new(Vec::new()); + /// Fills checked after their wait; those whose bytes had changed; the + /// bytes that had. + static CHECKED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + /// A fill of `len` bytes at `src` blocks on `written`. + pub(super) fn blocked(written: &[(usize, usize)], src: usize, len: usize) { + let at = written.partition_point(|r| r.1 <= src); + let touched = written.get(at).copied().unwrap_or((0, 0)); + let key = (src & !0xfff, len); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let known = seen.iter().position(|s| (s.0, s.1) == key); + match known { + Some(k) => seen[k].2 += 1, + None if seen.len() < 256 => { + seen.push((key.0, key.1, 1)); + if seen.len() <= 12 { + tracing::info!( + "a fill of upload memory waits for flights: {len} bytes at {src:#x}; the range shaders may write that it touches: {:#x}+{:#x} ({} ranges in the air); frame {}", + touched.0, + touched.1 - touched.0, + written.len(), + crate::frame::current() + ); + } + } + None => {} + } + drop(seen); + let mut bytes = vec![0u8; len.min(1 << 20)]; + if super::read_into(src as *const u8, &mut bytes) { + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((src, len, bytes)); + } + } + + /// The fill of `len` bytes at `src` runs now. + pub(super) fn runs(src: usize, len: usize) { + let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.as_ref().is_some_and(|p| (p.0, p.1) == (src, len)) { + return; + } + let Some((_, _, before)) = pending.take() else { return }; + drop(pending); + let mut now = vec![0u8; before.len()]; + if !super::read_into(src as *const u8, &mut now) { + return; + } + let differ = before.iter().zip(&now).filter(|(a, b)| a != b).count() as u64; + let n = CHECKED[0].fetch_add(1, Relaxed) + 1; + if differ > 0 { + let bad = CHECKED[1].fetch_add(1, Relaxed) + 1; + CHECKED[2].fetch_add(differ, Relaxed); + if bad <= 12 { + let first = before.iter().zip(&now).position(|(a, b)| a != b).unwrap_or(0); + tracing::info!( + "a fill of upload memory that waited for flights read other bytes after the wait: {differ} of {len} bytes at {src:#x} changed, the first at +{first:#x} (check {n}, frame {})", + crate::frame::current() + ); + } + } + } + + /// The title buffer copy waited for now: destination, source, length, + /// the bytes of both when it blocked. + static PENDING_COPY: Mutex, Vec)>> = Mutex::new(None); + /// Copies checked after their wait; those whose source had changed; + /// those whose destination had. + static COPIES: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + /// Copies that blocked by (source page, destination page, length). + static SEEN_COPIES: Mutex> = Mutex::new(Vec::new()); + + /// A title buffer copy of `len` bytes from `src` to `dst` blocks on + /// `written`. + pub(super) fn blocked_copy(written: &[(usize, usize)], dst: usize, src: usize, len: usize) { + let by_src = super::touches(written, src, src + len); + let by_dst = super::touches(written, dst, dst + len); + let key = (src & !0xfff, dst & !0xfff, len); + let mut seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let known = seen.iter().position(|s| (s.0, s.1, s.2) == key); + match known { + Some(k) => seen[k].3 += 1, + None if seen.len() < 256 => { + seen.push((key.0, key.1, key.2, 1)); + if seen.len() <= 16 { + let range = |at: usize| { + let k = written.partition_point(|r| r.1 <= at); + written.get(k).copied().unwrap_or((0, 0)) + }; + let (s, d) = (range(src), range(dst)); + tracing::info!( + "a title buffer copy waits for flights: {len} bytes from {src:#x} to {dst:#x}; source in a range shaders may write: {by_src} ({:#x}+{:#x}); destination: {by_dst} ({:#x}+{:#x}); {} ranges in the air; frame {}", + s.0, + s.1 - s.0, + d.0, + d.1 - d.0, + written.len(), + crate::frame::current() + ); + } + } + None => {} + } + drop(seen); + let n = len.min(1 << 20); + let (mut a, mut b) = (vec![0u8; n], vec![0u8; n]); + if super::read_into(src as *const u8, &mut a) && super::read_into(dst as *const u8, &mut b) { + *PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()) = Some((dst, src, len, a, b)); + } + } + + /// The title buffer copy runs now. + pub(super) fn copy_runs(dst: usize, src: usize, len: usize) { + let mut pending = PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.as_ref().is_some_and(|p| (p.0, p.1, p.2) == (dst, src, len)) { + return; + } + let Some((_, _, _, src_before, dst_before)) = pending.take() else { return }; + drop(pending); + let (mut a, mut b) = (vec![0u8; src_before.len()], vec![0u8; dst_before.len()]); + if !super::read_into(src as *const u8, &mut a) || !super::read_into(dst as *const u8, &mut b) { + return; + } + let n = COPIES[0].fetch_add(1, Relaxed) + 1; + let (src_changed, dst_changed) = (a != src_before, b != dst_before); + if src_changed { + COPIES[1].fetch_add(1, Relaxed); + } + if dst_changed { + COPIES[2].fetch_add(1, Relaxed); + } + if (src_changed || dst_changed) && COPIES[1].load(Relaxed) + COPIES[2].load(Relaxed) <= 16 { + let differ = |x: &[u8], y: &[u8]| x.iter().zip(y).filter(|(p, q)| p != q).count(); + tracing::info!( + "a title buffer copy that waited for flights found other bytes after the wait: {len} bytes from {src:#x} to {dst:#x}; {} source bytes changed, {} destination bytes changed (check {n}, frame {})", + differ(&a, &src_before), + differ(&b, &dst_before), + crate::frame::current() + ); + } + } + + /// With the frame line. + pub(super) fn line() { + let copies = COPIES[0].load(Relaxed); + if copies > 0 { + let seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let mut most: Vec<_> = seen.clone(); + most.sort_unstable_by_key(|s| std::cmp::Reverse(s.3)); + let most: Vec = + most.iter().take(6).map(|s| format!("{:#x}->{:#x}+{:#x} {}x", s.0, s.1, s.2, s.3)).collect(); + tracing::info!( + "title buffer copies that waited for flights, since the start: {copies} checked after their wait; the source had other bytes after it {} times, the destination {} times; {} distinct copies, the most frequent: {}", + COPIES[1].load(Relaxed), + COPIES[2].load(Relaxed), + seen.len(), + most.join(", ") + ); + } + let n = CHECKED[0].load(Relaxed); + if n == 0 { + return; + } + let seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let mut most: Vec<_> = seen.clone(); + most.sort_unstable_by_key(|s| std::cmp::Reverse(s.2)); + let most: Vec = most.iter().take(6).map(|s| format!("{:#x}+{:#x} {}x", s.0, s.1, s.2)).collect(); + tracing::info!( + "fills of upload memory that waited for flights, since the start: {n} checked after their wait, {} of them read other bytes than before it ({} bytes in all); {} distinct fills (page, length), the most frequent: {}", + CHECKED[1].load(Relaxed), + CHECKED[2].load(Relaxed), + seen.len(), + most.join(", ") + ); + } +} + /// With flights in the air, after the submission's write-watch asking: /// whether `runs` refresh a range of a host copy that a flight's shaders /// may write and that the title wrote since it was last copied. The @@ -2434,7 +2928,13 @@ fn stale_under_flights(runs: &[&HostList]) -> bool { // settle is still due where that could not be done. At most this // many changed runs go up to copies in the card's memory, each a // copy of its own there. - let mut runs_left = 512; + // (`VICTORY_MERGE_RUNS`: the cap. Run 218 had 500 to 5,400 changed + // runs a frame of a few bytes each, and the cap of 512 settled the + // flights twice a frame, 50 ms of the submitting thread.) + static RUNS: OnceLock = OnceLock::new(); + let mut runs_left = *RUNS.get_or_init(|| { + std::env::var("VICTORY_MERGE_RUNS").ok().and_then(|v| v.trim().parse::().ok()).map_or(512, |n| n.clamp(1, 1 << 16)) + }); return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); } spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) @@ -2771,6 +3271,9 @@ fn late_line(frames: f64) { if !late() { return; } + #[cfg(feature = "diagnostics")] + fill_check::line(); + fill_ahead::line(frames); let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); tracing::info!( "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ @@ -2818,11 +3321,15 @@ fn late_line(frames: f64) { } if relay() { let r: Vec = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let [again, noted] = [0, 1].map(|i| BESIDE_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); tracing::info!( - "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \ + "the relay per frame (VICTORY_RELAY={}): {:.1} flights landed in {:.1} landings by the thread that copies back, \ beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ - \"settles\" above are waits of other threads for it)", + \"settles\" above are waits of other threads for it); pieces fetched on the copy queue beside later \ + submissions: {noted:.1}, pieces those fetched again at their own landing whatever the compare said: {again:.1} \ + (VICTORY_QUEUE2_REFETCH)", + if relay_exact() { 2 } else { 1 }, r[1], r[0], r[2] / 1000.0, @@ -3216,7 +3723,9 @@ impl Host { prelude, pipelines: Mutex::default(), budget: OnceLock::new(), + card_budget: OnceLock::new(), indirect_args: Mutex::default(), + window_check: OnceLock::new(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), @@ -3423,7 +3932,20 @@ impl Host { /// `flown`: the submission is sent ahead with [`relay`]. Its compare /// then stores the hashes it makes (see [`flagged_pieces`] and /// `relay`). - fn card_before(&self, runs: &[&HostList], flown: bool) -> Option { + /// + /// `sent`: the last value signalled on the host's fence; the caller + /// signals the next one behind this submission's lists. + /// + /// With `VICTORY_QUEUE2` bit 2 (`crate::queue2`; off by default) the + /// changed bytes cross from the PC's memory to the card's on a copy + /// queue, on the card's copy engine, while the direct queue still runs + /// what was sent before: they go into a landing buffer in the card's + /// memory that nothing else uses. The direct queue is told to wait for + /// that copy and then moves the bytes from the landing buffer into the + /// copies, inside the card's memory, in the same place of its order as + /// before. So the copies change exactly when they did on one queue; what + /// leaves the direct queue is the crossing from the PC's memory. + fn card_before(&self, runs: &[&HostList], flown: bool, sent: u64) -> Option { use std::sync::Arc; if !crate::shadow::cards() { return None; @@ -3458,7 +3980,19 @@ impl Host { None => 0, }; let mut dirty = crate::shadow::card_dirty(sent_as); + // With fetches on a copy queue (`crate::queue2`, bit 1 of + // `VICTORY_QUEUE2`): the send's number is signalled on the direct + // queue behind the send, so that a fetch knows which sends the card + // has finished (`Second::order_done`). + let numbered = || { + if sent_as != 0 + && let Some(second) = crate::queue2::second().filter(|s| s.fetches()) + { + second.sent_up(&self.queue, sent_as); + } + }; if declared.is_empty() && dirty.is_empty() { + numbered(); return None; } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); @@ -3479,6 +4013,53 @@ impl Host { } } let mut used: Vec<(bool, Prelude)> = Vec::new(); + // The changed bytes through the copy queue (`VICTORY_QUEUE2` bit + // 2): the landing buffer they are in, in the order of `dirty`'s + // ranges, once the direct queue has waited. `None`: straight from + // the PC's memory on the direct queue, as before. + let mut landed: Option = None; + if let Some(second) = crate::queue2::second().filter(|s| s.uploads()) { + let bytes: u64 = dirty + .iter() + .filter(|(shadow, _)| shadow.carded()) + .flat_map(|(_, ranges)| ranges.iter().map(|&(a, b)| (b - a) as u64)) + .sum(); + // SAFETY: a plain query. + let completed = unsafe { self.fence.GetCompletedValue() }; + // Held until the card has passed this submission's signal: the + // direct queue's copy out of it runs ahead of that. + if bytes > 0 + && let Some(landing) = second.landing(bytes, completed, sent + 1) + { + // SAFETY: an open copy list of the lane's; live buffers, + // and the ranges lie in them; the host's queue. + let sent_up = unsafe { + (|| -> windows::core::Result<()> { + let copy = second.up.list()?; + let mut at = 0u64; + for (shadow, ranges) in &dirty { + let Some((staging, _, _)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + copy.1.CopyBufferRegion(&landing, at, staging, a as u64, (b - a) as u64); + at += (b - a) as u64; + } + } + let job = second.up.send(copy, &[], bytes)?; + // Nothing sent to the direct queue from here on + // runs before the bytes have landed. + second.hold(&self.queue, job) + })() + }; + if let Err(e) = sent_up { + fail(format_args!( + "host copies in the card's memory could not be brought up to date through the copy queue ({e}, VICTORY_QUEUE2)" + )); + } + landed = Some(landing); + } + } 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")); @@ -3491,12 +4072,18 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + // Where the next range lies in the landing buffer. + let mut at = 0u64; for (shadow, ranges) in &dirty { let Some((staging, before, size)) = shadow.card_sides() else { continue; }; for &(a, b) in ranges { - list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); + match &landed { + Some(landing) => list.CopyBufferRegion(&shadow.buffer, a as u64, landing, at, (b - a) as u64), + None => list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64), + } + at += (b - a) as u64; crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); } crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed); @@ -3546,6 +4133,7 @@ impl Host { } used.push((false, sync)); } + numbered(); drop(order); let mut plan = CardPlan { ranges: Vec::new(), @@ -3734,14 +4322,40 @@ impl Host { /// With [`inflight_fetch`] the pieces are first looked for where the /// flights' own compare lists put them ([`Host::relay_card_inflight`]); /// only a landing that cannot take them from there fetches, as here. - fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + /// `behind`: the value signalled on the host's fence behind the last of + /// the flights. With `VICTORY_QUEUE2` bit 1 (`crate::queue2`) the fetch + /// goes to a copy queue, behind that value and nothing else: it does + /// not stand behind what the submitting thread sent meanwhile (run + /// 118: 114-157 ms a frame of this thread's time). It then reads the + /// card's side while later flights may be writing it: a byte is the + /// old one or the new one, and the flight that writes it has a compare + /// and a landing of its own behind it. + /// + /// `plans` come with their flights' numbers and `landed` is the number + /// of the last flight being landed: a piece an earlier fetch on the + /// copy queue brought down beside one of these flights is fetched + /// whatever the compare says ([`BESIDE`]). + fn relay_card_back(&self, plans: &[(u64, &CardPlan)], fetch: &mut Option, behind: u64, landed: u64) { if inflight_fetch() { - let landed = self.relay_card_inflight(plans); - inflight_tickets_landed(plans); - if landed { + let only: Vec<&CardPlan> = plans.iter().map(|p| p.1).collect(); + let taken = self.relay_card_inflight(&only); + inflight_tickets_landed(&only); + if taken { return; } } + let lane = crate::queue2::second().filter(|s| s.fetches()); + // The pieces fetched beside flights that had started, as noted by + // earlier landings: looked at for these plans, renewed below. + let beside = lane.is_some() && refetch(); + let noted: std::collections::HashMap<(usize, u32), u64> = if beside { + BESIDE.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default() + } else { + Default::default() + }; + let mut again = 0u64; + // Every piece fetched now: (copy, piece number). + let mut numbers: Vec<(usize, u32)> = Vec::new(); 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)) @@ -3754,8 +4368,8 @@ impl Host { // before these are done with (`card_done`). let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; let mut seen = std::collections::HashSet::new(); - for plan in plans { - let flags: Vec<(usize, u32, bool)> = plan + for &(number, plan) in plans { + let mut flags: Vec<(usize, u32, bool)> = plan .ranges .iter() .flat_map(|r| { @@ -3765,7 +4379,16 @@ impl Host { }) }) .collect(); + // A piece an earlier fetch brought down while this flight + // may have been writing it: fetched, flagged or not. + for flag in flags.iter_mut().filter(|f| !f.2) { + if fetched_beside(noted.get(&(flag.0, flag.1)).copied(), number) { + flag.2 = true; + again += 1; + } + } let fetched = flagged_pieces(&flags); + numbers.extend(fetched.iter().copied()); for r in &plan.ranges { let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; for p in 0..r.span.pieces { @@ -3782,18 +4405,28 @@ impl Host { } } } + BESIDE_STATS[0].fetch_add(again, Ordering::Relaxed); if pieces.is_empty() { if inflight_fetch() { // The next merge may be of a flight in the air now, with // bytes from when it ran: only sends up to these plans' are // older than it. - if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + if let Some(last) = plans.iter().map(|p| p.1.sent_as).max() { crate::shadow::relay_fetched(last); } return; } - // Nothing to fetch: every send so far is older than the next fetch. - crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + if beside { + // Notes whose flights have all landed are done with. + let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); + note_beside(all.get_or_insert_with(Default::default), &[], landed, landed); + } + // Nothing to fetch: every send so far is older than the next + // fetch (on a copy queue: every send the card has finished). + crate::shadow::relay_fetched(match lane { + Some(second) => second.order_done(), + None => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + }); return; } if inflight_fetch() { @@ -3820,6 +4453,32 @@ impl Host { // event are this thread's. let ran = unsafe { (|| -> windows::core::Result { + if let Some(second) = lane { + // The sends of title bytes the card has finished are in + // what comes down. A later one may be too, if the card + // runs it before this fetch: the merge leaves its bytes + // out as a send that came after, and they are the + // title's either way. + let after = second.order_done(); + let copy = second.down.list()?; + for (shadow, lo, hi, at) in &pieces { + copy.1.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + } + let job = second.down.send(copy, &[(&self.fence, behind)], total)?; + second.down.wait(job, event)?; + if beside { + // Whatever had started by now may have been + // writing these pieces while they came down + // (counted before a submission's lists go to the + // queue, `Host::submit`: nothing later ran yet). + let started = STARTED.load(Ordering::Acquire); + let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); + let noted = note_beside(all.get_or_insert_with(Default::default), &numbers, landed, started); + BESIDE_STATS[1].fetch_add(noted, Ordering::Relaxed); + } + second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + return Ok(after); + } allocator.Reset()?; list.Reset(&allocator, None)?; for (shadow, lo, hi, at) in &pieces { @@ -3878,7 +4537,7 @@ impl Host { // Sends up to `after` are of no use to any later merge; with the // fetch inside flights only those up to these plans' are // (`fallback_fetched_mark`). - let landed = plans.iter().map(|p| p.sent_as).max(); + let landed = plans.iter().map(|p| p.1.sent_as).max(); crate::shadow::relay_fetched(fallback_fetched_mark(inflight_fetch(), after, landed)); } @@ -4062,8 +4721,11 @@ impl Host { last_notes(&runs) )); } - let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect(); - self.relay_card_back(&plans, fetch); + fill_ahead::landing(flights.iter().map(|f| f.number).min().unwrap_or(0)); + let plans: Vec<(u64, &CardPlan)> = flights.iter().filter_map(|f| f.card.as_ref().map(|card| (f.number, card))).collect(); + let behind = flights.iter().map(|f| f.fence).max().unwrap_or(0); + let landed = flights.iter().map(|f| f.number).max().unwrap_or(0); + self.relay_card_back(&plans, fetch, behind, landed); let mut back: Vec = Vec::new(); for flight in &flights { for (shadow, ranges) in &flight.back { @@ -4116,6 +4778,7 @@ impl Host { bury(last); } self.log_messages(); + fill_ahead::landing(0); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); { let mut line = line(); @@ -4206,6 +4869,24 @@ impl Host { // fence and event are ours, under the submission lock. let ran = unsafe { (|| -> windows::core::Result<()> { + // With `VICTORY_QUEUE2` bit 1 the fetch goes to the copy + // queue here too, behind everything sent to the direct + // queue. Nothing is gained (the card has run it all + // when this is reached); the path is the same one the + // relay uses, in the plainest run there is. + if let Some(second) = crate::queue2::second().filter(|s| s.fetches()) { + let copy = second.down.list()?; + for &(i, lo, hi, at) in &pieces { + copy.1.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + let job = second.down.send(copy, &[(&self.fence, *submitted)], total)?; + let was_working = working(false); + second.down.wait(job, self.event)?; + stood(waiting); + working(was_working); + second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + return Ok(()); + } allocator.Reset()?; list.Reset(allocator, None)?; for &(i, lo, hi, at) in &pieces { @@ -4289,6 +4970,9 @@ impl Host { /// Runs closed lists and waits for them, and with [`late`] for /// everything sent to the card before them, which is settled first. pub(crate) fn execute(&self, runs: &[&HostList]) { + // Behind what the queues were given before it and have not run + // yet (`crate::queue::behind`). + crate::queue::before_sync(); let _ = self.submit(runs, false); } @@ -4543,6 +5227,8 @@ impl Host { let called = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::submission_begins(); + #[cfg(feature = "diagnostics")] + crate::profile::seen(crate::profile::Seen::Submit); // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); @@ -4663,7 +5349,7 @@ impl Host { self.settle(&mut submitted, WHY_MOST); settled += settling.elapsed(); } - let card = self.card_before(runs, flown); + let card = self.card_before(runs, flown, *submitted); if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { lists.push(Some(check)); } @@ -5095,6 +5781,11 @@ impl HostList { pub(crate) fn close(&self) { self.twins_to_depth(); + let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some((scratch, _)) = scratch { + self.indirect_common(&scratch); + } + self.card_budget_out(); #[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); @@ -5678,6 +6369,7 @@ impl HostList { Some((b, d as usize)) }) .as_ref()?; + let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref(); let mut deferred = self.deferred(); if !deferred.budget_zeroed { deferred.budget_zeroed = true; @@ -5685,24 +6377,95 @@ impl HostList { // SAFETY: the list's own mapped words, written before it runs. // The words after the budget hold what the clamp noted about the // list's last run (mesh dispatches: the largest group count - // asked for, the groups asked in all): taken, then zeroed. + // asked for, the groups asked in all; with the card's copy, as + // the list's end copied them here): taken, then zeroed. deferred.copies.push(Step::Host(Box::new(move || unsafe { let words = at as *mut u32; let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); - // And of its indirect compute records: the largest x asked - // for, and how many asked for more than a dispatch runs. - let (widest, cut) = (words.add(3).read_volatile(), words.add(4).read_volatile()); - COMPUTE_GROUPS[0].fetch_max(u64::from(widest), Ordering::Relaxed); - COMPUTE_GROUPS[1].fetch_add(u64::from(cut), Ordering::Relaxed); - for k in 0..5 { + for k in 0..3 { words.add(k).write_volatile(0); } }))); + drop(deferred); + if let Some(card) = card { + self.zero_card_budget(card); + } } // SAFETY: a live buffer. - Some(unsafe { buffer.GetGPUVirtualAddress() }) + Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() }) + } + + /// The budget's words in the card's own memory ([`card_budget`]), if + /// the list can zero them itself (`WriteBufferImmediate`). + fn make_card_budget(&self) -> Option { + if !card_budget() { + return None; + } + self.list.cast::().ok()?; + let buffer = host()?.uav_buffer(256)?; + name(&buffer, || "indirect budget".to_owned()); + Some(buffer) + } + + /// Records, before the list's first clamp, the zeroing of the card's + /// copy of the budget: common, written as a copy, then left for + /// unordered access until the list closes ([`HostList::card_budget_out`]). + fn zero_card_budget(&self, card: &ID3D12Resource) { + let Ok(list2) = self.list.cast::() else { + return; + }; + // SAFETY: a live buffer. + let at = unsafe { card.GetGPUVirtualAddress() }; + let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: at + offset, + Value: 0, + }); + // SAFETY: an open list; the buffer is the list's own and in the + // common state at the start of every recording. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + } + + /// Before the list closes, if this recording charged the card's copy + /// of the budget: its notes on mesh records go to the mapped words + /// (read at the next submission), and it goes back to common. + fn card_budget_out(&self) { + if !self.deferred().budget_zeroed { + return; + } + let (Some(Some(card)), Some(Some((mapped, _)))) = + (self.card_budget.get(), self.budget.get()) + else { + return; + }; + // SAFETY: an open list; both buffers are the list's own. The + // mapped one is promoted from common to the copy destination. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + self.list.CopyBufferRegion(mapped, 4, card, 4, 8); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } } /// A device-local unordered-access buffer of at least `size` bytes for @@ -5727,11 +6490,62 @@ impl HostList { let old = slot.replace((buffer.clone(), alloc)); drop(slot); if let Some((old_buf, _)) = old { + // It ends the list common, as every scratch buffer does. + self.indirect_common(&old_buf); self.keep(&old_buf); } Some(buffer) } + /// Moves `scratch` back to the common state if a clamp left it readable + /// as indirect arguments ([`HostList::indirect_readable`]): where the + /// list's first clamp expects it. Done before the list closes and before + /// a bigger scratch buffer replaces it: one barrier per list (where + /// there was one per indirect execution), and the list ends as it + /// begins however it is submitted. + fn indirect_common(&self, scratch: &ID3D12Resource) { + { + let mut deferred = self.deferred(); + if deferred.indirect_readable != scratch.as_raw() as usize { + return; + } + deferred.indirect_readable = 0; + } + let barrier = transition( + scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + ); + // SAFETY: an open list and a live buffer this recording left in + // `INDIRECT_ARGUMENT`. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + + /// The state the list's indirect scratch buffer `scratch` is in at this + /// point of the recording: indirect arguments if a clamp in this + /// recording left it so ([`HostList::indirect_readable`]), otherwise + /// common: the state a buffer is made in, and the one a recording + /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]). + pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES { + if self.deferred().indirect_readable == scratch.as_raw() as usize { + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT + } else { + D3D12_RESOURCE_STATE_COMMON + } + } + + /// A clamp recorded in this list left `scratch` readable as indirect + /// arguments. It stays so for every execution that reads it, until the + /// next clamp moves it back to unordered access. + pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) { + self.deferred().indirect_readable = scratch.as_raw() as usize; + } + + /// The list's buffers for `crate::indirect::window_check`. + pub(crate) fn window_check(&self) -> Option<&crate::indirect::WindowCheck> { + self.window_check.get_or_init(crate::indirect::WindowCheck::new).as_ref() + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { @@ -5779,6 +6593,8 @@ impl HostList { add(C::CopyBytes, len as u64); } batch.title_written(); + #[cfg(feature = "diagnostics")] + fill_check::copy_runs(dst, src, len); copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); @@ -5789,6 +6605,7 @@ impl HostList { { add(C::Copies, 1); add(C::CopyBytes, len as u64); + fill_check::runs(src, len); } copy_mapped(dst as *mut u8, src as *const u8, len, false); len @@ -6379,11 +7196,10 @@ impl Meter { tracing::info!( "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" ); - let compute_widest = COMPUTE_GROUPS[0].swap(0, Ordering::Relaxed); - let compute_cut = COMPUTE_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; - tracing::info!( - "indirect compute dispatches: the largest group count in x asked for {compute_widest} (run: at most 65535), {compute_cut:.1} records per frame asked for more and were cut to that" - ); + // (Run 200 counted indirect compute records asking for 77,000 to + // 98,000 groups in x, 0.2 to 0.8 a frame, cut to the 65,535 one + // dispatch runs; the counter went when the clamp's budget moved to + // the card's memory.) { let [texture_us, slots] = [0, 1].map(|i| crate::draw::HEAP_PASS_PARTS[i].swap(0, Ordering::Relaxed)); tracing::info!( @@ -6396,6 +7212,7 @@ impl Meter { crate::descriptor::sync_line(frames); late_line(frames); card_clock_line(frames, ms); + crate::queue2::line(frames); crate::shadow::back_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); @@ -7320,3 +8137,352 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert_eq!(ram_idle_ms(None), 10_000); } } + +/// The host's own paths for a copy in the card's memory, end to end, on +/// the software adapter only: the title's bytes go up, a shader reads them +/// and writes, and what it wrote comes back into title memory. Run it with +/// the switches under test in the environment (they are read once per +/// process); it does nothing unless the host device is the software +/// adapter (`VICTORY_D3D12_WARP=1` in a diagnostics build) and the copy is +/// in the card's memory (`VICTORY_CARD_BUFFERS_MIN_MB=1`): +/// +/// `VICTORY_D3D12_WARP=1 VICTORY_CARD_BUFFERS_MIN_MB=1 [VICTORY_QUEUE2=n] +/// [VICTORY_RELAY=2 | VICTORY_LATE_WAIT=3] cargo test -p victory-gpu +/// --features diagnostics queue2_tests` +/// +/// The same title memory must come out whatever the switches: through the +/// direct queue alone, and through the copy queues. +#[cfg(test)] +mod queue2_tests { + use super::*; + + /// `memory[to] = memory[from] + add`, after `spin` steps. + const ADD: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint from; uint add; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = 0u; + [loop] + for (uint i = 0u; i < spin; i++) { + h = (h ^ memory.Load(from)) * 0x01000193u; + } + memory.Store(to, memory.Load(from) + add + (h & 0u)); +} +"#; + + #[test] + fn warp_title_bytes_go_up_and_shader_writes_come_back_whatever_the_queues() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + const ROUNDS: usize = 12; + // "Title memory": write-watched, as the title's is. + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x51_5151, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = 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() + }) + .expect("a pipeline"); + (root, pso) + }; + // Round k: the title writes a dword in piece 1+k; a submission's + // shader adds k to it and stores the sum in piece 30+k, a range + // declared as shader-written. Nothing is waited for between the + // rounds where submissions are sent ahead. + let from = |k: usize| (1 + k) * PIECE + 4 * k + 64; + let to = |k: usize| (30 + k) * PIECE + 8 * k + 128; + let titles = |k: usize| 0x0100_0000 + 0x1000 * k as u32 + 7; + let mut lists = Vec::new(); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + unsafe { dword(from(k)).write_volatile(titles(k)) }; + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + (30 + k) * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [to(k) as u32, from(k) as u32, k as u32, 30_000]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + if late() { + host.execute_own(&list); + } else { + host.execute(&[&list]); + } + lists.push(list); + } + settle_now(WHY_SYNC); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + let (sum, kept) = unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; + assert_eq!(kept, titles(k), "round {k}: the title's own dword changed"); + assert_eq!( + sum, + titles(k) + k as u32, + "round {k}: the shader read {:#x} where the title had written {:#x}, or its write did not come back", + sum.wrapping_sub(k as u32), + titles(k) + ); + } + // Nothing else moved. + let touched: std::collections::HashSet = (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); + for i in (0..LEN / 4).filter(|i| !touched.contains(&(i * 4))) { + // SAFETY: inside the allocation. + let got = unsafe { dword(i * 4).read_volatile() }; + assert_eq!(got, 0x5A00_0000 | i as u32, "dword {i} of title memory changed"); + } + // The queues the switches name did the work. + if let Some(second) = crate::queue2::second() { + let (down, up) = (second.down.stats.jobs.load(Ordering::Relaxed), second.up.stats.jobs.load(Ordering::Relaxed)); + // (Sends that found no landing buffer went the old way.) + let no_room = second.landing[1].load(Ordering::Relaxed); + eprintln!( + "queue2_tests: VICTORY_QUEUE2={} late {} relay {}: {down} fetches and {up} sends through the copy queues ({no_room} more found no landing buffer), the direct queue told to wait {} times", + crate::queue2::bits(), + late(), + relay(), + second.held[0].load(Ordering::Relaxed) + ); + assert_eq!(down > 0, second.fetches(), "fetches through the copy queue"); + assert_eq!(up + no_room > 0, second.uploads(), "sends through the copy queue"); + assert_eq!(up, second.held[0].load(Ordering::Relaxed), "the direct queue waits for every send"); + } else { + eprintln!("queue2_tests: the direct queue alone (late {}, relay {})", late(), relay()); + } + drop(lists); + } + + /// `memory[to] = first` at once; then `spin` steps, each a store to + /// `memory[to + 4]`; then `memory[to + 4] = 0` and `memory[to] = last`. + /// Whatever `spin` is, the bytes it leaves are the same. + const TWICE: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint first; uint last; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + memory.Store(to, first); + [loop] + for (uint i = 0u; i < spin; i++) { + memory.Store(to + 4u, i); + } + memory.Store(to + 4u, 0u); + memory.Store(to, last); +} +"#; + + /// The hole a fetch on the copy queue had (`VICTORY_QUEUE2` bit 1 with + /// the relay): flight A writes a piece; flight B, sent behind it, + /// writes the same piece through a half-way value and leaves it as A + /// left it. A is landed while B is half way: the fetch, beside B on + /// the copy queue, brings B's half-way bytes into title memory. B's + /// compare finds the piece as A's compare left it and flags nothing, + /// so B's landing fetched nothing and title memory kept the half-way + /// bytes. With the fix B's landing fetches the piece all the same + /// (`BESIDE`). + /// + /// `VICTORY_D3D12_WARP=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_QUEUE2=1 + /// VICTORY_RELAY=1 cargo test -p victory-gpu --features diagnostics + /// fetched_again -- --nocapture` (alone: it lands its two flights + /// itself; `VICTORY_QUEUE2_REFETCH=0` shows the fault). + #[test] + fn warp_a_piece_fetched_while_a_later_flight_writes_it_is_fetched_again() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + return; + } + if !relay() || !crate::queue2::second().is_some_and(|s| s.fetches()) { + eprintln!("queue2_tests: skipped, fetches do not go to a copy queue beside the relay (VICTORY_RELAY=1 VICTORY_QUEUE2=1)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x52_5252, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(TWICE, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = 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() + }) + .expect("a pipeline"); + (root, pso) + }; + // A list whose shader writes the dword at 256 of `piece`, declared. + let record = |piece: usize, first: u32, last: u32, spin: u32| { + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + piece * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [(piece * PIECE + 256) as u32, first, last, spin]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + list + }; + // SAFETY: a plain query. + let completed = || unsafe { host.fence.GetCompletedValue() }; + let wait_for = |value: u64| { + while completed() < value { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + // How many steps keep the card busy for some seconds: timed on + // another piece, waited for. + const TRIAL: u32 = 1 << 20; + let trial = record(40, 1, 2, TRIAL); + let timing = std::time::Instant::now(); + host.execute(&[&trial]); + let took = timing.elapsed().as_secs_f64().max(1e-4); + let spin = (f64::from(TRIAL) * 3.0 / took).clamp(f64::from(TRIAL), 2.0e9) as u32; + // SAFETY: inside the allocation. + assert_eq!(unsafe { dword(40 * PIECE + 256).read_volatile() }, 2, "the trial's write did not come back"); + const AT: usize = 20 * PIECE + 256; + const HALF_WAY: u32 = 0xDEAD_0001; + const LEFT: u32 = 0x600D_0002; + // Flight A, and the card has run it. + let a = record(20, HALF_WAY, LEFT, 16); + let (submitted, mut sent_a) = host.submit(&[&a], true).expect("flight A sent ahead"); + let fence_a = *submitted; + drop(submitted); + wait_for(fence_a); + // Flight B: the same piece, through the half-way value, for seconds. + let b = record(20, HALF_WAY, LEFT, spin); + let (submitted, mut sent_b) = host.submit(&[&b], true).expect("flight B sent ahead"); + let fence_b = *submitted; + drop(submitted); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!( + completed() < fence_b, + "flight B had run after 0.3 s ({spin} steps; the trial's {TRIAL} took {took:.3} s): nothing to show" + ); + // A lands, as `Host::relay_land` lands it, while B is half way. + let mut fetch = None; + { + let plan = sent_a.card.as_ref().expect("flight A has a plan for the card's copies"); + host.relay_card_back(&[(sent_a.number, plan)], &mut fetch, fence_a, sent_a.number); + } + for (copy, ranges) in &sent_a.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let seen = unsafe { dword(AT).read_volatile() }; + let b_ran = completed() >= fence_b; + eprintln!( + "queue2_tests: after A's landing title memory holds {seen:#x} (half way {HALF_WAY:#x}, left {LEFT:#x}); B had run: {b_ran}; {spin} steps" + ); + assert_eq!( + seen, HALF_WAY, + "the fetch for A did not come down beside B (it waited for B, or B had not begun): this machine cannot show the fault" + ); + // B has run; it left the piece as A left it, so its compare flags + // nothing. Its landing must bring the piece down all the same. + wait_for(fence_b); + { + let plan = sent_b.card.as_ref().expect("flight B has a plan for the card's copies"); + host.relay_card_back(&[(sent_b.number, plan)], &mut fetch, fence_b, sent_b.number); + } + for (copy, ranges) in &sent_b.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let (left, beside) = unsafe { (dword(AT).read_volatile(), dword(AT + 4).read_volatile()) }; + assert_eq!( + left, LEFT, + "title memory kept flight B's half-way bytes: B's compare found the piece as A left it and B's landing fetched nothing" + ); + assert_eq!(beside, 0, "the dword beside it holds a half-way count"); + for sent in [&mut sent_a, &mut sent_b] { + if let Some(plan) = sent.card.take() { + host.card_done(plan); + } + } + drop((a, b, trial)); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 3005031c..82449abc 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -8,6 +8,15 @@ //! shader with its root signature inside), leaving the title's argument and //! count buffers untouched. //! +//! The scratch buffer is left readable as indirect arguments after a clamp +//! and stays so until the next clamp into it, which moves it straight back +//! to unordered access; it goes back to the common state once, when the +//! list closes. The executions that read it record no barrier of their +//! own, so draws that read records clamped together (`crate::draw`'s +//! windows) follow each other with nothing between them. Before, each +//! execution was followed by a move of the scratch buffer back to the +//! common state, which drivers may treat as a full wait. +//! //! When a count buffer is given, threads at or past `min(max, count)` return //! immediately without charging the list's budget or reading uninitialized //! tail slots. Each list has a budget (2^27 vertex instances or threads, @@ -47,54 +56,76 @@ RWByteAddressBuffer dst_args : register(u0); // records run empty. RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; +// The vertices or indices an instance from which a draw record runs empty. +static const uint MOST_DRAW = 1u << 23; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; +// Each group charges the budget once: the costs of its records go here, +// one thread charges their sum, saturating as each record would in lane +// order, and every thread then reads whether its own record fitted. A +// compare and swap per record, 64 threads racing for one word, cost a +// round for each record of a window, and in memory the CPU maps (where the +// budget was, and is with VICTORY_INDIRECT_CARD_BUDGET=0) every atomic +// crosses the bus on a card of its own. +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; [RootSignature(RS)] [numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { uint eff_count = records; bool ahead = (has_count & 2u) != 0; if ((has_count & 1u) != 0) { eff_count = min(eff_count, count_buf.Load(count_offset)); } - if (id.x >= eff_count) return; + // Threads past the records take part in the group's charge (cost 0) + // and store nothing. + bool active = id.x < eff_count; uint src_at = args_offset + id.x * stride; uint dst_at = id.x * stride; - uint cost; + uint cost = 0; + uint asked = 0; uint2 draw_counts = uint2(0, 0); uint3 groups = uint3(0, 0, 0); - if (kind <= 1) { + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + if (active && kind <= 1) { // Draws: vertex or index count, then instances. - uint2 asked = src_args.Load2(src_at); - if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { - asked = uint2(0, 0); + uint2 want = src_args.Load2(src_at); + if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) { + want = uint2(0, 0); } - uint count = min(asked.x, 1u << 24); - uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + uint count = min(want.x, 1u << 24); + uint instances = min(want.y, (1u << 26) / max(count, 1u)); cost = count * instances; - draw_counts = uint2(count, instances); - } else if (kind == 2) { - uint3 asked = src_args.Load3(src_at); - // Diagnostics, in the budget buffer's words after the mesh ones: - // the largest x a compute record asked for, and the records that - // asked for more groups in x than one dispatch runs (they are cut - // to 65,535 below, so the groups past it never run). Not the - // garbage of a slot nothing wrote. - if (asked.x <= (1u << 24) && asked.y <= 64u && asked.z <= 64u) { - uint noted; - budget.InterlockedMax(12, asked.x, noted); - if (asked.x > 65535u) { - budget.InterlockedAdd(16, 1u, noted); - } + // A record that asks for MOST_DRAW vertices or indices an instance + // or more is no draw of the title's (no mesh of a console title has + // 2.8 million triangles): it runs empty and charges nothing. Run + // 206's window check found one list with 90 draws of 2^24 vertices + // and one instance each. Clamped one draw at a time, the list's + // budget lets eight of them run (2^27 in all) and empties the other + // 82; served from a window, whose records are charged once however + // often they are drawn, all 90 ran: 1.5 thousand million vertices + // in one list, with windows on in the runs that lost the device + // (201, 204). + if (count >= MOST_DRAW) { + count = 0; + instances = 0; + cost = 0; } - uint3 g = min(asked, uint3(65535u, 65535u, 65535u)); + draw_counts = uint2(count, instances); + } else if (active && kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64u; groups = g; - } else { + } else if (active) { // Mesh dispatches: the console's are one-dimensional. uint3 g = src_args.Load3(src_at); // Ahead of its draw, a record over the most a dispatch runs is a @@ -103,29 +134,68 @@ void main(uint3 id : SV_DispatchThreadID) { if (ahead && g.x > 65535u) { g = uint3(0, 0, 0); } - // Diagnostics, in the budget buffer's next words: the largest - // group count a mesh record asked for, and the groups asked in all. - uint was; - budget.InterlockedMax(4, g.x, was); - budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + asked = g.x; g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); cost = g.x * g.y * g.z * 128u; groups = g; } - bool over = false; - if (cost > 0) { + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind > 2) { + // Diagnostics, in the budget buffer's next words (below): the + // largest group count a mesh record asked for, and the groups + // asked in all. + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); + } + // The group's own records: none for a group past a count buffer's + // count (an execution may ask for thousands and count a few), which + // touches the budget not at all, as its threads did not before. + uint first = id.x - gi; + uint n = eff_count > first ? min(64u, eff_count - first) : 0u; + if (gi == 0 && n > 0) { + // What the records charge, from `before` on, in lane order: a + // record that does not fit whole runs empty and takes the rest. + // Only the group's own records are walked (one, clamped alone). uint before; budget.InterlockedOr(0, 0, before); [allow_uav_condition] while (before < BUDGET) { - uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint next = before; + for (uint j = 0; j < n; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + next = (BUDGET - next <= c) ? BUDGET : (next + c); + } + } + if (next == before) break; uint prev; budget.InterlockedCompareExchange(0, before, next, prev); if (prev == before) break; before = prev; } - over = before >= BUDGET || BUDGET - before < cost; + uint at = before; + for (uint k = 0; k < n; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + } + fits[k] = fit; + } + } + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && kind > 2 && n > 0) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); + } + if (!active) { + return; } + bool over = fits[gi] == 0; if (kind <= 1) { if (over) { draw_counts = uint2(0, 0); @@ -175,13 +245,19 @@ fn make() -> windows::core::Result { } fn make_for(device: &ID3D12Device) -> windows::core::Result { + make_from(device, SOURCE) +} + +/// The clamp compiled from `source` (ours, or in the benchmark the one it +/// replaced). +fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. let compiled = unsafe { D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), + source.as_ptr().cast(), + source.len(), s!("clamp"), None, None, @@ -254,9 +330,11 @@ fn validate_layout( /// Records, in `list`, the non-destructive clamp of up to `records` records of /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded /// by the 32-bit count in `count` when given) into a device-local scratch -/// buffer, leaving that scratch buffer in `INDIRECT_ARGUMENT` at offset `0`. -/// Replaces the list's compute root signature and pipeline (callers bind -/// theirs after). `None` if the clamp or alignment is not available. +/// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT` +/// until the next clamp into it: executions read it with no barrier of +/// their own. Replaces the list's compute root signature and pipeline +/// (callers bind theirs after). `None` if the clamp or alignment is not +/// available. pub(crate) fn bound( list: &HostList, src: (&ID3D12Resource, u64), @@ -265,7 +343,7 @@ pub(crate) fn bound( ) -> Option { let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?; let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); - record_clamp(c, &list.list, &dst, budget, src, count, spec).then_some(dst) + clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst) } /// [`bound`] for a window of records clamped ahead of the draws that will @@ -285,28 +363,41 @@ pub(crate) fn bound_ahead( ) -> Option { let bytes = validate_layout(spec, src.1, None)?; let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); - record_clamp_as(c, &list.list, &dst, budget, src, None, spec, true).then_some(dst) + clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst) } -fn record_clamp( +/// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state +/// the list left it in; afterwards the list knows it is readable as +/// indirect arguments. +#[allow(clippy::too_many_arguments)] +fn clamp_into( + list: &HostList, c: &Clamp, - l: &ID3D12GraphicsCommandList, dst: &ID3D12Resource, budget: u64, src: (&ID3D12Resource, u64), count: Option<(&ID3D12Resource, u64)>, spec: (u32, u32, u32), + ahead: bool, ) -> bool { - record_clamp_as(c, l, dst, budget, src, count, spec, false) + let before = list.indirect_state(dst); + let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead); + if recorded { + list.indirect_readable(dst); + } + recorded } -/// [`record_clamp`]; `ahead`: the records are a window clamped ahead of -/// their draws ([`bound_ahead`]). +/// Records the clamp into `dst`, which is in state `before` (common, or +/// indirect arguments after an earlier clamp into it), and leaves `dst` in +/// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of +/// their draws ([`bound_ahead`]). False, with nothing recorded, if the +/// layout or the addresses do not fit the clamp. #[allow(clippy::too_many_arguments)] fn record_clamp_as( c: &Clamp, l: &ID3D12GraphicsCommandList, - dst: &ID3D12Resource, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), budget: u64, (src, src_offset): (&ID3D12Resource, u64), count: Option<(&ID3D12Resource, u64)>, @@ -360,7 +451,9 @@ fn record_clamp_as( // SAFETY: an open list; our root signature and pipeline; live source, // count, scratch destination, and budget buffers. `src` and `count` stay // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` - // transitions `COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. + // 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). #[cfg(feature = "diagnostics")] @@ -371,11 +464,7 @@ fn record_clamp_as( let waits = true; let first = [ uav_barrier(), - transition( - dst, - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - ), + transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]; let second = [ uav_barrier(), @@ -404,21 +493,220 @@ fn record_clamp_as( true } -/// After indirect execution (or if preparation failed after [`bound`]): -/// returns the scratch buffer to the common state for the next call. -pub(crate) fn done(list: &HostList, scratch: &ID3D12Resource) { - done_on(&list.list, scratch); +/// Whether every draw served from a window is checked against a fresh +/// clamp of its record (`VICTORY_INDIRECT_WINDOW_CHECK=1`, with +/// `VICTORY_INDIRECT_WINDOW=1`; off by default). A window clamps its +/// records once, ahead of their draws; if anything wrote a record between +/// the window's clamp and its draw, the draw reads the old one. The check +/// clamps the record again just before the draw (into a buffer of its own, +/// charging a budget of its own) and compares the two on the card: the +/// counts are logged ("window check"), and the first record that differs in +/// each run of a list is named. For telling whether windows can be trusted +/// in a scene before they are on by default; it costs a clamp and a compare +/// per window draw. +pub(crate) fn window_check() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_INDIRECT_WINDOW_CHECK").is_some_and(|v| v == "1") + }) } -fn done_on(list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource) { - // SAFETY: an open list and a live scratch buffer in INDIRECT_ARGUMENT. - unsafe { - list.ResourceBarrier(&[transition( - scratch, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_COMMON, - )]) +/// The compare of [`window_check`]: `words` dwords of the record a window +/// clamped (`t0`) against the same record clamped just now (`t1`). Counts +/// the checks and the records that differ in `u0`, keeps the first record +/// that differs there (eight dwords of each), and zeroes the fresh clamp's +/// own budget (`u1`) for the next check. +const CHECK_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=1, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Check : register(b0) { + uint words; +}; +ByteAddressBuffer window_record : register(t0); +ByteAddressBuffer fresh_record : register(t1); +RWByteAddressBuffer results : register(u0); +RWByteAddressBuffer fresh_budget : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + bool same = true; + for (uint i = 0; i < words; i++) { + if (window_record.Load(4 * i) != fresh_record.Load(4 * i)) { + same = false; + } + } + uint was; + results.InterlockedAdd(4, 1, was); + if (!same) { + uint before; + results.InterlockedAdd(0, 1, before); + if (before == 0) { + for (uint k = 0; k < min(words, 8u); k++) { + results.Store(8 + 4 * k, window_record.Load(4 * k)); + results.Store(40 + 4 * k, fresh_record.Load(4 * k)); + } + } + } + fresh_budget.Store3(0, uint3(0, 0, 0)); +} +"#; + +fn compare() -> Option<&'static Clamp> { + static COMPARE: std::sync::OnceLock> = std::sync::OnceLock::new(); + COMPARE + .get_or_init(|| { + let device = &host()?.device; + match make_from(device, CHECK_SOURCE) { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no window check"); + None + } + } + }) + .as_ref() +} + +/// A list's buffers for [`window_check`]: the fresh clamps' records and +/// budget (the card's memory), and the results (memory the CPU maps: +/// records that differed, checks, then the first differing record as the +/// window had it and as the fresh clamp made it, eight dwords each). +pub(crate) struct WindowCheck { + args: ID3D12Resource, + budget: ID3D12Resource, + results: ID3D12Resource, + data: usize, +} + +// SAFETY: D3D12 objects are free-threaded; the mapping is read only at +// submission, when the list's last run has finished. +unsafe impl Send for WindowCheck {} +// SAFETY: as above. +unsafe impl Sync for WindowCheck {} + +impl WindowCheck { + pub(crate) fn new() -> Option { + let host = host()?; + let (results, data) = host.shared_buffer(256)?; + // SAFETY: the mapping holds 256 bytes; nothing runs yet. + unsafe { std::ptr::write_bytes(data, 0, 256) }; + Some(WindowCheck { + args: host.uav_buffer(64 << 10)?, + budget: host.uav_buffer(256)?, + results, + data: data as usize, + }) + } + + /// What the list's last run found, zeroed for the next: checks, records + /// that differed, and the first that did (as the window had it, as the + /// fresh clamp made it). Only between runs of the list. + pub(crate) fn take(&self) -> (u32, u32, [u32; 8], [u32; 8]) { + let words = self.data as *mut u32; + // SAFETY: the list's own mapped words; its last run has finished. + unsafe { + let at = |k: usize| words.add(k).read_volatile(); + let window = std::array::from_fn(|k| at(2 + k)); + let fresh = std::array::from_fn(|k| at(10 + k)); + let found = (at(1), at(0), window, fresh); + std::ptr::write_bytes(words, 0, 18); + found + } + } +} + +/// Checks and differing records seen by [`window_check`] so far. +static CHECKED: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`window_check`] for a draw served from a window: the record of `kind` +/// at `src`, `step` bytes long, which the window clamped into `scratch` at +/// `at`, is clamped again into the list's check buffer and compared. Runs +/// compute work of ours, so the caller binds its pipeline again after it. +/// False if nothing was recorded. +pub(crate) fn check_hit( + list: &HostList, + src: (&ID3D12Resource, u64), + (kind, step): (u32, u32), + scratch: &ID3D12Resource, + at: u64, +) -> bool { + const CHECK_USE: usize = usize::MAX - 0x78; + let (Some(c), Some(cmp), Some(check)) = (clamp(), compare(), list.window_check()) else { + return false; }; + if list.first_use(CHECK_USE) { + // At this recording's submission: what the list's last run found. + let data = check.data; + let words = WindowCheck { + args: check.args.clone(), + budget: check.budget.clone(), + results: check.results.clone(), + data, + }; + list.defer_host(move || { + let (checked, differed, window, fresh) = words.take(); + if checked == 0 { + return; + } + use std::sync::atomic::Ordering::Relaxed; + let total = CHECKED[0].fetch_add(u64::from(checked), Relaxed) + u64::from(checked); + let bad = CHECKED[1].fetch_add(u64::from(differed), Relaxed) + u64::from(differed); + if differed > 0 { + tracing::warn!( + differed, + checked, + ?window, + ?fresh, + "window check: a draw served from a window read a record that \ + differs from a fresh clamp of it" + ); + } + if total / 10_000 != (total - u64::from(checked)) / 10_000 { + tracing::info!(checked = total, differed = bad, "window check"); + } + }); + } + // SAFETY: live buffers. + let (budget, results, fresh, window) = unsafe { + ( + check.budget.GetGPUVirtualAddress(), + check.results.GetGPUVirtualAddress(), + check.args.GetGPUVirtualAddress(), + scratch.GetGPUVirtualAddress() + at, + ) + }; + // The record again, by the window's rules, into the check's buffer + // (common before and after every check). + let common = D3D12_RESOURCE_STATE_COMMON; + let spec = (kind, step, 1); + if !record_clamp_as(c, &list.list, (&check.args, common), budget, src, None, spec, true) { + return false; + } + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let words = step / 4; + // SAFETY: an open list; the compare's own root signature and pipeline; + // the scratch buffer is readable as arguments (and stays so), the + // check's buffer was left so by the clamp above. + unsafe { + list.list.ResourceBarrier(&[ + transition(scratch, args, D3D12_RESOURCE_STATES(args.0 | read.0)), + transition(&check.args, args, read), + ]); + list.list.SetComputeRootSignature(&cmp.root); + list.list.SetPipelineState(&cmp.pso); + list.list.SetComputeRoot32BitConstants(0, 1, (&raw const words).cast(), 0); + list.list.SetComputeRootShaderResourceView(1, window); + list.list.SetComputeRootShaderResourceView(2, fresh); + list.list.SetComputeRootUnorderedAccessView(3, results); + list.list.SetComputeRootUnorderedAccessView(4, budget); + list.list.Dispatch(1, 1, 1); + list.list.ResourceBarrier(&[ + transition(scratch, D3D12_RESOURCE_STATES(args.0 | read.0), args), + transition(&check.args, read, common), + ]); + } + true } fn uav_barrier() -> D3D12_RESOURCE_BARRIER { @@ -947,14 +1235,15 @@ void main() { // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first // 5 records of `dst_buf` out for inspection, then record Call #2 // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list! - assert!(record_clamp( + assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&src_buf, ARGS_OFFSET as u64), Some((&count_buf, COUNT_OFFSET_1 as u64)), (KIND_DISPATCH, STRIDE, MAX), + false, )); // SAFETY: open command list, valid worker PSO/root and buffers. unsafe { @@ -970,15 +1259,14 @@ void main() { COUNT_OFFSET_1 as u64, ); } - done_on(&warp.list, &dst_buf); - // Snapshot `dst_buf` after Call #1 (from `COMMON`, copy 5 * STRIDE bytes, - // then return `dst_buf` to `COMMON` before Call #2). - // SAFETY: open command list; `dst_buf` returned to `COMMON` by `done_on`. + // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave + // `dst_buf` readable as arguments again, as the clamp left it). + // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`. unsafe { warp.list.ResourceBarrier(&[transition( &dst_buf, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); warp.list @@ -986,20 +1274,23 @@ void main() { warp.list.ResourceBarrier(&[transition( &dst_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, )]); } // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1: // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`! - assert!(record_clamp( + // The scratch buffer goes straight from arguments back to unordered + // access. + assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), budget_gpu, (&src_buf, ARGS_OFFSET as u64), Some((&count_buf, COUNT_OFFSET_2 as u64)), (KIND_DISPATCH, STRIDE, MAX), + false, )); // SAFETY: open command list, valid worker PSO/root and buffers. unsafe { @@ -1015,7 +1306,6 @@ void main() { COUNT_OFFSET_2 as u64, ); } - done_on(&warp.list, &dst_buf); warp.submit_and_wait(); @@ -1112,27 +1402,22 @@ void main() { assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&src_buf, 0), None, (KIND_MESH, STRIDE, RECORDS), ahead, )); - done_on(&warp.list, &dst_buf); - // SAFETY: an open list; the scratch buffer is copied for the check. + // SAFETY: an open list; the scratch buffer, which the clamp left + // readable as arguments, is copied for the check. unsafe { warp.list.ResourceBarrier(&[transition( &dst_buf, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); - warp.list.ResourceBarrier(&[transition( - &dst_buf, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON, - )]); } warp.submit_and_wait(); // SAFETY: the work is done; mapped buffers. @@ -1181,9 +1466,11 @@ void main() { let mut initial_src = vec![0u8; total_bytes]; for i in 0..RECORDS as usize { + // The first record is no draw (2^24 indices): it runs empty + // and charges nothing. let words: [u32; 6] = [ - u32::MAX, // IndexCount -> clamps to 1 << 24 - u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26) + if i == 0 { 1 << 24 } else { 1 << 22 }, // IndexCount + if i == 0 { 1 } else { u32::MAX }, // InstanceCount -> clamps to 16 (cost = 1 << 26) 1000 + i as u32, // StartIndexLocation (-200i32 + i as i32) as u32, // BaseVertexLocation 5000 + i as u32, // StartInstanceLocation @@ -1202,31 +1489,27 @@ void main() { std::ptr::write_bytes(readback_ptr, 0, total_bytes); } - assert!(record_clamp( + assert!(record_clamp_as( &warp.clamp, &warp.list, - &dst_buf, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&src_buf, 0), None, (KIND_INDEXED, STRIDE, RECORDS), + false, )); - done_on(&warp.list, &dst_buf); - // SAFETY: open command list; copy clamped scratch buffer for verification. + // SAFETY: open command list; copy clamped scratch buffer (left + // readable as arguments) for verification. unsafe { warp.list.ResourceBarrier(&[transition( &dst_buf, - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); warp.list .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64); - warp.list.ResourceBarrier(&[transition( - &dst_buf, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON, - )]); } warp.submit_and_wait(); @@ -1252,7 +1535,8 @@ void main() { let mut zeroed = 0usize; for i in 0..RECORDS as usize { let rec = &out_words[i * 6..(i + 1) * 6]; - if rec[0] == (1 << 24) && rec[1] == 4 { + if rec[0] == (1 << 22) && rec[1] == 16 { + assert!(i == 1 || i == 2, "the first two real draws fit the budget"); kept += 1; } else { assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); @@ -1266,13 +1550,16 @@ void main() { assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2)); } - /// Exercises `HostList::indirect_scratch`, `bound`, `done`, `Host::execute`, - /// and `HostList::reset` end-to-end on the host device. + /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's + /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on + /// the host device. #[test] fn host_list_reuses_and_grows_scratch_across_submissions() { let Some(host) = super::host() else { return; }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); let Ok(list) = host.new_list() else { return; }; @@ -1288,47 +1575,483 @@ void main() { (count_ptr as *mut u32).write_volatile(2); } + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; // First two calls fit inside the initial 64 KiB scratch buffer and - // must reuse the exact same `ID3D12Resource`. + // must reuse the exact same `ID3D12Resource`, which stays readable + // as arguments between them. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap(); - done(&list, &b1); + assert_eq!( + list.indirect_state(&b1), + args, + "a clamp leaves the scratch readable as arguments" + ); let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap(); - done(&list, &b2); assert_eq!( b1.as_raw(), b2.as_raw(), "scratch buffer within capacity must be reused" ); + assert_eq!(list.indirect_state(&b2), args); // A call needing >64 KiB grows the scratch buffer mid-list while keeping - // `b1` alive until reset. + // `b1` alive until reset. The new buffer starts out common. + let grown = list.indirect_scratch(5000 * 20).unwrap(); + assert_eq!( + list.indirect_state(&grown), + D3D12_RESOURCE_STATE_COMMON, + "a new scratch buffer is common" + ); let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap(); - done(&list, &b3); + assert_eq!(b3.as_raw(), grown.as_raw()); assert_ne!( b3.as_raw(), b1.as_raw(), "larger request must grow scratch buffer" ); + assert_eq!(list.indirect_state(&b3), args); + assert_eq!( + list.indirect_state(&b1), + D3D12_RESOURCE_STATE_COMMON, + "the replaced buffer went back to common" + ); list.close(); + // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics): + // every barrier recorded named the state the buffer was in. Read + // before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); // After reset, requests up to the grown high-water mark reuse `b3` with - // zero new allocations. + // zero new allocations; the buffer decayed to common when the + // submission ran. + assert_eq!( + list.indirect_state(&b3), + D3D12_RESOURCE_STATE_COMMON, + "a reset list starts with a common scratch buffer" + ); let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap(); - done(&list, &b4); assert_eq!( b4.as_raw(), b3.as_raw(), "grown scratch buffer must persist across reset" ); + assert_eq!(list.indirect_state(&b4), args); list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); list.reset(); } + + /// A group charges its records in lane order: with 300 left of the + /// budget, the first draw (100) fits, the second (250) does not and + /// takes the rest, and the ones after it run empty. (Racing for the + /// word record by record, which of them fitted was up to the GPU.) + #[test] + fn warp_a_group_charges_its_records_in_lane_order() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DRAW: u32 = 0; + const STRIDE: u32 = 16; + const BUDGET_CAP: u32 = 1 << 27; + let counts = [100u32, 250, 50, 100]; + let total = counts.len() * STRIDE as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + for (i, &count) in counts.iter().enumerate() { + let words = [count, 1, 7, 9]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STRIDE as usize), + 16, + ); + } + std::ptr::write_bytes(budget_ptr, 0, 256); + (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_DRAW, STRIDE, counts.len() as u32), + false, + )); + // SAFETY: an open list; the clamped records are copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4) + .to_vec(), + ) + }; + assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); + for i in 1..counts.len() { + assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); + } + assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + } + + /// The list's budget starts empty at each submission, wherever it + /// lives (the card's copy is zeroed in the list): a recording whose + /// clamps spend all of it is followed, after the reset, by one whose + /// small record still runs. + #[test] + fn host_list_budget_starts_empty_at_each_submission() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + // Three records of 65,535 x 16 groups: about half the budget each. + let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else { + return; + }; + let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else { + return; + }; + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + for i in 0..3 { + let words = [65535u32, 16, 1]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + big_ptr.add(i * STRIDE as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::(), small_ptr, 12); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for round in 0..2 { + // Spends the budget (clamped, not executed), then one group. + bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap(); + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + // The small record comes after the big ones spent the budget: + // it runs empty, in every round alike (none carries over). + assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it"); + } + // A recording with only the small record: the budget is empty + // again, so it runs. + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + // SAFETY: as above. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, 1, "the budget starts empty at the next submission"); + } + + /// The window check: a record nothing wrote since its window clamped + /// it compares equal; one written on the card after the window's clamp + /// (an untracked writer) is found, and named as the window had it and + /// as it is now. + #[test] + fn host_list_window_check_finds_a_record_written_under_its_window() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + const KIND_DISPATCH: u32 = 2; + const STEP: u32 = 32; + let records = [[3u32, 1, 1], [5, 1, 1], [7, 1, 1], [9, 1, 1]]; + let total = records.len() * STEP as usize; + let (Some((src, src_ptr)), Some((patch, patch_ptr))) = + (host.shared_buffer(total as u64), host.shared_buffer(64)) + else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + std::ptr::write_bytes(src_ptr, 0, total); + for (i, words) in records.iter().enumerate() { + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STEP as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([11u32, 2, 1].as_ptr().cast::(), patch_ptr, 12); + } + let spec = (KIND_DISPATCH, STEP, records.len() as u32); + let scratch = bound_ahead(&list, (&src, 0), spec).unwrap(); + // Record 0: nothing wrote it. + assert!(check_hit(&list, (&src, 0), (KIND_DISPATCH, STEP), &scratch, 0)); + // Record 1 is written on the card after the window's clamp. + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + // SAFETY: an open list; `src` was read by the clamp (promoted to a + // shader read), `patch` is common; both live until the list has run. + unsafe { + list.list.ResourceBarrier(&[transition(&src, read, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.list.CopyBufferRegion(&src, u64::from(STEP), &patch, 0, 12); + list.list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, read)]); + } + let at = u64::from(STEP); + assert!(check_hit(&list, (&src, at), (KIND_DISPATCH, STEP), &scratch, at)); + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + let (checked, differed, window, fresh) = list.window_check().unwrap().take(); + list.reset(); + assert_eq!((checked, differed), (2, 1), "two checks, the written record differs"); + assert_eq!(window[..3], [5, 1, 1], "as the window clamped it"); + assert_eq!(fresh[..3], [11, 2, 1], "as it is now"); + } + + /// Records the dispatch records `groups` (three words each, `step` + /// bytes apart, the rest of each record ones) into a fresh mapped + /// buffer of `warp`'s device. + fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource { + let total = groups.len() * step as usize; + let (buffer, ptr, _) = warp.shared_buffer(total as u64); + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * step as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + buffer + } + + /// Two windows in one list, as `crate::draw` records them: each clamps + /// its records ahead, then one execution per record reads the scratch + /// buffer with no barrier between them; the second clamp moves the + /// scratch buffer straight from arguments back to unordered access. + /// Every record runs once, with the group count it asked for. + #[test] + fn warp_window_executions_read_their_records_with_no_barrier_between() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + // The title names 12 bytes and keeps its records 32 apart. + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let sources: Vec = + windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect(); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let dst_buf = warp.default_uav(u64::from(STEP) * 4); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + let mut state = D3D12_RESOURCE_STATE_COMMON; + for (groups, src) in windows.iter().zip(&sources) { + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, state), + budget_gpu, + (src, 0), + None, + (KIND_DISPATCH, STEP, groups.len() as u32), + true, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // SAFETY: an open list; the worker's root signature and + // pipeline; the scratch buffer is readable as arguments. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0); + } + } + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (hits, spent) = unsafe { + ( + (hits_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).read_volatile(), + ) + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + assert_eq!(hits, expected, "every record of both windows runs once"); + assert_eq!(spent, expected * 64, "and is charged what it asked for"); + } + + /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between` + /// through a host list (`bound_ahead`, the list's tracked scratch state, + /// `Host::execute`), twice: on the first recording the scratch buffer + /// starts common, on the second (after the reset) it starts common + /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a + /// diagnostics build) no barrier names a state the buffer is not in. + #[test] + fn host_list_window_executions_need_no_barrier_of_their_own() { + let Some(host) = super::host() else { + return; + }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let mut sources = Vec::new(); + for groups in windows { + let total = groups.len() * STEP as usize; + let Some((buffer, ptr)) = host.shared_buffer(total as u64) else { + return; + }; + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * STEP as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + sources.push(buffer); + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for _ in 0..2 { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + for (groups, src) in windows.iter().zip(&sources) { + let spec = (KIND_DISPATCH, STEP, groups.len() as u32); + let scratch = bound_ahead(&list, (src, 0), spec).unwrap(); + assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + let at = i * u64::from(STEP); + list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0); + } + } + } + list.close(); + // With the debug layer on: nothing it objects to was recorded. + // Read before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, expected, "every record of both windows runs once"); + } + } } +/// The benchmark of the clamp and its barriers (ignored by default). +#[cfg(test)] +mod bench; + /// What one small draw costs this card, bare and with one thing changed /// between every two draws: a measurement, not a check (it asserts only /// that the card answered). The timing run of the lit scene (run 187) has diff --git a/crates/victory-gpu/src/indirect/bench.rs b/crates/victory-gpu/src/indirect/bench.rs new file mode 100644 index 00000000..0e233dba --- /dev/null +++ b/crates/victory-gpu/src/indirect/bench.rs @@ -0,0 +1,502 @@ +//! A frame's worth of one-record indirect draws on the host GPU, clamped one +//! at a time and in windows, recorded as `main` does (the scratch buffer +//! back to the common state after every execution, the clamp charging the +//! budget record by record) and as this tree does (readable until the next +//! clamp, one charge per group). Ignored by default; run it with +//! `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`. +//! It needs no title files: the draws are tiny triangles of ours. + +use super::*; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; +use windows::Win32::Graphics::Dxgi::{ + CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4, +}; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, PCSTR}; + +/// Draws a frame (the title's gameplay frames hold about 3,200 indirect +/// executions, #107), records a window holds, and how far apart the +/// records are (the title keeps them 32 bytes apart). +const DRAWS: u32 = 3200; +const WINDOW: u32 = 32; +const STEP: u32 = 32; +const RUNS: usize = 9; + +const SHADERS: &str = r#" +#define RS "RootFlags(0)" +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position { +float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5; +return float4(p, 0.5, 1); +} +float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } +"#; + +fn compile(entry: &str, target: &str) -> Vec { + let entry = std::ffi::CString::new(entry).unwrap(); + let target = std::ffi::CString::new(target).unwrap(); + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { + D3DCompile( + SHADERS.as_ptr().cast(), + SHADERS.len(), + s!("bench"), + None, + None, + PCSTR(entry.as_ptr().cast()), + PCSTR(target.as_ptr().cast()), + 0, + 0, + &mut code, + None, + ) + .unwrap(); + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() + } +} + +/// The clamp as it was before it charged the budget once per group +/// (record by record, every thread racing for the budget word), kept +/// here to measure against. +const OLD_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { +uint kind; +uint stride; +uint records; +uint args_offset; +// Bit 0: a count buffer bounds the records. Bit 1: the records are a +// window clamped ahead of their draws: one that asks for more than can +// run is left empty and costs nothing. +uint has_count; +uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { +uint eff_count = records; +bool ahead = (has_count & 2u) != 0; +if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); +} +if (id.x >= eff_count) return; +uint src_at = args_offset + id.x * stride; +uint dst_at = id.x * stride; +uint cost; +uint2 draw_counts = uint2(0, 0); +uint3 groups = uint3(0, 0, 0); +if (kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + draw_counts = uint2(count, instances); +} else if (kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; +} else { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; +} +bool over = false; +if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; +} +if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} +} +"#; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Barriers { + /// Back to the common state after every execution (as before). + Old, + /// Readable as arguments until the next clamp, common at the end. + New, +} + +#[test] +#[ignore = "benchmark; see the module notes"] +fn bench_indirect_draw_barriers() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + let device = &host.device; + let clamps = [ + make_from(device, OLD_SOURCE).expect("the old clamp"), + make_for(device).expect("the clamp"), + ]; + // SAFETY: plain D3D12 object creation with valid descriptions; the + // objects outlive every list recorded and run below. + unsafe { + let adapter = { + let luid = device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| { + f.EnumAdapterByLuid::(luid) + }) + .and_then(|a| a.GetDesc1()) + .map(|d| { + String::from_utf16_lossy(&d.Description) + .trim_end_matches('\0') + .to_owned() + }) + .unwrap_or_else(|_| "an unnamed adapter".to_owned()) + }; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let frequency = queue.GetTimestampFrequency().unwrap() as f64; + + // The pipeline: tiny triangles into a small target. + let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut target: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtvs: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + + // The title's records: three vertices, one instance, 32 bytes apart. + let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap(); + for i in 0..DRAWS as usize { + let words = [3u32, 1, 0, 0]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STEP as usize), + 16, + ); + } + let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); + let budget_gpu = budget.GetGPUVirtualAddress(); + // The same words in the card's own memory (zeroed when made; the + // runs below charge far less than the budget). + let card_budget = host.uav_buffer(256).unwrap(); + let card_budget_gpu = card_budget.GetGPUVirtualAddress(); + let scratch = host + .uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)) + .unwrap(); + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + sig.unwrap() + }; + let stamps: ID3D12QueryHeap = { + let mut heap: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut heap, + ) + .unwrap(); + heap.unwrap() + }; + let mut back: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .unwrap(); + let back = back.unwrap(); + let mut submitted = 0u64; + + // One frame's lists: GPU ms (timestamps around the list), CPU ms + // recording it, ms from submission to the end of its run. + let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32, card: bool| -> [f64; 3] { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + let recording = std::time::Instant::now(); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: 256.0, + Height: 256.0, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 256, + bottom: 256, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.SetGraphicsRootSignature(&root); + let mut state = D3D12_RESOURCE_STATE_COMMON; + for first in (0..DRAWS).step_by(window as usize) { + let records = window.min(DRAWS - first); + assert!(record_clamp_as( + clamp, + &list, + (&scratch, state), + if card { card_budget_gpu } else { budget_gpu }, + (&src, u64::from(first * STEP)), + None, + (0, STEP, records), + window > 1, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + list.SetPipelineState(&pso); + for k in 0..records { + list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0); + if barriers == Barriers::Old { + list.ResourceBarrier(&[transition( + &scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + state = D3D12_RESOURCE_STATE_COMMON; + } + } + } + if state != D3D12_RESOURCE_STATE_COMMON { + list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]); + } + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0); + list.Close().unwrap(); + let recorded = recording.elapsed().as_secs_f64() * 1e3; + let running = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let ran = running.elapsed().as_secs_f64() * 1e3; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let t = std::slice::from_raw_parts(data.cast::(), 2); + let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3; + back.Unmap(0, None); + (budget_ptr as *mut u32).write_volatile(0); + [gpu, recorded, ran] + }; + + // What `main` records, then this branch; the windows a step at a + // time (barriers, then the clamp's one charge per group). + let (old, new) = (&clamps[0], &clamps[1]); + // The last two keep the budget in the card's memory instead of + // memory the CPU maps (where the list's budget is now). + let cases: [(&str, Barriers, &Clamp, u32, bool); 7] = [ + ("one at a time, main", Barriers::Old, old, 1, false), + ("one at a time, this", Barriers::New, new, 1, false), + ("windows of 32, main", Barriers::Old, old, WINDOW, false), + ("windows, new barriers", Barriers::New, old, WINDOW, false), + ("windows of 32, this", Barriers::New, new, WINDOW, false), + ("one at a time, card", Barriers::New, new, 1, true), + ("windows of 32, card", Barriers::New, new, WINDOW, true), + ]; + // Warm up, then the cases in turn, so drift falls on all alike. + for &(_, barriers, clamp, window, card) in &cases { + frame(barriers, clamp, window, card); + } + let mut times: Vec> = vec![Vec::new(); cases.len()]; + for _ in 0..RUNS { + for (i, &(_, barriers, clamp, window, card)) in cases.iter().enumerate() { + times[i].push(frame(barriers, clamp, window, card)); + } + } + let median = |v: &[[f64; 3]], k: usize| { + let mut x: Vec = v.iter().map(|t| t[k]).collect(); + x.sort_by(f64::total_cmp); + x[x.len() / 2] + }; + eprintln!( + "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \ + medians of {RUNS} frames" + ); + for (i, (name, ..)) in cases.iter().enumerate() { + let gpu = median(×[i], 0); + eprintln!( + " {name:<22} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \ + submit to done {:7.2} ms", + gpu * 1e3 / f64::from(DRAWS), + median(×[i], 1), + median(×[i], 2), + ); + } + for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4), (1, 5), (4, 6)] { + let (a, b) = (median(×[from], 0), median(×[to], 0)); + eprintln!( + " {} -> {}: GPU time {:+.1} %", + cases[from].0, + cases[to].0, + (b / a - 1.0) * 100.0 + ); + } + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index e001a473..54e12518 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -38,8 +38,12 @@ pub mod object; pub mod pipeline; #[cfg(windows)] mod primitive; +#[cfg(all(windows, feature = "diagnostics"))] +mod profile; pub mod query; pub mod queue; +#[cfg(windows)] +mod queue2; pub mod resource; pub mod root; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index f9edaab5..516ba261 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -151,6 +151,8 @@ fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::dra f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); #[cfg(feature = "diagnostics")] crate::copystat::recorded(started); + #[cfg(feature = "diagnostics")] + crate::profile::seen(crate::profile::Seen::Record); } /// The submission of `lists` has run: each gives its descriptor tables' @@ -222,7 +224,12 @@ static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::ne /// between them (a list keeps scratch chunks over a reset only while lists /// do not share them, `VICTORY_SCRATCH_POOL=0`). #[cfg(windows)] -const IDLE_MOST: (usize, u64) = (128, 256 << 20); +// (512 since run 221: with submissions prepared by a thread of ours the +// title has its lists back at once and resets them while the flights of +// the frame before are still in the air, so more than 128 are out at a +// time: 80 host lists were made and as many thrown away every frame, +// 8 ms to make and more to free, on the thread that submits.) +const IDLE_MOST: (usize, u64) = (512, 256 << 20); /// Whether host lists that have run are used again (on by default; /// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before). diff --git a/crates/victory-gpu/src/profile.rs b/crates/victory-gpu/src/profile.rs new file mode 100644 index 00000000..26792f48 --- /dev/null +++ b/crates/victory-gpu/src/profile.rs @@ -0,0 +1,2961 @@ +//! Where the layer's threads spend their time: a sampling profiler +//! (`VICTORY_PROFILE=1`, diagnostics builds; off otherwise). +//! +//! The log's own counters say how long the phases of a frame take, not +//! what a thread does inside them: in the graphics driver, in a kernel +//! call, waiting for a lock. A thread of ours ([`run`]) looks, a thousand +//! times a second (`VICTORY_PROFILE_HZ`), at the threads that matter: +//! +//! * the submitting thread and the recording threads, which name +//! themselves by what they call ([`seen`]: [`crate::host::Host`]'s +//! submissions, the list calls); +//! * our workers, by the names we start them with (`victory-pipelines-N`, +//! `victory-wide-N`, `victory-late-wait`) and the title's main thread; +//! * the busiest of the other threads (the title's own). +//! +//! A look ([`Sampler::capture`]) suspends the thread, reads its registers +//! and copies the used part of its stack with the kernel's own read, and +//! lets it go: between the two nothing of ours takes a lock, allocates or +//! reads memory that may be gone. The stack is walked afterwards, in the +//! copy ([`Sampler::walk`]), by each image's unwind data (the Windows +//! loader registered it for title images too), every read checked to stay +//! inside the copy. A thread that has used no processor cycles since the +//! last look is where it was: it is not suspended again. +//! +//! Names are found when the report is written, not when a sample is +//! taken ([`Symbols`]): our executable through its PDB (inlined calls +//! too), system and driver code by export or `module+offset`, title code +//! as `title+offset` of the function's start. +//! +//! The report is written every `VICTORY_PROFILE_EVERY` seconds (30) and at +//! exit to `VICTORY_PROFILE_OUT` (`%TEMP%\victory_profile_.txt`), the +//! stacks for a flame graph beside it (`.folded`). Per kind of thread: +//! time by module, by function (own and with what it calls), where it +//! waited and for which of our functions, the hottest lines of ours. Times +//! are milliseconds per presented frame ([`frame`]). + +use std::cell::Cell; +use std::collections::HashMap; +use std::ffi::c_void; +use std::fmt::Write as _; +use std::hash::{BuildHasherDefault, Hasher}; +use std::path::PathBuf; +use std::ptr::{null, null_mut}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering::Relaxed}; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE, HMODULE, LocalFree, +}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64, GetThreadContext, IMAGEHLP_LINEW64, + IMAGEHLP_MODULEW64, ReadProcessMemory, RtlLookupFunctionEntry, RtlVirtualUnwind, SYMBOL_INFOW, + UNW_FLAG_NHANDLER, +}; +use windows_sys::Win32::System::LibraryLoader::{ + GetModuleFileNameW, GetModuleHandleW, GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, + LoadLibraryExA, +}; +use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; +use windows_sys::Win32::System::ProcessStatus::{ + K32EnumProcessModules, K32GetModuleInformation, MODULEINFO, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentThread, GetCurrentThreadId, GetThreadDescription, GetThreadId, + GetThreadTimes, OpenThread, ResumeThread, SetThreadPriority, SuspendThread, THREAD_GET_CONTEXT, + THREAD_PRIORITY_TIME_CRITICAL, THREAD_QUERY_INFORMATION, THREAD_QUERY_LIMITED_INFORMATION, + THREAD_SUSPEND_RESUME, WaitForSingleObject, +}; + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + /// The processor cycles a thread has used so far. + fn QueryThreadCycleTime(thread: HANDLE, cycles: *mut u64) -> i32; +} + +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The thread of `process` after `thread` (null: the first), opened + /// with `access`; an NTSTATUS, not zero after the last. + fn NtGetNextThread( + process: HANDLE, + thread: HANDLE, + access: u32, + attributes: u32, + flags: u32, + next: *mut HANDLE, + ) -> i32; + /// `(thread, class, out, size, written)`: an NTSTATUS. + fn NtQueryInformationThread( + thread: HANDLE, + class: i32, + information: *mut c_void, + size: u32, + written: *mut u32, + ) -> i32; +} + +// --------------------------------------------------------------------- +// What the layer's threads tell the profiler. +// --------------------------------------------------------------------- + +/// 0: not asked yet, [`OFF`], [`ON`]. +static STATE: AtomicU8 = AtomicU8::new(0); +const OFF: u8 = 1; +const ON: u8 = 2; + +/// Frames presented since the profiler started. +static FRAMES: AtomicU64 = AtomicU64::new(0); + +/// What a thread was seen doing. +#[derive(Clone, Copy)] +pub(crate) enum Seen { + /// It called a submission ([`crate::host::Host`]). + Submit = 0, + /// It made a list call. + Record = 1, +} + +/// A thread that called [`seen`], and how often for each [`Seen`]. A line +/// of the cache each: the recording threads count here at every list call. +#[repr(align(64))] +struct Known { + thread: AtomicU32, + seen: [AtomicU64; 2], +} + +const KNOWN: usize = 64; +static KNOWN_THREADS: [Known; KNOWN] = [const { + Known { + thread: AtomicU32::new(0), + seen: [const { AtomicU64::new(0) }; 2], + } +}; KNOWN]; + +/// Submissions after which a thread is a submitting thread, and list calls +/// after which it is a recording thread: a thread that reads a texture +/// back once while the world loads is neither. +const SUBMITS: u64 = 8; +const LIST_CALLS: u64 = 64; + +thread_local! { + /// This thread's place in [`KNOWN_THREADS`], plus one; 0 before it has + /// one, 255 if there was none left. + static MINE: Cell = const { Cell::new(0) }; +} + +/// Whether the profiler runs; the first call reads `VICTORY_PROFILE` and +/// starts it. +#[inline] +fn on() -> bool { + match STATE.load(Relaxed) { + ON => true, + OFF => false, + _ => decide(), + } +} + +#[cold] +fn decide() -> bool { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let started = Config::from_env().is_some_and(start); + let state = if started { ON } else { OFF }; + STATE.store(state, Relaxed); + }); + STATE.load(Relaxed) == ON +} + +/// The calling thread was seen doing `what`: it is followed once it has +/// done so often enough. Costs a load when the profiler is off. +#[inline] +pub(crate) fn seen(what: Seen) { + if !on() { + return; + } + let mine = MINE.with(Cell::get); + let known = match mine { + 0 => match claim() { + Some(known) => known, + None => return, + }, + 255 => return, + at => &KNOWN_THREADS[usize::from(at) - 1], + }; + known.seen[what as usize].fetch_add(1, Relaxed); +} + +/// A place in [`KNOWN_THREADS`] for the calling thread. +#[cold] +fn claim() -> Option<&'static Known> { + // SAFETY: a plain query. + let id = unsafe { GetCurrentThreadId() }; + for (at, known) in KNOWN_THREADS.iter().enumerate() { + if known + .thread + .compare_exchange(0, id, Relaxed, Relaxed) + .is_ok() + { + known.seen[0].store(0, Relaxed); + known.seen[1].store(0, Relaxed); + MINE.with(|m| m.set(at as u8 + 1)); + return Some(known); + } + } + MINE.with(|m| m.set(255)); + None +} + +/// A frame was presented. +#[inline] +pub(crate) fn frame() { + if on() { + FRAMES.fetch_add(1, Relaxed); + } +} + +// --------------------------------------------------------------------- +// The switches. +// --------------------------------------------------------------------- + +/// The kinds of thread followed. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Role { + Submit, + Record, + Late, + Wide, + Pipelines, + TitleMain, + Busy, +} + +impl Role { + const ALL: [Role; 7] = [ + Role::Submit, + Role::Record, + Role::Late, + Role::Wide, + Role::Pipelines, + Role::TitleMain, + Role::Busy, + ]; + + /// As `VICTORY_PROFILE_THREADS` and the stacks file name it. + fn name(self) -> &'static str { + match self { + Role::Submit => "submit", + Role::Record => "record", + Role::Late => "late-wait", + Role::Wide => "wide", + Role::Pipelines => "pipelines", + Role::TitleMain => "title-main", + Role::Busy => "busy", + } + } + + fn says(self) -> &'static str { + match self { + Role::Submit => "SUBMITTING (threads that send lists to the card: Host::submit)", + Role::Record => "RECORDING (threads that make list calls and do not submit)", + Role::Late => "LATE WAIT (victory-late-wait: settles submissions sent ahead)", + Role::Wide => "WIDE WORKERS (victory-wide-N: copies and compares of title memory)", + Role::Pipelines => "PIPELINE WORKERS (victory-pipelines-N)", + Role::TitleMain => "TITLE MAIN (title-main)", + Role::Busy => "OTHER BUSY THREADS (the busiest threads with none of the roles above)", + } + } + + /// The role of a thread we named. + fn of_name(name: &str) -> Option { + if name.starts_with("victory-pipelines-") { + Some(Role::Pipelines) + } else if name.starts_with("victory-wide-") { + Some(Role::Wide) + } else if name == "victory-late-wait" { + Some(Role::Late) + } else if name == "title-main" { + Some(Role::TitleMain) + } else { + None + } + } +} + +/// Frames kept of a stack at most (`VICTORY_PROFILE_DEPTH` asks for fewer). +const MAX_DEPTH: usize = 96; + +#[derive(Clone)] +struct Config { + /// Looks per second. + hz: u32, + /// The report. + out: PathBuf, + /// Seconds between reports. + every: f64, + /// Seconds before the first look, and after how many more the last. + after: f64, + length: Option, + /// Frames kept of a stack, from the innermost. + depth: usize, + /// Bytes copied of a stack at most. + stack: usize, + /// Threads followed at most, and of those the busy ones with no role. + most: usize, + busy: usize, + /// The roles followed, by `Role as usize`. + roles: [bool; 7], + /// Whether calls the compiler inlined are shown as frames of their own. + inline: bool, + /// Whether a thread that used no cycles since the last look is taken + /// to be where it was. + reuse: bool, + /// The share of a thread's time it may stand still for our looks + /// (0: no limit): a thread whose looks cost more is looked at less + /// often. + budget: f64, + /// Microseconds a tick is put off by at most, a different time each + /// tick ([`Pace::wait`]). + jitter: u64, +} + +fn env_number(name: &str) -> Option { + std::env::var(name).ok()?.trim().parse().ok() +} + +impl Config { + fn new(hz: u32, out: PathBuf) -> Config { + Config { + hz, + out, + every: 30.0, + after: 0.0, + length: None, + depth: 48, + stack: 128 << 10, + most: 24, + busy: 6, + roles: [true; 7], + inline: true, + reuse: true, + budget: 0.03, + jitter: 250, + } + } + + /// `VICTORY_PROFILE=1` and the switches beside it; `None` without it. + fn from_env() -> Option { + if !std::env::var_os("VICTORY_PROFILE").is_some_and(|v| v == "1") { + return None; + } + let out = std::env::var_os("VICTORY_PROFILE_OUT").map_or_else( + || std::env::temp_dir().join(format!("victory_profile_{}.txt", std::process::id())), + PathBuf::from, + ); + let hz = env_number("VICTORY_PROFILE_HZ").map_or(1000.0, |v| v.clamp(1.0, 4000.0)); + let mut config = Config::new(hz as u32, out); + let seconds = |name: &str, least: f64| env_number(name).map(|v| v.max(least)); + config.every = seconds("VICTORY_PROFILE_EVERY", 1.0).unwrap_or(config.every); + config.after = seconds("VICTORY_PROFILE_AFTER", 0.0).unwrap_or(0.0); + config.length = seconds("VICTORY_PROFILE_FOR", 1.0); + let count = |name: &str, usual: usize, most: usize| { + env_number(name).map_or(usual, |v| (v.max(0.0) as usize).min(most)) + }; + config.depth = count("VICTORY_PROFILE_DEPTH", config.depth, MAX_DEPTH).max(4); + config.stack = count("VICTORY_PROFILE_STACK_KB", 128, 1024).max(4) << 10; + config.most = count("VICTORY_PROFILE_MAX_THREADS", config.most, 64).max(1); + config.busy = count("VICTORY_PROFILE_BUSY", config.busy, 32); + config.inline = std::env::var_os("VICTORY_PROFILE_INLINE").is_none_or(|v| v != "0"); + config.reuse = std::env::var_os("VICTORY_PROFILE_REUSE").is_none_or(|v| v != "0"); + config.budget = env_number("VICTORY_PROFILE_BUDGET") + .map_or(config.budget, |v| v.clamp(0.0, 100.0) / 100.0); + config.jitter = count("VICTORY_PROFILE_JITTER_US", 250, 2000) as u64; + if let Ok(list) = std::env::var("VICTORY_PROFILE_THREADS") { + let named: Vec<&str> = list.split(',').map(str::trim).collect(); + for role in Role::ALL { + config.roles[role as usize] = named.contains(&role.name()); + } + } + Some(config) + } +} + +// --------------------------------------------------------------------- +// Samples: a tree of calls per thread. +// --------------------------------------------------------------------- + +/// A hash for small keys of ours (addresses and indices), not for +/// anything a stranger chooses. +#[derive(Default, Clone, Copy)] +struct Fast(u64); + +impl Hasher for Fast { + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + fn write_u8(&mut self, v: u8) { + self.write_u64(u64::from(v)); + } + fn write_u32(&mut self, v: u32) { + self.write_u64(u64::from(v)); + } + fn write_u64(&mut self, v: u64) { + self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x517c_c1b7_2722_0a95); + } + fn write_usize(&mut self, v: usize) { + self.write_u64(v as u64); + } + fn finish(&self) -> u64 { + self.0 + } +} + +type FastMap = HashMap>; + +/// A frame as called from its parent's: `address` is the instruction the +/// thread was at (an innermost frame) or a byte inside the call that has +/// not returned (the others), so both lie in the function they belong to. +struct Node { + parent: u32, + address: u64, + /// Of the samples that ended here: microseconds of wall clock they + /// stand for, microseconds of those the thread was on a processor (by + /// its cycle counter), and how many they were. + wall: u64, + cpu: u64, + hits: u32, +} + +/// The address of the node that stands for the frames not kept, between +/// the thread's first frame and the outermost one kept. +const CUT: u64 = 1; +/// The address of the node samples go to once the trees are full. +const FULL: u64 = 2; + +/// The calls of one thread, each sample at the node of its innermost frame. +struct Tree { + nodes: Vec, + children: FastMap<(u32, u64), u32>, +} + +impl Tree { + fn new() -> Tree { + Tree { + nodes: vec![Node { + parent: 0, + address: 0, + wall: 0, + cpu: 0, + hits: 0, + }], + children: FastMap::default(), + } + } + + fn child(&mut self, parent: u32, address: u64) -> u32 { + *self.children.entry((parent, address)).or_insert_with(|| { + self.nodes.push(Node { + parent, + address, + wall: 0, + cpu: 0, + hits: 0, + }); + self.nodes.len() as u32 - 1 + }) + } + + /// The node of a stack, `frames` from the innermost; `whole` if they + /// reach the thread's first frame. With `room` false no node is made: + /// what is new goes to the [`FULL`] node. + fn place(&mut self, frames: &[u64], whole: bool, room: bool) -> u32 { + let mut at = 0; + if !whole { + at = self.child(0, CUT); + } + for &address in frames.iter().rev() { + at = match self.children.get(&(at, address)) { + Some(&next) => next, + None if room => self.child(at, address), + None => return self.child(0, FULL), + }; + } + at + } +} + +/// The trees' nodes together, at most (56 bytes each with their index). +const MOST_NODES: usize = 1_500_000; + +// --------------------------------------------------------------------- +// Looking at a thread. +// --------------------------------------------------------------------- + +/// `GetThreadContext` and `RtlVirtualUnwind` want the context 16-byte +/// aligned, and windows-sys declares it without that alignment. +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// Zeroed bytes kept after the room for a stack's copy: what a frame's +/// unwinding reads past the copied part (a frame cut by the limit, a +/// return address that was none) is read from here. +const SLACK: usize = 2 << 20; +/// Copied of a stack that is not the thread's own (a fiber's) at most. +const FOREIGN: usize = 32 << 10; +/// What a thread needs open for [`Sampler::capture`], and to be asked +/// whether it has ended (`SYNCHRONIZE`). +const ACCESS: u32 = + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | 0x0010_0000; +/// Microseconds of processor time a waiting thread is taken to use at +/// most for being suspended and resumed (the kernel wakes it for both): +/// about 6 were measured. A thread that used no more since a look that +/// suspended it has not left its wait. +const SETTLING_US: f64 = 30.0; +/// The share of a suspension, as we time it (from asking for it to having +/// let go), that the thread really stands still: the rest is the kernel +/// reaching the thread and returning to us. Measured with threads whose +/// work is counted, eight of them always running: about 20 us of work +/// lost a look (1.8 to 2.1 % at 960 looks a second) for 25 to 28 us held. +const STOOD: f64 = 0.8; +/// A suspension counted as no longer than this in a thread's running +/// average (nanoseconds): the long ones are a thread that was not on a +/// processor when we asked, which costs it nothing. +const COST_MOST: f64 = 250_000.0; + +struct Thread { + id: u32, + handle: HANDLE, + name: String, + /// Where it started: what a thread without a name is told by. + start: u64, + role: Role, + /// Its stack's reservation: a stack pointer inside is the thread's own. + low: usize, + high: usize, + /// Its cycle counter at the last look, the node of that look, and + /// whether the thread was suspended for it. + cycles: u64, + last: Option, + stood: bool, + /// It is looked at every `every` ticks ([`Config::budget`]), next in + /// `turn` ticks; `owed` is the time since its last look + /// (microseconds), `cost` what a suspension of it takes (nanoseconds, + /// a running average). + every: u32, + turn: u32, + owed: u64, + cost: f64, + /// Bytes of its stack copied at a look; 0: all of it. Less once a + /// walk has shown how many the kept frames take. + want: usize, + tree: Tree, + /// Still running, as of the last [`Sampler::rescan`]. + alive: bool, + round: u64, + /// Looks: all, those answered without suspending it, those that + /// failed, and those whose stack did not reach its first frame. + looks: u64, + reused: u64, + missed: u64, + cut: u64, +} + +/// A thread with no role, watched for how busy it is. +struct Other { + handle: HANDLE, + cycles: u64, + name: String, + round: u64, +} + +struct Sampler { + config: Config, + me: u32, + threads: Vec, + others: FastMap, + round: u64, + scanned: Instant, + context: Box, + /// The copy of a stack: `config.stack + 16` bytes, then [`SLACK`]. + copy: *mut u8, + room: usize, + /// How far the copy has bytes that are not zero. + dirty: usize, + frames: [u64; MAX_DEPTH], + /// Cycles of the processor's counter per microsecond. + cycles_per_us: f64, + /// The cycles a waiting thread uses at most to be suspended and let + /// go again ([`SETTLING_US`]). + settling: u64, + clock: Instant, + /// The count of frames presented ([`FRAMES`]; a test's own). + presents: &'static AtomicU64, + /// The last tick, on `clock`, and the frame count then. + last: Duration, + frames_then: u64, + /// Since the start: ticks, late ones, microseconds they stand for, + /// frames presented meanwhile. + ticks: u64, + late: u64, + wall: u64, + presented: u64, + /// Suspensions: how many, their time together and the longest + /// (nanoseconds), and how many by length ([`held_class`]). + held: u64, + held_ns: u64, + held_longest: u64, + held_by: [u64; 256], + nodes: usize, + symbols: Option, +} + +impl Sampler { + fn new(config: Config) -> Sampler { + let room = config.stack + 16 + SLACK; + // SAFETY: fresh zeroed memory of ours, kept for the process's life. + let copy = unsafe { VirtualAlloc(null(), room, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!copy.is_null(), "no memory for the profiler's stack copy"); + let clock = Instant::now(); + let cycles_per_us = cycles_per_us(); + // SAFETY: a zeroed CONTEXT is valid. + let context = Box::new(Aligned(unsafe { std::mem::zeroed() })); + Sampler { + config, + // SAFETY: a plain query. + me: unsafe { GetCurrentThreadId() }, + threads: Vec::new(), + others: FastMap::default(), + round: 0, + scanned: clock, + context, + copy: copy.cast(), + room, + dirty: 0, + frames: [0; MAX_DEPTH], + cycles_per_us, + settling: (SETTLING_US * cycles_per_us) as u64, + clock, + presents: &FRAMES, + last: clock.elapsed(), + frames_then: FRAMES.load(Relaxed), + ticks: 0, + late: 0, + wall: 0, + presented: 0, + held: 0, + held_ns: 0, + held_longest: 0, + held_by: [0; 256], + nodes: 0, + symbols: None, + } + } + + /// The time under which `share` of the suspensions stayed, in + /// microseconds (to a quarter of a power of two). + fn held_within(&self, share: f64) -> f64 { + let mut left = (self.held as f64 * share) as u64; + for (class, &count) in self.held_by.iter().enumerate() { + if count > left { + // The class's upper end: its lower end as [`held_class`] + // gives it, plus its width. + let (bits, quarter) = (class / 4, class as u64 % 4); + let under = if bits < 2 { + class as u64 + 1 + } else { + (5 + quarter) << (bits - 2) + }; + return under as f64 / 1000.0; + } + left -= count; + } + self.held_longest as f64 / 1000.0 + } + + /// Time that passed while the sampler did something else (a report) is + /// nobody's: the next tick counts from now. + fn resync(&mut self) { + self.last = self.clock.elapsed(); + self.frames_then = self.presents.load(Relaxed); + } + + /// One look at every followed thread. + fn tick(&mut self) { + let now = self.clock.elapsed(); + let passed = now.saturating_sub(self.last).as_micros() as u64; + self.last = now; + let period = 1_000_000 / u64::from(self.config.hz.max(1)); + // A stall of ours is not the threads' time. + let weight = passed.min(20 * period); + self.late += u64::from(passed > 2 * period); + let frames = self.presents.load(Relaxed); + self.presented += frames.saturating_sub(self.frames_then); + self.frames_then = frames; + self.wall += weight; + self.ticks += 1; + for at in 0..self.threads.len() { + let thread = &mut self.threads[at]; + if !thread.alive { + continue; + } + // A thread looked at every few ticks: its look stands for all + // the time since its last one. + thread.owed += weight; + thread.turn = thread.turn.saturating_sub(1); + if thread.turn == 0 { + thread.turn = thread.every; + let weight = std::mem::take(&mut thread.owed); + self.look(at, weight); + } + } + } + + fn look(&mut self, at: usize, weight: u64) { + let reuse = self.config.reuse; + let thread = &mut self.threads[at]; + thread.looks += 1; + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + if unsafe { QueryThreadCycleTime(thread.handle, &mut cycles) } == 0 { + thread.missed += 1; + return; + } + let ran = cycles.saturating_sub(thread.cycles); + thread.cycles = cycles; + // It has not run since the last look: it is where it was. A + // thread that was suspended for that look ran to be suspended and + // let go, which is not running its own code. + let still = ran == 0 || thread.stood && ran <= self.settling; + let last = thread.last; + let node = match last { + Some(node) if still && reuse => { + thread.reused += 1; + thread.stood = false; + node + } + _ => { + let Some((got, held)) = self.capture(at) else { + self.threads[at].missed += 1; + self.threads[at].last = None; + return; + }; + let (frames, whole, used) = self.walk(at, got); + let room = self.nodes < MOST_NODES; + let (hz, budget) = (f64::from(self.config.hz), self.config.budget); + let deep = frames >= self.config.depth.min(MAX_DEPTH); + let thread = &mut self.threads[at]; + thread.stood = true; + // The kept frames took `used` bytes: that and a quarter more + // next time. A walk that ran out of copy first: all again. + thread.want = if deep { used + used / 4 + 1024 } else { 0 }; + // What a look costs the thread: about [`STOOD`] of the time we + // hold it (the rest is the kernel reaching it). Over the + // budget, it is looked at less often. + let held = (held as f64).min(COST_MOST); + thread.cost = if thread.cost == 0.0 { + held + } else { + thread.cost + (held - thread.cost) / 16.0 + }; + thread.every = if budget > 0.0 { + (STOOD * thread.cost * hz / 1e9 / budget) + .ceil() + .clamp(1.0, 32.0) as u32 + } else { + 1 + }; + let before = thread.tree.nodes.len(); + let node = thread.tree.place(&self.frames[..frames], whole, room); + self.nodes += thread.tree.nodes.len() - before; + thread.cut += u64::from(!whole); + node + } + }; + let cpu = ((ran as f64 / self.cycles_per_us) as u64).min(weight); + let thread = &mut self.threads[at]; + thread.last = Some(node); + let node = &mut thread.tree.nodes[node as usize]; + node.wall += weight; + node.cpu += cpu; + node.hits += 1; + } + + /// Suspends the thread, reads its registers into `self.context` and + /// copies its stack from the stack pointer up into `self.copy`, and + /// resumes it; the bytes copied, or `None` if it could not be looked + /// at (it ended). + /// + /// While the thread stands still it may hold any lock of the process + /// (the heap's, the loader's, the unwinder's tables'): nothing here + /// between the suspension and the resumption takes one or allocates. + /// The stack is read by the kernel (`ReadProcessMemory`), which fails + /// where a plain read would fault (a thread that is ending). + fn capture(&mut self, at: usize) -> Option<(usize, u64)> { + let thread = &self.threads[at]; + let (handle, low, high) = (thread.handle, thread.low, thread.high); + let context = &mut self.context.0; + context.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let limit = match thread.want { + 0 => self.config.stack, + want => want.min(self.config.stack), + }; + let began = Instant::now(); + // SAFETY: a thread of this process that is not this one; the + // context is aligned and ours; the copy has `limit + 16` bytes. + let (read, offset, got) = unsafe { + if SuspendThread(handle) == u32::MAX { + return None; + } + let read = GetThreadContext(handle, context) != 0; + let (mut offset, mut got) = (0, 0); + if read { + let rsp = context.Rsp as usize; + let want = if rsp >= low && rsp < high { + (high - rsp).min(limit) + } else { + limit.min(FOREIGN) + }; + // The copy keeps the stack's alignment: unwinding loads + // saved vector registers with aligned moves. + offset = rsp & 15; + ReadProcessMemory( + GetCurrentProcess(), + rsp as *const c_void, + self.copy.add(offset).cast(), + want, + &mut got, + ); + got = got.min(want); + } + ResumeThread(handle); + (read, offset, got) + }; + let held = began.elapsed().as_nanos() as u64; + self.held += 1; + self.held_ns += held; + self.held_longest = self.held_longest.max(held); + self.held_by[held_class(held).0] += 1; + if !read { + return None; + } + // What an earlier, longer copy left behind it. + let end = offset + got; + if end < self.dirty { + // SAFETY: inside the copy. + unsafe { self.copy.add(end).write_bytes(0, self.dirty - end) }; + } + self.dirty = end; + Some((got, held)) + } + + /// Walks the stack copied by [`Sampler::capture`] (`got` bytes from + /// the stack pointer in `self.context`) into `self.frames`, from the + /// innermost: the count, whether the thread's first frame was + /// reached, and the bytes of the copy the frames took. + /// + /// The thread runs again, so the walk reads the copy: the stack + /// pointer and every saved register that points into the copied part + /// of the stack are moved into the copy before each step (frame + /// pointers are such registers), and a step is taken only if all it + /// can read lies in the copy or the zeroes after it ([`frame_fits`]). + fn walk(&mut self, at: usize, got: usize) -> (usize, bool, usize) { + let (low, high) = (self.threads[at].low, self.threads[at].high); + let depth = self.config.depth.min(MAX_DEPTH); + let context = &mut self.context.0; + let lo = context.Rsp as usize; + let start = self.copy as usize + (lo & 15); + let end = start + got; + let limit = self.copy as usize + self.room; + let top = if lo >= low && lo < high { + high + } else { + lo + got + }; + let mut clipped = false; + self.frames[0] = context.Rip; + let mut frames = 1; + let (mut blind, mut last) = (0, 0); + while frames < depth { + // Into the copy: what points into the stack as it was. + for register in [ + &mut context.Rsp, + &mut context.Rbx, + &mut context.Rbp, + &mut context.Rsi, + &mut context.Rdi, + &mut context.R12, + &mut context.R13, + &mut context.R14, + &mut context.R15, + ] { + let value = *register as usize; + if value >= lo && value < top { + if value - lo < got { + *register = (start + (value - lo)) as u64; + } else { + // Above what was copied: reads there find zeroes. + *register = end as u64; + clipped = true; + } + } + } + let rsp = context.Rsp as usize; + // Out of the copy, or not upwards: the walk ends. + if rsp < start || rsp + 8 > end || rsp <= last { + break; + } + last = rsp; + let mut image = 0; + // SAFETY: looks up the unwind data covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // Code without unwind data is a leaf function (the + // system's call stubs are): its return address is at + // `rsp`. Twice in a row it is no stack of calls. + blind += 1; + if blind > 2 { + break; + } + // SAFETY: `rsp..rsp + 8` is inside the copy. + context.Rip = unsafe { (rsp as *const u64).read_unaligned() }; + context.Rsp += 8; + } else { + blind = 0; + // SAFETY: `entry` is `image`'s, as just looked up. + if !unsafe { frame_fits(image, entry.cast(), context, start, end, limit) } { + break; + } + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our + // aligned copy, and what the step reads is in our copy of + // the stack (checked above). + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; + } + if context.Rip == 0 { + // The first frame's caller: none. (Zeroes read above a + // clipped copy look the same.) + return (frames, !clipped, last + 8 - start); + } + self.frames[frames] = context.Rip - 1; + frames += 1; + } + (frames, false, (last + 8).saturating_sub(start)) + } + + /// Follows the thread `id` as `role`; `handle`, if not null, is open + /// with [`ACCESS`] and becomes ours. + fn follow(&mut self, id: u32, role: Role, handle: HANDLE, name: Option) { + if let Some(thread) = self.threads.iter_mut().find(|t| t.alive && t.id == id) { + // Seen doing more than it was followed for. + if (role as usize) < thread.role as usize { + thread.role = role; + } + thread.round = self.round; + if !handle.is_null() { + // SAFETY: ours, as the caller says. + unsafe { CloseHandle(handle) }; + } + return; + } + let handle = if handle.is_null() { + // SAFETY: opens a thread of this process by its id. + unsafe { OpenThread(ACCESS, 0, id) } + } else { + handle + }; + if handle.is_null() { + return; + } + if self.threads.iter().filter(|t| t.alive).count() >= self.config.most { + // SAFETY: opened above or given to us. + unsafe { CloseHandle(handle) }; + return; + } + let (low, high) = stack_of(handle); + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + unsafe { QueryThreadCycleTime(handle, &mut cycles) }; + self.threads.push(Thread { + id, + handle, + name: name.unwrap_or_else(|| thread_name(handle)), + start: start_of(handle), + role, + low, + high, + cycles, + last: None, + stood: false, + every: 1, + turn: 1, + owed: 0, + cost: 0.0, + want: 0, + tree: Tree::new(), + alive: true, + round: self.round, + looks: 0, + reused: 0, + missed: 0, + cut: 0, + }); + } + + /// Finds the threads to follow: those the hooks have seen, those with + /// a name of ours, and the busiest of the rest; and notes the ones + /// that ended. + fn rescan(&mut self) { + let passed = self.scanned.elapsed(); + self.scanned = Instant::now(); + self.round += 1; + let wanted = self.config.roles; + for known in &KNOWN_THREADS { + let id = known.thread.load(Relaxed); + if id == 0 || id == self.me { + continue; + } + let role = if known.seen[Seen::Submit as usize].load(Relaxed) >= SUBMITS { + Role::Submit + } else if known.seen[Seen::Record as usize].load(Relaxed) >= LIST_CALLS { + Role::Record + } else { + continue; + }; + if wanted[role as usize] { + self.follow(id, role, null_mut(), None); + } + } + // Every thread of the process: (cycles since the last scan, id) of + // those with no role. + let mut busy: Vec<(u64, u32)> = Vec::new(); + let mut previous: HANDLE = null_mut(); + loop { + let mut next = null_mut(); + // SAFETY: our own process; `previous` is null or a thread + // handle the last pass gave us, closed once passed on. + let status = unsafe { + let status = NtGetNextThread( + GetCurrentProcess(), + previous, + THREAD_QUERY_LIMITED_INFORMATION, + 0, + 0, + &mut next, + ); + if !previous.is_null() { + CloseHandle(previous); + } + status + }; + if status != 0 || next.is_null() { + break; + } + previous = next; + // SAFETY: a thread handle just opened. + let id = unsafe { GetThreadId(next) }; + if id == 0 || id == self.me { + continue; + } + if let Some(thread) = self.threads.iter_mut().find(|t| t.alive && t.id == id) { + thread.round = self.round; + continue; + } + let round = self.round; + let other = match self.others.entry(id) { + std::collections::hash_map::Entry::Occupied(o) => o.into_mut(), + std::collections::hash_map::Entry::Vacant(v) => { + // SAFETY: opens a thread of this process by its id. + let handle = unsafe { OpenThread(ACCESS, 0, id) }; + if handle.is_null() { + continue; + } + let mut cycles = 0; + // SAFETY: a thread handle of ours, a valid out pointer. + unsafe { QueryThreadCycleTime(handle, &mut cycles) }; + v.insert(Other { + handle, + cycles, + name: String::new(), + round, + }) + } + }; + other.round = round; + if other.name.is_empty() { + other.name = thread_name(other.handle); + } + if other.name == "victory-profile" { + continue; + } + // SAFETY: a thread handle of ours, opened with `SYNCHRONIZE`. + if unsafe { WaitForSingleObject(other.handle, 0) } == 0 { + continue; + } + if let Some(role) = Role::of_name(&other.name) { + if wanted[role as usize] + && let Some(other) = self.others.remove(&id) + { + self.follow(id, role, other.handle, Some(other.name)); + } + continue; + } + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + unsafe { QueryThreadCycleTime(other.handle, &mut cycles) }; + busy.push((cycles.saturating_sub(other.cycles), id)); + other.cycles = cycles; + } + // Threads that ended: no longer looked at; what was sampled stays. + // (A thread we hold a handle to is still listed after its end.) + let round = self.round; + // SAFETY: a thread handle of ours, opened with `SYNCHRONIZE`. + let ended = |handle: HANDLE| unsafe { WaitForSingleObject(handle, 0) } == 0; + for thread in self + .threads + .iter_mut() + .filter(|t| t.alive && (t.round != round || ended(t.handle))) + { + thread.alive = false; + // SAFETY: ours. + unsafe { CloseHandle(thread.handle) }; + thread.handle = null_mut(); + for known in &KNOWN_THREADS { + let _ = known + .thread + .compare_exchange(thread.id, 0, Relaxed, Relaxed); + } + } + self.others.retain(|_, other| { + let gone = other.round != round || ended(other.handle); + if gone { + // SAFETY: ours. + unsafe { CloseHandle(other.handle) }; + } + !gone + }); + // The busiest of the rest: a quarter of a processor or more. + if wanted[Role::Busy as usize] { + let least = (0.25 * passed.as_micros() as f64 * self.cycles_per_us) as u64; + busy.sort_unstable_by(|a, b| b.cmp(a)); + for (ran, id) in busy { + let followed = self + .threads + .iter() + .filter(|t| t.alive && t.role == Role::Busy) + .count(); + if ran < least.max(1) || followed >= self.config.busy { + break; + } + if let Some(other) = self.others.remove(&id) { + self.follow(id, Role::Busy, other.handle, Some(other.name)); + } + } + } + } +} + +/// Whether unwinding one frame of the function `entry` of the image at +/// `image` from `context` reads only our copy of a stack (`start..end`) +/// and the zeroes after it (to `limit`): the stack pointer, and the frame +/// pointer if the function has set one up, must lie in the copy, and what +/// the function's unwind codes take off the stack must fit in the zeroes. +/// +/// `RtlVirtualUnwind` trusts the registers it is given. Ours come from a +/// thread stopped anywhere, and a return address may be none (code +/// without unwind data in the middle of a stack): a frame pointer that +/// points nowhere would be read through. +/// +/// # Safety +/// `entry` is the function table entry of `image` for `context.Rip`. +unsafe fn frame_fits( + image: u64, + entry: *const [u32; 3], + context: &CONTEXT, + start: usize, + end: usize, + limit: usize, +) -> bool { + // SAFETY: the caller's entry, and the unwind data it names in its + // loaded image: a header of four bytes, `count` two-byte codes, and + // after them (made even) the entry of the function this one is a + // part of, if the header says so. + unsafe { + let [begin, finish, mut data] = entry.read_unaligned(); + let at = context + .Rip + .wrapping_sub(image) + .wrapping_sub(u64::from(begin)); + // The frame register the function itself names (its first part). + let mut pointer = 0; + // Bytes above the frame's base that unwinding may read: the + // return address, a machine frame's tail. + let mut reach = 64usize; + // Bases other than the stack pointer: frame pointers set up. + let mut bases = [0usize; 4]; + let mut based = 0; + for part in 0..8 { + if data & 1 != 0 { + return false; + } + let info = (image + u64::from(data)) as *const u8; + let [version, _prolog, count, frame] = info.cast::<[u8; 4]>().read(); + if !matches!(version & 7, 1 | 2) { + return false; + } + let chained = version >> 3 & 4 != 0; + if part == 0 { + pointer = frame & 15; + } + let codes = info.add(4); + let count = usize::from(count); + let slot = |i: usize| codes.add(2 * i).cast::().read_unaligned(); + let mut i = 0; + let (mut found, mut set) = (false, false); + while i < count { + let [offset, op] = codes.add(2 * i).cast::<[u8; 2]>().read(); + let (op, op_info) = (op & 15, usize::from(op >> 4)); + i += match op { + // A register pushed. + 0 => { + reach += 8; + 1 + } + // A large allocation: its size in the next one or two slots. + 1 if op_info == 0 => { + reach += usize::from(slot(i + 1)) * 8; + 2 + } + 1 => { + reach += usize::from(slot(i + 1)) | usize::from(slot(i + 2)) << 16; + 3 + } + // A small allocation. + 2 => { + reach += op_info * 8 + 8; + 1 + } + // The frame pointer set: done already if the thread is + // past that instruction, or in a later part of the function. + 3 => { + found = true; + set = part > 0 || chained || at >= u64::from(offset); + 1 + } + // Registers saved in the frame (near, far), an epilogue + // note and a spare code, vector registers saved. + 4 | 8 => 2, + 5 | 9 => 3, + 6 => 1, + 7 => 2, + // A machine frame. + 10 => { + reach += 48; + 1 + } + _ => return false, + }; + } + if frame & 15 != 0 && (set || !found || part > 0 || chained) { + let register = gpr(context, frame & 15) as usize; + let back = usize::from(frame >> 4) * 16; + if register < start + back || register > end || based == bases.len() { + return false; + } + bases[based] = register - back; + based += 1; + } + if !chained { + let rsp = context.Rsp as usize; + let code = image + u64::from(finish) - context.Rip; + return rsp >= start + && rsp < end + && reach <= SLACK + && rsp + reach <= limit + && bases[..based].iter().all(|base| base + reach <= limit) + && epilogue_fits(context, code as usize, pointer, start, end); + } + let parent = codes + .add(2 * ((count + 1) & !1)) + .cast::<[u32; 3]>() + .read_unaligned(); + data = parent[2]; + } + false + } +} + +/// Whether the instructions at `context.Rip` (`code` bytes of them are the +/// function's), if the unwinder takes them for the end of a function, +/// leave the stack pointer inside our copy of a stack (`start..end`). +/// `pointer` is the function's frame register (0: none). +/// +/// Where a thread stands at a function's last instructions, the +/// unwinder does not use the unwind codes: it runs those instructions +/// itself, an `add rsp, n` or a `lea rsp, [frame register + n]`, then the +/// `pop`s, then the return. An address that is no instruction's start can +/// read as a `pop rsp`, or as an `add` of any number: this reads the +/// bytes as the unwinder does and refuses what would take the stack +/// pointer out of the copy. It takes a little more for a function's end +/// than the unwinder does (any jump after the `pop`s, wherever it goes). +/// +/// # Safety +/// `code` bytes at `context.Rip` are readable. +unsafe fn epilogue_fits( + context: &CONTEXT, + code: usize, + pointer: u8, + start: usize, + end: usize, +) -> bool { + let rip = context.Rip as *const u8; + // Past the function's end reads as a breakpoint: nothing of an epilogue. + let byte = |i: usize| { + if i < code { + // SAFETY: inside the `code` bytes the caller says are readable. + unsafe { rip.add(i).read() } + } else { + 0xcc + } + }; + let number = |i: usize| i32::from_le_bytes([byte(i), byte(i + 1), byte(i + 2), byte(i + 3)]); + let moved = |from: u64, by: i32| (from as usize).wrapping_add(by as isize as usize); + let mut rsp = context.Rsp as usize; + let mut at = 0; + if byte(0) == 0x48 && byte(1) == 0x83 && byte(2) == 0xc4 { + // add rsp, n (a byte). + rsp = moved(context.Rsp, i32::from(byte(3) as i8)); + at = 4; + } else if byte(0) == 0x48 && byte(1) == 0x81 && byte(2) == 0xc4 { + // add rsp, n. + rsp = moved(context.Rsp, number(3)); + at = 7; + } else if byte(0) & 0xfe == 0x48 && byte(1) == 0x8d { + // lea rsp, [register + n]: taken only from the frame register. + let register = (byte(0) & 1) << 3 | byte(2) & 7; + let (near, far) = (byte(2) & 0xf8 == 0x60, byte(2) & 0xf8 == 0xa0); + if register != 0 && register == pointer && (near || far) { + let by = if near { + i32::from(byte(3) as i8) + } else { + number(3) + }; + rsp = moved(gpr(context, register), by); + at = if near { 4 } else { 7 }; + } + } + // The `pop`s. + let (mut pops, mut pops_rsp) = (0, false); + loop { + let (op, rex) = (byte(at), byte(at) & 0xf0 == 0x40); + let register = if rex { byte(at + 1) } else { op }; + if register & 0xf8 != 0x58 || pops == 64 { + break; + } + pops_rsp |= register & 7 == 4 && !(rex && op & 1 != 0); + at += if rex { 2 } else { 1 }; + pops += 1; + } + // A return or a jump: only then are the instructions before it run. + let leaves = matches!(byte(at), 0xc3 | 0xc2 | 0xeb | 0xe9) + || byte(at) == 0xf3 && byte(at + 1) == 0xc3 + || byte(at) == 0xff && byte(at + 1) == 0x25 + || byte(at) & 0xf0 == 0x40 && byte(at + 1) == 0xff && byte(at + 2) & 0x38 == 0x20; + !leaves || (!pops_rsp && pops < 64 && rsp >= start && rsp + 8 * (pops + 1) <= end) +} + +/// The class of a time in nanoseconds: four to a power of two (the +/// index), and the class's lower end. +fn held_class(ns: u64) -> (usize, u64) { + if ns < 4 { + return (ns as usize, ns); + } + let bits = 63 - ns.leading_zeros() as usize; + let quarter = ns >> (bits - 2) & 3; + (bits * 4 + quarter as usize, (4 + quarter) << (bits - 2)) +} + +/// The general register numbered `n` as unwind data numbers them. +fn gpr(context: &CONTEXT, n: u8) -> u64 { + match n & 15 { + 0 => context.Rax, + 1 => context.Rcx, + 2 => context.Rdx, + 3 => context.Rbx, + 4 => context.Rsp, + 5 => context.Rbp, + 6 => context.Rsi, + 7 => context.Rdi, + 8 => context.R8, + 9 => context.R9, + 10 => context.R10, + 11 => context.R11, + 12 => context.R12, + 13 => context.R13, + 14 => context.R14, + _ => context.R15, + } +} + +/// The processor counter's cycles per microsecond, measured. +fn cycles_per_us() -> f64 { + let began = Instant::now(); + // SAFETY: reads the processor's time stamp counter. + let from = unsafe { std::arch::x86_64::_rdtsc() }; + std::thread::sleep(Duration::from_millis(20)); + // SAFETY: as above. + let cycles = unsafe { std::arch::x86_64::_rdtsc() }.wrapping_sub(from); + (cycles as f64 / began.elapsed().as_micros().max(1) as f64).max(1.0) +} + +/// The reservation of a thread's stack, lowest address and end; (0, 0) if +/// it cannot be asked (the thread ended). +fn stack_of(thread: HANDLE) -> (usize, usize) { + /// `THREAD_BASIC_INFORMATION` (ntddk). + #[repr(C)] + struct Basic { + exit_status: i32, + teb: usize, + client_id: [usize; 2], + affinity: usize, + priority: i32, + base_priority: i32, + } + let mut basic = Basic { + exit_status: 0, + teb: 0, + client_id: [0; 2], + affinity: 0, + priority: 0, + base_priority: 0, + }; + // SAFETY: writes `basic`, whose layout and size are the system's. + let status = unsafe { + NtQueryInformationThread( + thread, + 0, + (&raw mut basic).cast(), + size_of::() as u32, + null_mut(), + ) + }; + if status != 0 || basic.teb == 0 { + return (0, 0); + } + // The thread's block: the stack's end at +8, the start of its + // reservation at +0x1478. Read by the kernel: the thread may end. + let word = |at: usize| { + let (mut value, mut got) = (0usize, 0); + // SAFETY: reads eight bytes into `value`; fails if they are gone. + let read = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + at as *const c_void, + (&raw mut value).cast(), + 8, + &mut got, + ) + }; + if read != 0 && got == 8 { value } else { 0 } + }; + let (high, low) = (word(basic.teb + 8), word(basic.teb + 0x1478)); + if low != 0 && low < high { + (low, high) + } else { + (0, 0) + } +} + +/// The address a thread started at; 0 if it cannot be asked. +fn start_of(thread: HANDLE) -> u64 { + let mut start = 0u64; + // SAFETY: writes one pointer-sized start address + // (`ThreadQuerySetWin32StartAddress` is 9). + unsafe { + NtQueryInformationThread(thread, 9, (&raw mut start).cast(), 8, null_mut()); + } + start +} + +fn thread_name(thread: HANDLE) -> String { + let mut text: *mut u16 = null_mut(); + // SAFETY: the system allocates the string; we free it with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut text) < 0 || text.is_null() { + return String::new(); + } + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + let name = String::from_utf16_lossy(std::slice::from_raw_parts(text, len)); + LocalFree(text.cast()); + name + } +} + +// --------------------------------------------------------------------- +// Names, found when a report is written. +// --------------------------------------------------------------------- + +/// Whose code a frame is. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +enum Kind { + Ours = 0, + Driver = 1, + Direct3d = 2, + System = 3, + Title = 4, + Other = 5, +} + +const KINDS: [&str; 6] = [ + "ours", + "graphics driver", + "d3d12 / dxgi", + "ntdll + kernel", + "title", + "other", +]; + +/// The kind of a module by its file name (lower case). +fn kind_of(file: &str, ours: bool) -> Kind { + let starts = |list: &[&str]| list.iter().any(|p| file.starts_with(p)); + if ours { + Kind::Ours + } else if file.starts_with("victory-image-") { + Kind::Title + } else if starts(&["nv", "amd", "ati", "igd", "igc", "ig1", "ig9", "ig7", "ig8"]) { + Kind::Driver + } else if starts(&["d3d", "dxgi", "dxcore", "dxil", "dcomp", "dwmapi"]) { + Kind::Direct3d + } else if matches!( + file, + "ntdll.dll" | "kernelbase.dll" | "kernel32.dll" | "win32u.dll" + ) { + Kind::System + } else { + Kind::Other + } +} + +struct Module { + base: u64, + end: u64, + /// What its frames are named by: `title`, or its file name. + label: String, + kind: Kind, +} + +/// A function as the report names it. +struct Func { + name: String, + /// Of ours, but the language's runtime (`std::`, `core::`, `alloc::`). + runtime: bool, + /// A call that waits ([`waits`]). + wait: bool, +} + +/// What an address is. +struct Resolved { + /// The functions it is in, outermost first: more than one where the + /// compiler inlined calls (ours only). + funcs: Box<[u32]>, + kind: Option, + /// Its source line (ours), an index into `Symbols::lines`. + line: Option, +} + +type SymFromAddr = unsafe extern "system" fn(HANDLE, u64, *mut u64, *mut SYMBOL_INFOW) -> i32; +type SymFromInline = + unsafe extern "system" fn(HANDLE, u64, u32, *mut u64, *mut SYMBOL_INFOW) -> i32; +type SymInlineQuery = + unsafe extern "system" fn(HANDLE, u64, u32, u64, u64, *mut u32, *mut u32) -> i32; +type SymLine = unsafe extern "system" fn(HANDLE, u64, *mut u32, *mut IMAGEHLP_LINEW64) -> i32; +type SymLineInline = + unsafe extern "system" fn(HANDLE, u64, u32, u64, *mut u32, *mut IMAGEHLP_LINEW64) -> i32; + +/// The system's symbol library (`dbghelp.dll`), loaded when the first +/// report is written: a build that does not profile does not load it. +struct DbgHelp { + process: HANDLE, + refresh: unsafe extern "system" fn(HANDLE) -> i32, + from_addr: SymFromAddr, + line: Option, + module: Option i32>, + /// Inlined calls: how many at an address, their first context, a name + /// and a line by context. + inline: Option<( + unsafe extern "system" fn(HANDLE, u64) -> u32, + SymInlineQuery, + SymFromInline, + Option, + )>, +} + +/// A symbol with room for its name. +#[repr(C)] +struct Symbol { + info: SYMBOL_INFOW, + name: [u16; 1024], +} + +impl DbgHelp { + fn open() -> Option { + // SAFETY: loads the system's own dbghelp.dll and looks its + // functions up by name; each is called with the signature the + // system documents for it. The library's "process" is a second + // handle to ours, so its tables are not the ones Rust's own + // backtraces set up for the plain handle. + unsafe { + let library = LoadLibraryExA( + c"dbghelp.dll".as_ptr().cast(), + null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ); + if library.is_null() { + return None; + } + macro_rules! find { + ($name:literal) => { + GetProcAddress(library, $name.as_ptr().cast()).map(|f| std::mem::transmute(f)) + }; + } + let get_options: unsafe extern "system" fn() -> u32 = find!(c"SymGetOptions")?; + let set_options: unsafe extern "system" fn(u32) -> u32 = find!(c"SymSetOptions")?; + let initialize: unsafe extern "system" fn(HANDLE, *const u16, i32) -> i32 = + find!(c"SymInitializeW")?; + let refresh = find!(c"SymRefreshModuleList")?; + let from_addr = find!(c"SymFromAddrW")?; + let inline = match ( + find!(c"SymAddrIncludeInlineTrace"), + find!(c"SymQueryInlineTrace"), + find!(c"SymFromInlineContextW"), + ) { + (Some(count), Some(query), Some(name)) => { + Some((count, query, name, find!(c"SymGetLineFromInlineContextW"))) + } + _ => None, + }; + let mut process = null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, me, me, &mut process, 0, 0, DUPLICATE_SAME_ACCESS) == 0 { + return None; + } + // Names undecorated, lines loaded, a module's symbols read + // when first asked for, no dialogs. Symbols are looked for + // where the image says and beside our executable only: no + // symbol server is asked (`_NT_SYMBOL_PATH` is not used when + // a path is given). + const UNDNAME: u32 = 0x2; + const DEFERRED_LOADS: u32 = 0x4; + const LOAD_LINES: u32 = 0x10; + const FAIL_CRITICAL_ERRORS: u32 = 0x200; + const NO_PROMPTS: u32 = 0x80000; + set_options( + get_options() + | UNDNAME + | DEFERRED_LOADS + | LOAD_LINES + | FAIL_CRITICAL_ERRORS + | NO_PROMPTS, + ); + let folder = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|p| p.to_path_buf())) + .unwrap_or_default(); + let path: Vec = folder + .to_string_lossy() + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + if initialize(process, path.as_ptr(), 1) == 0 { + CloseHandle(process); + return None; + } + Some(DbgHelp { + process, + refresh, + from_addr, + line: find!(c"SymGetLineFromAddrW64"), + module: find!(c"SymGetModuleInfoW64"), + inline, + }) + } + } + + /// A symbol's name and address from a lookup that fills `symbol`. + fn named(lookup: impl FnOnce(*mut SYMBOL_INFOW) -> i32) -> Option<(String, u64)> { + // SAFETY: a zeroed symbol is valid; its header says how much room + // follows for the name, and the name read is inside that room. + unsafe { + let mut symbol: Box = Box::new(std::mem::zeroed()); + symbol.info.SizeOfStruct = size_of::() as u32; + symbol.info.MaxNameLen = symbol.name.len() as u32; + // The whole of it: the name runs on past the header. + let whole = (&raw mut *symbol).cast::(); + if lookup(whole) == 0 { + return None; + } + let len = ((*whole).NameLen as usize).min(symbol.name.len()); + let name = whole + .cast::() + .add(std::mem::offset_of!(SYMBOL_INFOW, Name)) + .cast::(); + let text = std::slice::from_raw_parts(name, len); + let end = text.iter().position(|&c| c == 0).unwrap_or(len); + Some((String::from_utf16_lossy(&text[..end]), (*whole).Address)) + } + } + + /// The symbol at or before `address`: its name and its own address. + fn symbol(&self, address: u64) -> Option<(String, u64)> { + let mut displacement = 0; + // SAFETY: the library's own call with a symbol of ours to fill. + Self::named(|symbol| unsafe { + (self.from_addr)(self.process, address, &mut displacement, symbol) + }) + } + + /// The functions `address` is in, outermost first (the calls the + /// compiler inlined there, if `inlined`), and the context of the + /// innermost for [`DbgHelp::line`]. + fn functions(&self, address: u64, inlined: bool) -> (Vec, Option) { + if inlined && let Some((count, query, name, _)) = self.inline { + // SAFETY: the library's own calls, as documented: the count + // of inlined calls at an address, the context of the first, + // then a name per context; the last context is the function + // itself. + unsafe { + let inlines = count(self.process, address); + let (mut first, mut index) = (0, 0); + if inlines > 0 + && query( + self.process, + address, + 0, + address, + address, + &mut first, + &mut index, + ) != 0 + { + let mut names: Vec = (first..=first + inlines) + .filter_map(|context| { + let mut displacement = 0; + Self::named(|symbol| { + name(self.process, address, context, &mut displacement, symbol) + }) + }) + .map(|(name, _)| name) + .collect(); + if !names.is_empty() { + names.reverse(); + return (names, Some(first)); + } + } + } + } + ( + self.symbol(address) + .into_iter() + .map(|(name, _)| name) + .collect(), + None, + ) + } + + /// The source file and line of `address` (of the inlined call with + /// `context`, if any). + fn line(&self, address: u64, context: Option) -> Option<(String, u32)> { + // SAFETY: the library's own calls with a line of ours to fill; + // the file name it points to is a string of its own. + unsafe { + let mut line: IMAGEHLP_LINEW64 = std::mem::zeroed(); + line.SizeOfStruct = size_of::() as u32; + let mut displacement = 0; + let found = match (context, self.inline.and_then(|i| i.3)) { + (Some(context), Some(by_context)) => { + by_context( + self.process, + address, + context, + 0, + &mut displacement, + &mut line, + ) != 0 + } + _ => false, + } || self.line.is_some_and(|by_address| { + by_address(self.process, address, &mut displacement, &mut line) != 0 + }); + if !found || line.FileName.is_null() { + return None; + } + let len = (0..1024) + .take_while(|&i| *line.FileName.add(i) != 0) + .count(); + let file = String::from_utf16_lossy(std::slice::from_raw_parts(line.FileName, len)); + Some((file, line.LineNumber)) + } + } + + /// Whether the module at `base` has its symbols from a PDB, and what + /// the library says it loaded. + fn has_pdb(&self, base: u64) -> (bool, String) { + let Some(module) = self.module else { + return (false, String::new()); + }; + // SAFETY: the library's own call with a sized structure to fill. + unsafe { + let mut info: Box = Box::new(std::mem::zeroed()); + info.SizeOfStruct = size_of::() as u32; + if module(self.process, base, &mut *info) == 0 { + return (false, String::new()); + } + let text = |chars: &[u16]| { + let end = chars.iter().position(|&c| c == 0).unwrap_or(chars.len()); + String::from_utf16_lossy(&chars[..end]) + }; + // SymPdb is 3 and SymDia 7. + (matches!(info.SymType, 3 | 7), text(&info.LoadedPdbName)) + } + } +} + +/// The start of the function `address` is in, by its image's unwind data +/// (the first part's, for a function in several); `None` for code that +/// has none. +fn function_start(address: u64) -> Option { + let mut image = 0; + // SAFETY: looks up the unwind data covering `address`, if any, and + // reads it in its loaded image: a part of a function names the entry + // of the function it belongs to after its codes. + unsafe { + let entry = RtlLookupFunctionEntry(address, &mut image, null_mut()); + if entry.is_null() { + return None; + } + let mut entry = entry.cast::<[u32; 3]>().read_unaligned(); + for _ in 0..8 { + if entry[2] & 1 != 0 { + break; + } + let info = (image + u64::from(entry[2])) as *const u8; + let [version, _, count, _] = info.cast::<[u8; 4]>().read(); + if version >> 3 & 4 == 0 { + break; + } + let after = info.add(4 + 2 * ((usize::from(count) + 1) & !1)); + entry = after.cast::<[u32; 3]>().read_unaligned(); + } + Some(image + u64::from(entry[0])) + } +} + +/// Whether a thread whose innermost frame is `name` waits there: the +/// kernel's waits, by their names in ntdll and win32u (`Nt` or `Zw`). +fn waits(name: &str) -> bool { + let function = name.rsplit('!').next().unwrap_or(name); + let Some(call) = function + .strip_prefix("Nt") + .or_else(|| function.strip_prefix("Zw")) + else { + return false; + }; + [ + "WaitFor", + "DelayExecution", + "RemoveIoCompletion", + "SignalAndWait", + "UserMsgWaitForMultipleObjects", + "UserGetMessage", + "UserWaitMessage", + "GdiDdDDIWaitFor", + ] + .iter() + .any(|wait| call.starts_with(wait)) +} + +/// What kind of wait the frames between a waiting call and the function +/// of ours that waited make it. +fn wait_kind(path: &[&str]) -> &'static str { + let has = |what: &str| path.iter().any(|name| name.contains(what)); + if has("SleepConditionVariable") || has("Condvar") { + "condition variable" + } else if has("SRWLock") { + "lock (SRW)" + } else if has("CriticalSection") { + "lock (critical section)" + } else if has("Mutex") || has("RwLock") || has("Once") { + "lock (ours)" + } else if has("park") { + "parked" + } else if has("Sleep") || has("sleep") || has("DelayExecution") { + "sleep" + } else if has("GdiDdDDIWaitFor") { + "graphics kernel" + } else if has("WaitOnAddress") || has("WaitForAlertByThreadId") { + "wait on address" + } else if has("IoCompletion") || has("GetQueuedCompletionStatus") { + "I/O completion" + } else if has("MsgWait") || has("GetMessage") || has("WaitMessage") { + "window messages" + } else if has("WaitForMultipleObjects") || has("WaitForSingleObject") { + "event or handle" + } else { + "other wait" + } +} + +struct Symbols { + dbghelp: Option, + inline: bool, + /// Loaded modules by base, as of the report being written. + modules: Vec, + /// Whether our executable's names come from its PDB, and which. + pdb: (bool, String), + funcs: Vec, + by_name: HashMap, + lines: Vec, + by_line: HashMap, + resolved: Vec, + by_address: FastMap, +} + +impl Symbols { + fn new(inline: bool) -> Symbols { + Symbols { + dbghelp: DbgHelp::open(), + inline, + modules: Vec::new(), + pdb: (false, String::new()), + funcs: Vec::new(), + by_name: HashMap::new(), + lines: Vec::new(), + by_line: HashMap::new(), + resolved: Vec::new(), + by_address: FastMap::default(), + } + } + + /// Lists the loaded modules anew (a report's first step). + fn refresh(&mut self) { + // SAFETY: plain queries of our own process with sized buffers. + unsafe { + if let Some(dbghelp) = &self.dbghelp { + (dbghelp.refresh)(dbghelp.process); + } + let me = GetCurrentProcess(); + let mut handles: Vec = vec![null_mut(); 2048]; + let mut bytes = 0; + let size = (handles.len() * size_of::()) as u32; + if K32EnumProcessModules(me, handles.as_mut_ptr(), size, &mut bytes) == 0 { + return; + } + handles.truncate(bytes as usize / size_of::()); + let exe = GetModuleHandleW(null()); + let mut modules = Vec::with_capacity(handles.len()); + for handle in handles { + let mut info = MODULEINFO { + lpBaseOfDll: null_mut(), + SizeOfImage: 0, + EntryPoint: null_mut(), + }; + if K32GetModuleInformation(me, handle, &mut info, size_of::() as u32) + == 0 + { + continue; + } + let mut path = [0u16; 520]; + let len = GetModuleFileNameW(handle, path.as_mut_ptr(), path.len() as u32); + let path = String::from_utf16_lossy(&path[..len as usize]); + let file = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_owned(); + let kind = kind_of(&file.to_ascii_lowercase(), handle == exe); + let base = handle as u64; + modules.push(Module { + base, + end: base + u64::from(info.SizeOfImage), + label: file, + kind, + }); + } + modules.sort_by_key(|m| m.base); + // The title's images are named by their content: the largest + // is the title itself, the others its libraries. + let largest = modules + .iter() + .filter(|m| m.kind == Kind::Title) + .map(|m| m.end - m.base) + .max(); + for module in modules.iter_mut().filter(|m| m.kind == Kind::Title) { + module.label = if Some(module.end - module.base) == largest { + "title".to_owned() + } else { + let hash = module.label.trim_start_matches("victory-image-"); + format!("title-{}", &hash[..hash.len().min(6)]) + }; + } + self.modules = modules; + if let Some(dbghelp) = &self.dbghelp + && !self.pdb.0 + { + // The executable's symbols are read when first asked for. + dbghelp.symbol(function_start as *const () as u64); + self.pdb = dbghelp.has_pdb(exe as u64); + } + } + } + + fn func(&mut self, name: String, kind: Option) -> u32 { + if let Some(&at) = self.by_name.get(&name) { + return at; + } + // (By the name before its type arguments: a closure of ours is one.) + let own_name = name.split('<').next().unwrap_or(&name); + let runtime = kind == Some(Kind::Ours) + && [ + "std::", "core::", "alloc::", "__rust", "__chkstk", "mem", "str", + ] + .iter() + .any(|p| own_name.starts_with(p)); + self.funcs.push(Func { + wait: waits(&name), + name: name.clone(), + runtime, + }); + self.by_name.insert(name, self.funcs.len() as u32 - 1); + self.funcs.len() as u32 - 1 + } + + /// What `address` is, as an index into `self.resolved`. + fn resolve(&mut self, address: u64) -> u32 { + if let Some(&at) = self.by_address.get(&address) { + return at; + } + let resolved = self.look_up(address); + self.resolved.push(resolved); + let at = self.resolved.len() as u32 - 1; + self.by_address.insert(address, at); + at + } + + fn look_up(&mut self, address: u64) -> Resolved { + let marker = match address { + CUT => Some("[frames not kept]"), + FULL => Some("[samples after the trees were full]"), + _ => None, + }; + if let Some(name) = marker { + let func = self.func(name.to_owned(), None); + return Resolved { + funcs: Box::new([func]), + kind: None, + line: None, + }; + } + let at = self.modules.partition_point(|m| m.base <= address); + let module = at + .checked_sub(1) + .map(|at| &self.modules[at]) + .filter(|m| address < m.end); + let Some(module) = module else { + let func = self.func("[code in no loaded module]".to_owned(), Some(Kind::Other)); + return Resolved { + funcs: Box::new([func]), + kind: Some(Kind::Other), + line: None, + }; + }; + let (base, kind, label) = (module.base, module.kind, module.label.clone()); + let start = function_start(address); + // By the function's start in its module: what code with no names + // (the title, the driver) is told apart by. + let plain = || match start { + Some(start) => format!("{label}+{:#x}", start - base), + None => format!("{label}+{:#x}", (address - base) & !15), + }; + let mut line = None; + let names = match (&self.dbghelp, kind) { + (_, Kind::Title) | (None, _) => vec![plain()], + (Some(dbghelp), Kind::Ours) if self.pdb.0 => { + let (names, context) = dbghelp.functions(address, self.inline); + line = dbghelp.line(address, context); + if names.is_empty() { + vec![plain()] + } else { + names + } + } + (Some(dbghelp), _) => { + // An export names the function only if it starts it: the + // nearest export below is some other function's. + let export = dbghelp.symbol(address).filter(|&(_, at)| match start { + Some(start) => at >= start && at <= address, + None => at <= address && address - at < 0x100, + }); + match export { + Some((name, _)) => { + let module = label.rsplit_once('.').map_or(&*label, |(stem, _)| stem); + vec![format!("{module}!{name}")] + } + None => vec![plain()], + } + } + }; + let funcs = names + .into_iter() + .map(|name| self.func(name, Some(kind))) + .collect(); + let line = line.map(|(file, line)| { + // The last three parts of the path: the crate, `src`, the file. + let mut parts: Vec<&str> = file.rsplit(['\\', '/']).take(3).collect(); + parts.reverse(); + let text = format!("{}:{line}", parts.join("\\")); + *self.by_line.entry(text.clone()).or_insert_with(|| { + self.lines.push(text); + self.lines.len() as u32 - 1 + }) + }); + Resolved { + funcs, + kind: Some(kind), + line, + } + } +} + +// --------------------------------------------------------------------- +// The report. +// --------------------------------------------------------------------- + +/// A function's time in a role, microseconds. +#[derive(Default, Clone, Copy)] +struct Row { + /// In the function itself, and of that on a processor. + own: u64, + cpu: u64, + /// In it and in what it called. + all: u64, +} + +/// What a role's threads did. +#[derive(Default)] +struct RoleReport { + threads: Vec, + wall: u64, + cpu: u64, + waiting: u64, + funcs: FastMap, + /// By [`Kind`]: innermost frame's, the nearest frame's that is not the + /// system's, and with what it called. + modules: [[u64; 3]; 6], + /// (kind of wait, the function that waited, through whose code) to + /// microseconds. + waits: HashMap<(&'static str, u32, Option), u64>, + lines: FastMap<(u32, u32), u64>, + /// Stacks as function indices, outermost first. + stacks: HashMap, u64>, +} + +/// A written report, and its numbers for the tests. +struct Report { + text: String, + folded: String, + #[cfg_attr(not(test), allow(dead_code))] + roles: Vec, +} + +/// A role's numbers as the tests ask for them (microseconds). +#[cfg_attr(not(test), allow(dead_code))] +struct RoleSummary { + role: Role, + wall: u64, + waiting: u64, + /// (name, own, with what it called), every function. + functions: Vec<(String, u64, u64)>, + /// (kind, the function that waited, time). + waits: Vec<(String, String, u64)>, +} + +/// The stacks written to the stacks file: those with this share of their +/// role's time or more; the rest go to one line per role. +const FOLD_LEAST: f64 = 0.00005; + +impl Sampler { + fn report(&mut self) -> Report { + let began = Instant::now(); + let inline = self.config.inline; + let stood = (self.held_within(0.5), self.held_within(0.99)); + let symbols = self.symbols.get_or_insert_with(|| Symbols::new(inline)); + symbols.refresh(); + // Every node's address, named. + let named: Vec> = self + .threads + .iter() + .map(|t| { + t.tree + .nodes + .iter() + .map(|n| symbols.resolve(n.address)) + .collect() + }) + .collect(); + let starts: Vec = self + .threads + .iter() + .map(|t| symbols.resolve(t.start)) + .collect(); + let symbols = &*symbols; + let mut roles: Vec = Role::ALL.iter().map(|_| RoleReport::default()).collect(); + // Per thread: wall, on a processor, waiting (microseconds). + let mut per_thread = vec![[0u64; 3]; self.threads.len()]; + // Per thread: own time by function, for the one it is mostly in. + let mut mostly: Vec> = vec![FastMap::default(); self.threads.len()]; + let mut stamp = 0u32; + let mut seen = vec![0u32; symbols.funcs.len()]; + let mut path: Vec<(u32, Option)> = Vec::new(); + for (t, thread) in self.threads.iter().enumerate() { + let role = &mut roles[thread.role as usize]; + role.threads.push(t); + let nodes = &thread.tree.nodes; + for (i, node) in nodes.iter().enumerate().skip(1) { + if node.wall == 0 { + continue; + } + // The stack, innermost first, inlined calls as frames. + path.clear(); + let mut at = i; + while at != 0 { + let resolved = &symbols.resolved[named[t][at] as usize]; + path.extend(resolved.funcs.iter().rev().map(|&f| (f, resolved.kind))); + at = nodes[at].parent as usize; + } + let (wall, cpu) = (node.wall, node.cpu); + role.wall += wall; + role.cpu += cpu; + per_thread[t][0] += wall; + per_thread[t][1] += cpu; + *mostly[t].entry(path[0].0).or_default() += wall; + let (leaf, leaf_kind) = path[0]; + let row = role.funcs.entry(leaf).or_default(); + row.own += wall; + row.cpu += cpu; + stamp += 1; + let mut kinds = [false; 6]; + // Every thread starts in the system's code: those outermost + // frames are not the system "with what it calls". + let start = path + .iter() + .rposition(|p| p.1.is_some_and(|k| k != Kind::System)); + for (at, &(func, kind)) in path.iter().enumerate() { + if seen[func as usize] != stamp { + seen[func as usize] = stamp; + role.funcs.entry(func).or_default().all += wall; + } + if let Some(kind) = kind + && start.is_some_and(|start| at <= start) + { + kinds[kind as usize] = true; + } + } + for (kind, &on) in kinds.iter().enumerate() { + role.modules[kind][2] += if on { wall } else { 0 }; + } + if let Some(kind) = leaf_kind { + role.modules[kind as usize][0] += wall; + } + // Whose time it is: the innermost frame that is not the + // system's (a kernel call is its caller's). + let owner = path + .iter() + .filter_map(|&(_, kind)| kind) + .find(|&kind| !matches!(kind, Kind::System | Kind::Other)) + .or(leaf_kind); + if let Some(kind) = owner { + role.modules[kind as usize][1] += wall; + } + let ours = |&(func, kind): &(u32, Option)| { + kind == Some(Kind::Ours) && !symbols.funcs[func as usize].runtime + }; + if symbols.funcs[leaf as usize].wait { + role.waiting += wall; + per_thread[t][2] += wall; + // The function of ours that waited (the title's, on a + // thread with none of ours), and what lies between. + let caller = path + .iter() + .position(ours) + .or_else(|| path.iter().position(|p| p.1 == Some(Kind::Title))); + let between = &path[..caller.unwrap_or(path.len())]; + let names: Vec<&str> = between + .iter() + .map(|&(f, _)| &*symbols.funcs[f as usize].name) + .collect(); + let through = between.iter().filter_map(|&(_, kind)| kind).find(|kind| { + matches!( + kind, + Kind::Driver | Kind::Direct3d | Kind::Title | Kind::Other + ) + }); + let caller = caller.map_or(u32::MAX, |at| path[at].0); + *role + .waits + .entry((wait_kind(&names), caller, through)) + .or_default() += wall; + } + let resolved = &symbols.resolved[named[t][i] as usize]; + if let Some(line) = resolved.line { + *role.lines.entry((line, leaf)).or_default() += wall; + } + let stack: Vec = path.iter().rev().map(|&(f, _)| f).collect(); + *role.stacks.entry(stack).or_default() += wall; + } + } + + // Written out. + let frames = self.presented; + let seconds = self.wall as f64 / 1e6; + // Microseconds to the unit of the tables. + let (unit, per) = if frames > 0 { + ("ms a frame", 1000.0 * frames as f64) + } else { + ("ms a second", 1000.0 * seconds.max(1e-9)) + }; + let ms = |us: u64| us as f64 / per; + let share = |us: u64, of: u64| 100.0 * us as f64 / of.max(1) as f64; + let name = |func: u32| match symbols.funcs.get(func as usize) { + Some(func) => &*func.name, + None => "[no function of ours or the title's]", + }; + // For the tables: a long name's start and end (the stacks file has it whole). + let short = |func: u32, most: usize| { + let name = name(func); + let chars = name.chars().count(); + if chars <= most { + return name.to_owned(); + } + let head: String = name.chars().take(most * 2 / 3).collect(); + let tail: String = name.chars().skip(chars - most / 3).collect(); + format!("{head}...{tail}") + }; + let mut text = String::new(); + let mut folded = String::new(); + let mut summaries = Vec::new(); + let w = &mut text; + let _ = writeln!(w, "VIctory profile, process {}", std::process::id()); + let _ = writeln!( + w, + "sampled {seconds:.1} s in {} looks ({} asked a second, {:.2} ms between looks, {} late); \ + {frames} frames presented meanwhile{}", + self.ticks, + self.config.hz, + self.wall as f64 / 1000.0 / self.ticks.max(1) as f64, + self.late, + if frames > 0 { + format!( + " ({:.1} ms a frame)", + self.wall as f64 / 1000.0 / frames as f64 + ) + } else { + " (none: the tables are per second of sampling)".to_owned() + }, + ); + let alive = self.threads.iter().filter(|t| t.alive).count(); + let _ = writeln!( + w, + "{} threads followed ({alive} still running); a thread looked at stood still under {:.0} us \ + half the times, under {:.0} us 99 in 100, {:.0} us at longest, {:.1} us on average, {} \ + times; {} call sites kept{}", + self.threads.len(), + stood.0, + stood.1, + self.held_longest as f64 / 1000.0, + self.held_ns as f64 / 1000.0 / self.held.max(1) as f64, + self.held, + self.nodes, + if self.nodes >= MOST_NODES { + " (FULL: later new stacks are one line)" + } else { + "" + }, + ); + if self.config.budget > 0.0 { + let _ = writeln!( + w, + "a thread may stand still for looks {:.1} % of its time (VICTORY_PROFILE_BUDGET): one \ + whose looks cost more is looked at every 2nd, 3rd... tick while it runs (\"every\" \ + below); its samples stand for more time each, so the times stay right", + 100.0 * self.config.budget + ); + } + let (mine, since) = (own_cpu(), self.clock.elapsed()); + let _ = writeln!( + w, + "the sampler's thread used {:.1} % of one processor", + 100.0 * mine.as_secs_f64() / since.as_secs_f64().max(1e-9), + ); + let _ = writeln!( + w, + "names of ours: {}", + match (&symbols.dbghelp, &symbols.pdb) { + (None, _) => + "dbghelp.dll could not be used: every frame is module+offset".to_owned(), + (Some(_), (true, pdb)) => format!("from {pdb}"), + (Some(_), (false, _)) => + "NO PDB FOUND for the executable: its frames are module+offset of each \ + function's start (keep victory.pdb beside victory.exe)" + .to_owned(), + } + ); + let _ = writeln!(w); + let _ = writeln!( + w, + "How to read. Every number is {unit} unless it is a %. A role's time is its threads' \ + together: five recording threads can make more than a frame." + ); + let _ = writeln!( + w, + " own time with the function as the innermost frame; a call into the kernel \ + (ntdll!Nt..., win32u!Nt...) is the kernel working or waiting for that caller" + ); + let _ = writeln!(w, " with own time plus everything the function called"); + let _ = writeln!( + w, + " on cpu share of the own time the thread was on a processor (its cycle counter): \ + low means it stood there blocked" + ); + let _ = writeln!( + w, + " waiting samples whose innermost frame is one of the kernel's waits; under WAITS \ + they are given to the function of ours that waited" + ); + let _ = writeln!( + w, + " looks times a thread was sampled; not susp: of those, the ones answered without \ + suspending it (it had not run since the look before); cut: stacks that did not reach \ + the thread's first frame; look us: what a suspension of it takes" + ); + let _ = writeln!( + w, + " title+0x1234 is the title's function starting at that offset; \ + nvwgf2umx.dll+0x1234 a driver function with no name; [frames not kept] marks stacks \ + deeper than {} frames or {} KB", + self.config.depth, + self.config.stack >> 10, + ); + let _ = writeln!(w); + let _ = writeln!(w, "THREADS"); + let _ = writeln!( + w, + " {:<10} {:>7} {:<30} {:>9} {:>8} {:>9} {:>9} {:>8} {:>7} {:>7} {:>5} {:>8} mostly in (own time)", + "role", + "thread", + "name, or where it started", + unit, + "on cpu %", + "waiting %", + "looks", + "not susp", + "failed", + "cut", + "every", + "look us" + ); + for role in Role::ALL { + for &t in &roles[role as usize].threads { + let thread = &self.threads[t]; + let [wall, cpu, waiting] = per_thread[t]; + let said = if thread.name.is_empty() { + let start = &symbols.resolved[starts[t] as usize]; + format!("at {}", short(start.funcs[0], 27)) + } else { + thread.name.chars().take(30).collect::() + }; + let top = mostly[t].iter().max_by_key(|&(&func, &us)| (us, func)); + let top = top.map_or(String::new(), |(&func, &us)| { + format!(" {} ({:.0} %)", short(func, 70), share(us, wall)) + }); + let _ = writeln!( + w, + " {:<10} {:>7} {:<30} {:>9.1} {:>8.1} {:>9.1} {:>9} {:>8} {:>7} {:>7} {:>5} {:>8.1}{}{top}", + role.name(), + thread.id, + said, + ms(wall), + share(cpu, wall), + share(waiting, wall), + thread.looks, + thread.reused, + thread.missed, + thread.cut, + thread.every, + thread.cost / 1000.0, + if thread.alive { "" } else { " (ended)" }, + ); + } + } + for role in Role::ALL { + let r = &roles[role as usize]; + if r.wall == 0 { + continue; + } + let _ = writeln!(w); + let _ = writeln!( + w, + "=== {} === {} thread{}: {:.1} {unit}, on a processor {:.1} ({:.0} %), waiting {:.1} ({:.0} %)", + role.says(), + r.threads.len(), + if r.threads.len() == 1 { "" } else { "s" }, + ms(r.wall), + ms(r.cpu), + share(r.cpu, r.wall), + ms(r.waiting), + share(r.waiting, r.wall), + ); + let _ = writeln!( + w, + " BY MODULE (own: the innermost frame's; for: system time given to the nearest \ + caller that is ours, the driver's, Direct3D's or the title's; with: anywhere on \ + the stack above the thread's start)" + ); + let _ = writeln!( + w, + " {:<18} {:>9} {:>6} {:>9} {:>6} {:>9} {:>6}", + "", "own", "%", "for", "%", "with", "%" + ); + for (kind, label) in KINDS.iter().enumerate() { + let [own, owner, all] = r.modules[kind]; + let _ = writeln!( + w, + " {:<18} {:>9.2} {:>6.1} {:>9.2} {:>6.1} {:>9.2} {:>6.1}", + label, + ms(own), + share(own, r.wall), + ms(owner), + share(owner, r.wall), + ms(all), + share(all, r.wall), + ); + } + let mut rows: Vec<(u32, Row)> = r.funcs.iter().map(|(&f, &row)| (f, row)).collect(); + let table = |w: &mut String, title: &str, rows: &[(u32, Row)]| { + let _ = writeln!(w, " {title}"); + let _ = writeln!( + w, + " {:>9} {:>6} {:>9} {:>6} {:>7} function", + "own", "%", "with", "%", "on cpu%" + ); + for &(func, row) in rows.iter().take(40) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {:>9.2} {:>6.1} {:>7} {}", + ms(row.own), + share(row.own, r.wall), + ms(row.all), + share(row.all, r.wall), + if row.own > 0 { + format!("{:.0}", share(row.cpu, row.own)) + } else { + "-".into() + }, + short(func, 150), + ); + } + }; + rows.sort_by(|a, b| b.1.own.cmp(&a.1.own).then(a.0.cmp(&b.0))); + let own = rows.iter().take_while(|row| row.1.own > 0).count(); + table(&mut *w, "FUNCTIONS BY OWN TIME (top 40)", &rows[..own]); + // Every stack of a thread has its start-up frames: they say nothing. + rows.retain(|&(func, _)| { + let func = &symbols.funcs[func as usize]; + let start = ["!RtlUserThreadStart", "!BaseThreadInitThunk"]; + !func.runtime && !start.iter().any(|s| func.name.ends_with(s)) + }); + rows.sort_by(|a, b| b.1.all.cmp(&a.1.all).then(a.0.cmp(&b.0))); + table( + &mut *w, + "FUNCTIONS WITH WHAT THEY CALL (top 40; without the thread's start and the language's runtime)", + &rows, + ); + let mut waits: Vec<_> = r.waits.iter().map(|(&key, &us)| (us, key)).collect(); + waits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.1.cmp(&b.1.1))); + if !waits.is_empty() { + let _ = writeln!( + w, + " WAITS ({:.1} {unit}, {:.0} % of the role), by the function that waited", + ms(r.waiting), + share(r.waiting, r.wall) + ); + let _ = writeln!( + w, + " {:>9} {:>6} {:<24} {:<16} waited in", + "", "%", "kind", "inside" + ); + for &(us, (kind, caller, through)) in waits.iter().take(30) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {:<24} {:<16} {}", + ms(us), + share(us, r.wall), + kind, + through.map_or("-", |kind| KINDS[kind as usize]), + short(caller, 150), + ); + } + } + let mut lines: Vec<_> = r.lines.iter().map(|(&key, &us)| (us, key)).collect(); + lines.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + if !lines.is_empty() { + let _ = writeln!(w, " HOTTEST LINES OF OURS (own time)"); + for &(us, (line, func)) in lines.iter().take(25) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {} ({})", + ms(us), + share(us, r.wall), + symbols.lines[line as usize], + short(func, 100), + ); + } + } + let mut stacks: Vec<(&Vec, u64)> = + r.stacks.iter().map(|(s, &us)| (s, us)).collect(); + stacks.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + let fold = |stack: &[u32]| { + let mut line = String::from(role.name()); + for &func in stack { + line.push(';'); + line.extend(name(func).chars().map(|c| match c { + ';' => ':', + ' ' => '_', + c => c, + })); + } + line + }; + let _ = writeln!( + w, + " STACKS (the 12 heaviest of {}, their innermost 10 frames, {unit}; all of them \ + whole, in microseconds, in the .folded file)", + stacks.len() + ); + for &(stack, us) in stacks.iter().take(12) { + let from = stack.len().saturating_sub(10); + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {}{}", + ms(us), + share(us, r.wall), + if from > 0 { "... " } else { "" }, + stack[from..] + .iter() + .map(|&f| short(f, 60)) + .collect::>() + .join(" > "), + ); + } + let least = (FOLD_LEAST * r.wall as f64) as u64; + let mut rest = 0; + for &(stack, us) in &stacks { + if us >= least { + let _ = writeln!(folded, "{} {us}", fold(stack)); + } else { + rest += us; + } + } + if rest > 0 { + let _ = writeln!( + folded, + "{};[stacks_under_{:.3}_%_each] {rest}", + role.name(), + 100.0 * FOLD_LEAST + ); + } + summaries.push(RoleSummary { + role, + wall: r.wall, + waiting: r.waiting, + functions: r + .funcs + .iter() + .map(|(&f, row)| (name(f).to_owned(), row.own, row.all)) + .collect(), + waits: waits + .iter() + .map(|&(us, (kind, caller, _))| (kind.to_owned(), name(caller).to_owned(), us)) + .collect(), + }); + } + let _ = writeln!(w); + let _ = writeln!( + w, + "(this report took {:.0} ms to write; sampling stood still meanwhile)", + began.elapsed().as_secs_f64() * 1000.0 + ); + Report { + text, + folded, + roles: summaries, + } + } + + /// Writes the report and the stacks file, each whole or not at all (a + /// process ended in the middle leaves the last ones). + fn write(&mut self) { + let report = self.report(); + let out = self.config.out.clone(); + let put = |file: PathBuf, text: &str| { + let mut partial = file.clone().into_os_string(); + partial.push(".part"); + std::fs::write(&partial, text).and_then(|()| std::fs::rename(&partial, &file)) + }; + let mut stacks = out.clone().into_os_string(); + stacks.push(".folded"); + let written = + put(out.clone(), &report.text).and_then(|()| put(stacks.into(), &report.folded)); + static SAID: AtomicBool = AtomicBool::new(false); + match written { + Ok(()) if !SAID.swap(true, Relaxed) => { + tracing::info!(file = %out.display(), "profile written (and again as the run goes on; the stacks for a flame graph are beside it, .folded)"); + } + Ok(()) => {} + Err(e) => tracing::warn!(error = %e, file = %out.display(), "profile not written"), + } + self.resync(); + } +} + +/// The processor time the calling thread has used. +fn own_cpu() -> Duration { + use windows_sys::Win32::Foundation::FILETIME; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; + let ticks = |t: FILETIME| u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime); + Duration::from_nanos((ticks(kernel) + ticks(user)) * 100) +} + +// --------------------------------------------------------------------- +// The sampler's thread. +// --------------------------------------------------------------------- + +/// Asks the sampler to write its last report and end; set when it has. +static STOP: AtomicBool = AtomicBool::new(false); +static DONE: AtomicBool = AtomicBool::new(false); +/// The sampler's thread, as a handle: to see at exit whether it still runs. +static SAMPLER: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(null_mut()); + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// At process exit (registered after the loader's own exit function, so +/// run before it ends the other threads): the last report is written. +extern "C" fn at_exit() { + STOP.store(true, Relaxed); + let thread = SAMPLER.load(Relaxed); + let waiting = Instant::now(); + while !DONE.load(Relaxed) && waiting.elapsed() < Duration::from_secs(10) { + // SAFETY: the sampler's thread handle, never closed; signalled + // when the thread is gone, however it went. + if thread.is_null() || unsafe { WaitForSingleObject(thread, 5) } == 0 { + break; + } + } +} + +/// The sampler's clock: a timer of the system's finer kind, which fires +/// every period by itself where the period is whole milliseconds (a +/// sleep of a millisecond takes one and a half). +struct Pace { + timer: HANDLE, + period: Duration, + /// The timer fires by itself; otherwise it is set before each wait, + /// for `next`. + repeats: bool, + next: Instant, + /// Microseconds a tick is put off by at most, and the state of the + /// numbers that say by how much. + jitter: u64, + random: u64, +} + +impl Pace { + fn new(hz: u32, jitter: u64) -> Pace { + use windows_sys::Win32::System::Threading::{ + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, SetWaitableTimer, + }; + let hz = hz.max(1); + let period = Duration::from_secs_f64(1.0 / f64::from(hz)); + // SAFETY: makes a timer of ours (all access), unnamed. + let timer = unsafe { + CreateWaitableTimerExW( + null(), + null(), + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, + 0x1f_0003, + ) + }; + let mut repeats = false; + if !timer.is_null() && hz <= 1000 && 1000 % hz == 0 { + // First in a period from now (100 ns units, negative: from + // now), then every period (milliseconds). + let first = -(period.as_nanos() as i64 / 100); + // SAFETY: our timer; no completion routine. + repeats = unsafe { + SetWaitableTimer(timer, &first, (1000 / hz) as i32, None, null(), 0) != 0 + }; + } + Pace { + timer, + period, + repeats, + next: Instant::now() + period, + // Less than the period, so ticks stay in order. + jitter: jitter.min(period.as_micros() as u64 / 2), + random: 0x9e37_79b9_7f4a_7c15, + } + } + + /// Waits for the next tick. + /// + /// The timer wakes us on the system's clock, and so are woken the + /// threads that sleep: looked at then, a thread that sleeps a + /// millisecond at a time is always just waking (a test's sleeping + /// thread was seen out of its wait 12 % of the time; it is 0.5 %). So + /// the look is put off by a time that differs from tick to tick, + /// spent spinning: no timer is that fine. + fn wait(&mut self) { + self.wait_for_timer(); + if self.jitter > 0 { + self.random ^= self.random << 13; + self.random ^= self.random >> 7; + self.random ^= self.random << 17; + let until = Instant::now() + Duration::from_micros(self.random % (self.jitter + 1)); + while Instant::now() < until { + std::hint::spin_loop(); + } + } + } + + fn wait_for_timer(&mut self) { + use windows_sys::Win32::System::Threading::{INFINITE, SetWaitableTimer}; + if self.repeats { + // SAFETY: our timer. + unsafe { WaitForSingleObject(self.timer, INFINITE) }; + return; + } + let now = Instant::now(); + if self.next > now { + let due = -((self.next - now).as_nanos() as i64 / 100).max(1); + // SAFETY: our timer, set to fire once and waited for. + let set = !self.timer.is_null() + && unsafe { SetWaitableTimer(self.timer, &due, 0, None, null(), 0) } != 0; + if set { + // SAFETY: our timer. + unsafe { WaitForSingleObject(self.timer, INFINITE) }; + } else { + std::thread::sleep(self.next - now); + } + } + // A tick that came late is not made up for: the next is a period on. + self.next = (self.next + self.period).max(Instant::now()); + } +} + +/// Starts the sampler; false if its thread could not be made. +fn start(config: Config) -> bool { + use std::os::windows::io::IntoRawHandle; + let says = format!( + "profiling (VICTORY_PROFILE=1): {} looks a second at the submitting, recording and worker \ + threads, the report in {} every {:.0} s and at exit", + config.hz, + config.out.display(), + config.every + ); + match std::thread::Builder::new() + .name("victory-profile".into()) + .spawn(move || run(config)) + { + Ok(thread) => { + SAMPLER.store(thread.into_raw_handle().cast(), Relaxed); + // SAFETY: registers a function with the host CRT's exit table. + unsafe { atexit(at_exit) }; + tracing::info!("{says}"); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread for the profiler"); + false + } + } +} + +fn run(config: Config) { + // Above the threads it looks at: a late look stretches a sample, and + // a sampler taken off its processor between suspending a thread and + // letting it go leaves that thread standing. It sleeps most of the time. + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let wait = |seconds: f64| { + let until = Instant::now() + Duration::from_secs_f64(seconds); + while Instant::now() < until && !STOP.load(Relaxed) { + std::thread::sleep(Duration::from_millis(20)); + } + }; + wait(config.after); + let mut pace = Pace::new(config.hz, config.jitter); + let (every, length) = ( + Duration::from_secs_f64(config.every), + config.length.map(Duration::from_secs_f64), + ); + let mut sampler = Sampler::new(config); + sampler.rescan(); + sampler.resync(); + let began = Instant::now(); + let (mut scan, mut report) = (began + SCAN, began + every); + while !STOP.load(Relaxed) && length.is_none_or(|length| began.elapsed() < length) { + pace.wait(); + sampler.tick(); + let now = Instant::now(); + if now >= scan { + sampler.rescan(); + scan = now + SCAN; + } + if now >= report { + sampler.write(); + report = Instant::now() + every; + } + } + sampler.write(); + DONE.store(true, Relaxed); +} + +/// Between two searches for threads to follow. +const SCAN: Duration = Duration::from_secs(1); + +#[cfg(test)] +mod tests; diff --git a/crates/victory-gpu/src/profile/tests.rs b/crates/victory-gpu/src/profile/tests.rs new file mode 100644 index 00000000..16c57243 --- /dev/null +++ b/crates/victory-gpu/src/profile/tests.rs @@ -0,0 +1,1005 @@ +//! The profiler on threads whose work is known. No graphics card is used. + +use super::*; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Mutex, mpsc}; + +fn config(hz: u32) -> Config { + Config::new(hz, std::env::temp_dir().join("victory_profile_test.txt")) +} + +/// Starts a thread running `work` and returns its id once it runs. +fn thread(work: impl FnOnce() + Send + 'static) -> (u32, std::thread::JoinHandle<()>) { + let (said, hears) = mpsc::channel(); + let running = std::thread::spawn(move || { + // SAFETY: a plain query. + said.send(unsafe { GetCurrentThreadId() }).unwrap(); + work(); + }); + (hears.recv().unwrap(), running) +} + +/// Looks at the followed threads for `time`, a look every `period`, with +/// `frames` presents spread over it. +fn sample(sampler: &mut Sampler, time: Duration, period: Duration, frames: &AtomicU64, each: u64) { + sampler.resync(); + let began = Instant::now(); + let mut looks = 0u64; + while began.elapsed() < time { + std::thread::sleep(period); + sampler.tick(); + looks += 1; + if each > 0 && looks.is_multiple_of(each) { + frames.fetch_add(1, Relaxed); + } + } +} + +#[inline(never)] +fn profile_test_spin_inner(stop: &AtomicBool) -> u64 { + let mut sum = 0u64; + while !stop.load(Relaxed) { + for i in 0..2000u64 { + sum = std::hint::black_box(sum.wrapping_mul(31).wrapping_add(i)); + } + } + sum +} + +#[inline(never)] +fn profile_test_spins(stop: &AtomicBool) -> u64 { + std::hint::black_box(profile_test_spin_inner(stop)).wrapping_add(1) +} + +#[inline(never)] +fn profile_test_sleeps(stop: &AtomicBool) -> u64 { + let mut naps = 0; + while !stop.load(Relaxed) { + std::thread::sleep(Duration::from_millis(5)); + naps = std::hint::black_box(naps + 1); + } + naps +} + +#[inline(never)] +fn profile_test_locks(lock: &Mutex) -> u64 { + let mut held = lock.lock().unwrap(); + *held += 1; + std::hint::black_box(*held) +} + +#[inline(never)] +fn profile_test_deep(left: u32, stop: &AtomicBool) -> u64 { + // A frame of a kilobyte, so a hundred of them pass any small limit. + let mut room = [0u64; 128]; + room[left as usize % 128] = u64::from(left); + let room = std::hint::black_box(room); + let below = if left == 0 { + profile_test_sleeps(stop) + } else { + profile_test_deep(left - 1, stop) + }; + std::hint::black_box(below.wrapping_add(room[3])) +} + +/// Whether `address` is committed code. +fn executable(address: u64) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid; the query reads + // the address space's bookkeeping, not `address`. + unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(address as *const _, &mut info, size_of_val(&info)) != 0 + && info.State == MEM_COMMIT + && info.Protect & 0xf0 != 0 + && info.Protect & 0x100 == 0 + } +} + +fn own(role: &RoleSummary, what: &str) -> u64 { + role.functions + .iter() + .filter(|f| f.0.contains(what)) + .map(|f| f.1) + .sum() +} + +fn with(role: &RoleSummary, what: &str) -> u64 { + role.functions + .iter() + .filter(|f| f.0.contains(what)) + .map(|f| f.2) + .max() + .unwrap_or(0) +} + +fn role(report: &Report, role: Role) -> &RoleSummary { + report + .roles + .iter() + .find(|r| r.role == role) + .unwrap_or_else(|| panic!("no {role:?} in\n{}", report.text)) +} + +/// A busy loop in one function, a sleep in another, a wait for a lock in +/// a third: the report gives each thread's time to the right one, as +/// running or as waiting, and per frame. +#[test] +fn time_goes_to_the_function_that_spent_it() { + static PRESENTS: AtomicU64 = AtomicU64::new(0); + let stop = Arc::new(AtomicBool::new(false)); + let lock = Arc::new(Mutex::new(0u64)); + let held = lock.lock().unwrap(); + let (spinning, a) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_spins(&stop)); + } + }); + let (sleeping, b) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_sleeps(&stop)); + } + }); + let (locked, c) = thread({ + let lock = lock.clone(); + move || { + std::hint::black_box(profile_test_locks(&lock)); + } + }); + std::thread::sleep(Duration::from_millis(50)); + + let mut sampler = Sampler::new(config(1000)); + sampler.presents = &PRESENTS; + sampler.follow(spinning, Role::Submit, null_mut(), Some("spins".into())); + sampler.follow(sleeping, Role::Record, null_mut(), Some("sleeps".into())); + sampler.follow(locked, Role::Wide, null_mut(), Some("locks".into())); + assert_eq!(sampler.threads.len(), 3); + assert!( + sampler.threads.iter().all(|t| t.low != 0 && t.low < t.high), + "stack bounds" + ); + sample( + &mut sampler, + Duration::from_millis(1500), + Duration::from_millis(1), + &PRESENTS, + 20, + ); + let report = sampler.report(); + stop.store(true, Relaxed); + drop(held); + for running in [a, b, c] { + running.join().unwrap(); + } + println!("{}", report.text); + assert!(sampler.presented >= 20, "{} frames", sampler.presented); + assert!( + sampler.symbols.as_ref().is_some_and(|s| s.pdb.0), + "the test's PDB was not found" + ); + + // The busy loop: all of it in the inner function, called from the outer. + let spins = role(&report, Role::Submit); + assert!(spins.wall >= 1_200_000, "{} us sampled", spins.wall); + // (An unoptimised build calls the loop's own pieces; an optimised one + // has them inside it.) + let inner = with(spins, "profile_test_spin_inner"); + assert!( + inner * 100 >= spins.wall * 95, + "inner {inner} of {}", + spins.wall + ); + assert!(with(spins, "profile_test_spins") * 100 >= spins.wall * 95); + assert!(own(spins, "profile_test_spins") * 100 <= spins.wall * 5); + assert!( + spins.waiting * 100 <= spins.wall * 5, + "waiting {}", + spins.waiting + ); + // Every sample is some function's own time, once. + assert_eq!(spins.functions.iter().map(|f| f.1).sum::(), spins.wall); + + // The sleep: waiting, for the function that slept. + let sleeps = role(&report, Role::Record); + assert!( + sleeps.waiting * 100 >= sleeps.wall * 85, + "{} of {}", + sleeps.waiting, + sleeps.wall + ); + let (kind, caller, time) = &sleeps.waits[0]; + assert!( + kind == "sleep" && caller.contains("profile_test_sleeps"), + "{kind}, {caller}" + ); + assert!(time * 100 >= sleeps.waiting * 95); + + // The lock: waiting, for the function that wanted it. + let locks = role(&report, Role::Wide); + assert!( + locks.waiting * 100 >= locks.wall * 95, + "{} of {}", + locks.waiting, + locks.wall + ); + let (kind, caller, _) = &locks.waits[0]; + assert!( + kind == "lock (ours)" && caller.contains("profile_test_locks"), + "{kind}, {caller}" + ); + + // Per frame, and the stacks for a flame graph: outer before inner. + assert!(report.text.contains("ms a frame")); + let stack = report + .folded + .lines() + .find(|l| l.starts_with("submit;") && l.contains("profile_test_spin_inner")) + .unwrap_or_else(|| panic!("{}", report.folded)); + let (outer, inner) = ( + stack.find("profile_test_spins").unwrap(), + stack.find("profile_test_spin_inner").unwrap(), + ); + assert!(outer < inner, "{stack}"); + // The thread that waited the whole time was suspended once at most a + // few times: it had not run since the look before. + let waiting = sampler.threads.iter().find(|t| t.id == locked).unwrap(); + assert!( + waiting.reused * 10 >= waiting.looks * 9, + "{} of {}", + waiting.reused, + waiting.looks + ); +} + +/// A stack deeper than is kept, and one longer than is copied: the +/// innermost frames are still named, and the stack is marked as cut. +#[test] +fn deep_stacks_are_cut_not_lost() { + let stop = Arc::new(AtomicBool::new(false)); + let (deep, running) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_deep(150, &stop)); + } + }); + std::thread::sleep(Duration::from_millis(50)); + for (depth, stack) in [(24, 128 << 10), (MAX_DEPTH, 8 << 10)] { + static PRESENTS: AtomicU64 = AtomicU64::new(0); + let mut settings = config(500); + (settings.depth, settings.stack, settings.reuse) = (depth, stack, false); + let mut sampler = Sampler::new(settings); + sampler.presents = &PRESENTS; + sampler.follow(deep, Role::Busy, null_mut(), None); + sample( + &mut sampler, + Duration::from_millis(300), + Duration::from_millis(2), + &PRESENTS, + 0, + ); + let report = sampler.report(); + let thread = &sampler.threads[0]; + assert!( + thread.looks > 20 && thread.missed == 0, + "{} looks", + thread.looks + ); + assert_eq!( + thread.cut, thread.looks, + "depth {depth}, {stack} bytes copied" + ); + let busy = role(&report, Role::Busy); + assert!( + with(busy, "[frames not kept]") * 100 >= busy.wall * 99, + "{}", + report.text + ); + assert!( + with(busy, "profile_test_sleeps") * 100 >= busy.wall * 90, + "{}", + report.text + ); + assert!(report.text.contains("ms a second")); + } + stop.store(true, Relaxed); + running.join().unwrap(); +} + +/// Registers and stack bytes that mean nothing, at addresses inside real +/// code: the walk stops, and reads nothing outside its copy (a read +/// elsewhere would end the test with an access violation). +#[test] +fn stacks_that_mean_nothing_are_walked_without_a_fault() { + let mut symbols = Symbols::new(false); + symbols.refresh(); + let modules: Vec<(u64, u64)> = symbols.modules.iter().map(|m| (m.base, m.end)).collect(); + assert!(modules.len() > 3); + let mut sampler = Sampler::new(config(1000)); + // SAFETY: a plain query. + let me = unsafe { GetCurrentThreadId() }; + // A thread entry is all the walk needs; this one is never suspended. + sampler.follow(me, Role::Busy, null_mut(), None); + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + // Return instructions (bytes that read as one) in the modules' code. + let mut returns = Vec::new(); + while returns.len() < 20_000 { + let r = next(); + let (base, end) = modules[(r >> 32) as usize % modules.len()]; + let at = base + 0x1000 + r % (end - base - 0x1000).max(1); + if !executable(at) { + continue; + } + // SAFETY: committed code of a loaded module, as just asked, to + // the end of its page. + let bytes = + unsafe { std::slice::from_raw_parts(at as *const u8, 0x1000 - (at as usize & 0xfff)) }; + if let Some(ret) = bytes.iter().skip(16).position(|&b| b == 0xc3) { + returns.push(at + 16 + ret as u64); + } + } + let limit = sampler.config.stack; + let (mut walked, mut frames) = (0u64, 0u64); + let rounds = env_number("VICTORY_PROFILE_TEST_WALKS").map_or(60_000, |n| n as u64); + for round in 0..rounds { + let got = (next() as usize % limit) & !7; + // A pretended stack somewhere, or the thread's own range. + let rsp = if round.is_multiple_of(2) { + (0x7000_0000_0000u64 + (next() & 0xffff_fff0)) as usize + } else { + sampler.threads[0].low + 0x1000 + (next() as usize & 0xff8) + }; + let code = |r: u64| { + if r.is_multiple_of(3) { + // A few bytes before a return: where functions end. + return returns[(r >> 32) as usize % returns.len()] - (r >> 8 & 15); + } + let (base, end) = modules[(r >> 32) as usize % modules.len()]; + base + 0x1000 + r % (end - base - 0x1000).max(1) + }; + // The copy: words that are nothing, stack addresses, code addresses. + for at in (0..got).step_by(8) { + let r = next(); + let word = match r % 4 { + 0 => r, + 1 => (rsp + (next() as usize % (got + 4096))) as u64, + 2 => code(next()), + _ => r & 0xffff, + }; + // SAFETY: inside the copy. + unsafe { + sampler + .copy + .add((rsp & 15) + at) + .cast::() + .write_unaligned(word) + }; + } + let end = (rsp & 15) + got; + if end < sampler.dirty { + // SAFETY: inside the copy. + unsafe { sampler.copy.add(end).write_bytes(0, sampler.dirty - end) }; + } + sampler.dirty = end; + let context = &mut sampler.context.0; + for register in [ + &mut context.Rax, + &mut context.Rbx, + &mut context.Rcx, + &mut context.Rdx, + &mut context.Rbp, + &mut context.Rsi, + &mut context.Rdi, + &mut context.R8, + &mut context.R9, + &mut context.R10, + &mut context.R11, + &mut context.R12, + &mut context.R13, + &mut context.R14, + &mut context.R15, + ] { + let r = next(); + *register = match r % 3 { + 0 => r, + 1 => (rsp + (next() as usize % (got + 4096))) as u64, + _ => r & 0xfff, + }; + } + context.Rsp = rsp as u64; + context.Rip = code(next()); + let (count, _, used) = sampler.walk(0, got); + assert!(used <= got + 8, "{used} of {got}"); + walked += 1; + frames += count as u64; + } + println!("{walked} walks of stacks that mean nothing, {frames} frames"); + assert!(frames > walked); +} + +/// The walk of another thread's copied stack names the same callers as +/// the system's own walk of that thread by itself. +#[test] +fn the_walk_in_the_copy_is_the_systems_walk() { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + let (said, hears) = mpsc::channel(); + let (go, wait) = mpsc::channel::<()>(); + #[inline(never)] + fn profile_test_parked(said: &mpsc::Sender>, wait: &mpsc::Receiver<()>) -> u64 { + let mut own = [null_mut(); 32]; + // SAFETY: writes at most 32 return addresses into `own`. + let n = unsafe { RtlCaptureStackBackTrace(0, 32, own.as_mut_ptr(), null_mut()) }; + said.send(own[..usize::from(n)].iter().map(|&a| a as u64).collect()) + .unwrap(); + wait.recv().ok(); + std::hint::black_box(u64::from(n)) + } + let (parked, running) = thread(move || { + std::hint::black_box(profile_test_parked(&said, &wait)); + }); + let own = hears.recv().unwrap(); + std::thread::sleep(Duration::from_millis(50)); + let mut sampler = Sampler::new(config(1000)); + sampler.follow(parked, Role::Busy, null_mut(), None); + let (got, _) = sampler.capture(0).expect("the thread is looked at"); + let (frames, whole, used) = sampler.walk(0, got); + assert!(used > 64 && used <= got, "{used} of {got} bytes"); + let walked: Vec = sampler.frames[..frames].to_vec(); + go.send(()).unwrap(); + running.join().unwrap(); + assert!(whole, "{frames} frames"); + // The system's walk starts in the function that asked; ours deeper, in + // the wait. From that function's caller on they are the same calls + // (ours keeps the byte before each return address). + let callers: Vec = own[1..].iter().map(|a| a - 1).collect(); + assert!(callers.len() >= 3, "{own:x?}"); + let at = walked + .iter() + .position(|&a| a == callers[0]) + .unwrap_or_else(|| panic!("{walked:x?} {callers:x?}")); + assert_eq!( + &walked[at..], + &callers[..], + "ours {walked:x?}, the system's {own:x?}" + ); +} + +#[test] +fn names_say_what_waits_and_whose_code_it_is() { + assert!(waits("ntdll!NtWaitForSingleObject")); + assert!(waits("ntdll!ZwWaitForAlertByThreadId")); + assert!(waits("ntdll!NtDelayExecution")); + assert!(waits( + "win32u!NtGdiDdDDIWaitForSynchronizationObjectFromCpu" + )); + assert!(!waits("ntdll!NtQueryVirtualMemory")); + assert!(!waits("ntdll!NtYieldExecution")); + assert!(!waits("victory_gpu::host::Host::submit")); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "ntdll!RtlAcquireSRWLockExclusive" + ]), + "lock (SRW)" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "ntdll.dll+0x1230", + "std::sys::sync::mutex::futex::Mutex::lock_contended" + ]), + "lock (ours)" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "std::sys::sync::condvar::futex::Condvar::wait" + ]), + "condition variable" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForSingleObject", + "KERNELBASE!WaitForSingleObjectEx" + ]), + "event or handle" + ); + assert_eq!( + wait_kind(&["ntdll!NtDelayExecution", "KERNELBASE!SleepEx"]), + "sleep" + ); + assert_eq!(kind_of("nvwgf2umx.dll", false), Kind::Driver); + assert_eq!(kind_of("ntdll.dll", false), Kind::System); + assert_eq!(kind_of("d3d12core.dll", false), Kind::Direct3d); + assert_eq!( + kind_of("victory-image-0123456789abcdef.dll", false), + Kind::Title + ); + assert_eq!(kind_of("vcruntime140.dll", false), Kind::Other); + assert_eq!(kind_of("victory.exe", true), Kind::Ours); + assert_eq!(Role::of_name("victory-pipelines-3"), Some(Role::Pipelines)); + assert_eq!(Role::of_name("victory-wide-0"), Some(Role::Wide)); + assert_eq!(Role::of_name("victory-window"), None); +} + +#[test] +fn times_are_classed_four_to_a_power_of_two() { + assert_eq!(held_class(0), (0, 0)); + assert_eq!(held_class(3), (3, 3)); + assert_eq!(held_class(4), (8, 4)); + assert_eq!(held_class(7), (11, 7)); + assert_eq!(held_class(8), (12, 8)); + assert_eq!(held_class(9), (12, 8)); + assert_eq!(held_class(10), (13, 10)); + assert_eq!(held_class(20_000), (56, 16_384)); + let mut sampler = Sampler::new(config(1000)); + for ns in [1000, 20_000, 20_000, 20_000, 500_000] { + sampler.held += 1; + sampler.held_by[held_class(ns).0] += 1; + sampler.held_longest = sampler.held_longest.max(ns); + } + // The middle one of five is a 20 us one: its class ends at 20.48. + assert_eq!(sampler.held_within(0.5), 20.48); + assert_eq!(sampler.held_within(0.99), 524.288); +} + +#[test] +fn a_tree_keeps_each_call_site_once() { + let mut tree = Tree::new(); + // Innermost first: 3 called by 2 called by 1. + let a = tree.place(&[3, 2, 1], true, true); + let b = tree.place(&[3, 2, 1], true, true); + let c = tree.place(&[4, 2, 1], true, true); + assert_eq!(a, b); + assert_ne!(a, c); + assert_eq!(tree.nodes.len(), 5); + assert_eq!(tree.nodes[a as usize].parent, tree.nodes[c as usize].parent); + // A cut stack hangs under the marker, not under the first frame. + let cut = tree.place(&[3, 2, 1], false, true); + assert_ne!(cut, a); + assert_eq!(tree.nodes[1 + 4].address, CUT); + // With no room, what is new goes to the one node for it. + let nodes = tree.nodes.len(); + let full = tree.place(&[9, 8, 1], true, false); + assert_eq!(tree.nodes[full as usize].address, FULL); + assert_eq!(tree.nodes.len(), nodes + 1); + assert_eq!(tree.place(&[3, 2, 1], true, false), a); +} + +/// The hooks' own cost and the roles they give: a thread that submits is +/// followed as submitting once it has done so often enough. +#[test] +fn threads_are_followed_by_what_they_were_seen_doing() { + STATE.store(ON, Relaxed); + let stop = Arc::new(AtomicBool::new(false)); + let (submits, a) = thread({ + let stop = stop.clone(); + move || { + for _ in 0..SUBMITS { + seen(Seen::Submit); + } + for _ in 0..LIST_CALLS { + seen(Seen::Record); + } + profile_test_sleeps(&stop); + } + }); + let (records, b) = thread({ + let stop = stop.clone(); + move || { + seen(Seen::Submit); + for _ in 0..LIST_CALLS { + seen(Seen::Record); + } + profile_test_sleeps(&stop); + } + }); + let (named, c) = { + let stop = stop.clone(); + let (said, hears) = mpsc::channel(); + let running = std::thread::Builder::new() + .name("victory-wide-7".into()) + .spawn(move || { + // SAFETY: a plain query. + said.send(unsafe { GetCurrentThreadId() }).unwrap(); + profile_test_sleeps(&stop); + }) + .unwrap(); + (hears.recv().unwrap(), running) + }; + std::thread::sleep(Duration::from_millis(50)); + let mut settings = config(1000); + settings.busy = 0; + let mut sampler = Sampler::new(settings); + sampler.rescan(); + let role_of = |id: u32| sampler.threads.iter().find(|t| t.id == id).map(|t| t.role); + assert_eq!(role_of(submits), Some(Role::Submit)); + assert_eq!(role_of(records), Some(Role::Record)); + assert_eq!(role_of(named), Some(Role::Wide)); + assert!(sampler.threads.iter().all(|t| t.id != sampler.me)); + // A thread that ends is no longer looked at, and its place is free. + stop.store(true, Relaxed); + for running in [a, b, c] { + running.join().unwrap(); + } + sampler.rescan(); + sampler.rescan(); + assert!( + sampler + .threads + .iter() + .filter(|t| [submits, records, named].contains(&t.id)) + .all(|t| !t.alive) + ); + assert!( + KNOWN_THREADS + .iter() + .all(|k| ![submits, records].contains(&k.thread.load(Relaxed))) + ); + sampler.tick(); +} + +/// The sampler's own thread, as the game runs it: it finds a worker by +/// its name and a busy thread by its work, and writes the report and the +/// stacks file when its time is up. +#[test] +fn the_sampler_finds_threads_and_writes_its_files() { + let stop = Arc::new(AtomicBool::new(false)); + let named = { + let stop = stop.clone(); + std::thread::Builder::new() + .name("victory-pipelines-9".into()) + .spawn(move || { + profile_test_sleeps(&stop); + }) + .unwrap() + }; + let (_, busy) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_spins(&stop)); + } + }); + let folder = std::env::temp_dir().join(format!("victory_profile_test_{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let mut settings = config(500); + settings.out = folder.join("profile.txt"); + (settings.every, settings.length, settings.busy) = (1.2, Some(3.0), 2); + let out = settings.out.clone(); + std::thread::spawn(move || run(settings)).join().unwrap(); + stop.store(true, Relaxed); + named.join().unwrap(); + busy.join().unwrap(); + let text = std::fs::read_to_string(&out).unwrap(); + let mut stacks = out.clone().into_os_string(); + stacks.push(".folded"); + let folded = std::fs::read_to_string(&stacks).unwrap(); + let _ = std::fs::remove_dir_all(&folder); + println!("{text}"); + assert!(text.contains("=== PIPELINE WORKERS"), "{text}"); + assert!(text.contains("victory-pipelines-9")); + assert!(text.contains("=== OTHER BUSY THREADS"), "{text}"); + // The sleeping thread is seen sleeping: its wake-ups are on the same + // clock as the sampler's ticks, and are not what is sampled. + let pipelines = text.split("=== PIPELINE WORKERS").nth(1).unwrap(); + let waiting: f64 = pipelines + .split("waiting ") + .nth(1) + .and_then(|rest| rest.split('(').nth(1)) + .and_then(|rest| rest.split(' ').next()) + .and_then(|share| share.parse().ok()) + .unwrap_or_else(|| panic!("{pipelines}")); + assert!( + waiting >= 93.0, + "the sleeping thread waits {waiting} % of its time" + ); + assert!( + folded + .lines() + .any(|l| l.starts_with("busy;") && l.contains("profile_test_spin_inner")), + "{folded}" + ); + assert!( + folded + .lines() + .any(|l| l.starts_with("pipelines;") && l.contains("profile_test_sleeps")), + "{folded}" + ); + // Each stack line ends in its microseconds. + assert!(folded.lines().all(|l| { + l.rsplit(' ') + .next() + .is_some_and(|n| n.parse::().is_ok()) + })); + assert!(DONE.load(Relaxed)); +} + +/// Measures what the profiler costs the threads it looks at. Not a test +/// of anything: run it by name, in a release build: +/// `cargo test --profile diag -p victory-gpu --features diagnostics +/// profile::tests::what_looking_costs -- --ignored --nocapture`. +/// +/// Eight threads do work that is counted, one to a core and above the +/// priority other programs run at, so that a busy machine does not +/// decide the result; rounds with and without the profiler alternate. +#[test] +#[ignore = "a measurement, not a test"] +fn what_looking_costs() { + use windows_sys::Win32::System::Threading::{SetThreadAffinityMask, THREAD_PRIORITY_HIGHEST}; + #[repr(align(128))] + struct Count(AtomicU64); + const THREADS: usize = 8; + static COUNTS: [Count; THREADS] = [const { Count(AtomicU64::new(0)) }; THREADS]; + static STOP: AtomicBool = AtomicBool::new(false); + static WAITS: AtomicBool = AtomicBool::new(false); + + #[inline(never)] + fn profile_cost_work(depth: u32, count: &AtomicU64, seed: u64) -> u64 { + if depth > 0 { + return std::hint::black_box(profile_cost_work( + depth - 1, + count, + seed ^ u64::from(depth), + )) + 1; + } + let mut x = seed | 1; + while !STOP.load(Relaxed) { + for _ in 0..4096 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + } + count.fetch_add(1, Relaxed); + if WAITS.load(Relaxed) && x.is_multiple_of(64) { + // Now and then a wait, as a thread that waits for the card has. + std::thread::sleep(Duration::from_micros(500)); + } + } + x + } + + let pinned = std::thread::available_parallelism().map_or(1, |n| n.get()) >= 2 * THREADS; + let mut running = Vec::new(); + let mut ids = Vec::new(); + for (i, count) in COUNTS.iter().enumerate() { + let (id, thread) = thread(move || { + // SAFETY: plain calls on our own thread. + unsafe { + if pinned { + SetThreadAffinityMask(GetCurrentThread(), 1 << (2 * i)); + } + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + } + std::hint::black_box(profile_cost_work(30, &count.0, i as u64 + 1)); + }); + ids.push(id); + running.push(thread); + } + std::thread::sleep(Duration::from_millis(200)); + // The parts of a look at a running thread, each timed on its own. + { + // SAFETY: a thread of this test, suspended and resumed in turn; the + // context is aligned; the copy is ours. + unsafe { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + let thread = OpenThread(ACCESS, 0, ids[0]); + let mut context = Box::new(Aligned(std::mem::zeroed())); + let mut copy = vec![0u8; 256 << 10]; + let mut parts: [Vec; 5] = Default::default(); + for _ in 0..3000 { + std::thread::sleep(Duration::from_micros(300)); + context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let mut got = 0; + let t0 = Instant::now(); + SuspendThread(thread); + let t1 = Instant::now(); + GetThreadContext(thread, &mut context.0); + let t2 = Instant::now(); + ReadProcessMemory( + GetCurrentProcess(), + context.0.Rsp as *const c_void, + copy.as_mut_ptr().cast(), + 4096, + &mut got, + ); + let t3 = Instant::now(); + ResumeThread(thread); + let t4 = Instant::now(); + for (part, time) in + parts + .iter_mut() + .zip([t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0]) + { + part.push(time.as_nanos() as u64); + } + } + CloseHandle(thread); + SetThreadPriority(GetCurrentThread(), 0); + let median = |part: &mut Vec| { + part.sort_unstable(); + ( + part[part.len() / 2] as f64 / 1000.0, + part[part.len() * 9 / 10] as f64 / 1000.0, + ) + }; + let [a, b, c, d, e] = parts.each_mut().map(median); + println!( + "a look at a running thread, 3000 of them, median (and 9 in 10 under), microseconds: \ + suspend {:.1} ({:.1}), read its registers {:.1} ({:.1}), copy 4 KB of stack {:.1} ({:.1}), \ + resume {:.1} ({:.1}), all {:.1} ({:.1})", + a.0, a.1, b.0, b.1, c.0, c.1, d.0, d.1, e.0, e.1 + ); + // The kernel's copy against a plain one, by size. + let source = vec![7u8; 256 << 10]; + for size in [4usize << 10, 16 << 10, 64 << 10, 128 << 10, 256 << 10] { + let (mut kernel, mut plain) = (Vec::new(), Vec::new()); + for _ in 0..400 { + let mut got = 0; + let t0 = Instant::now(); + ReadProcessMemory( + GetCurrentProcess(), + source.as_ptr().cast(), + copy.as_mut_ptr().cast(), + size, + &mut got, + ); + let t1 = Instant::now(); + std::ptr::copy_nonoverlapping( + source.as_ptr(), + std::hint::black_box(copy.as_mut_ptr()), + size, + ); + let t2 = Instant::now(); + kernel.push((t1 - t0).as_nanos() as u64); + plain.push((t2 - t1).as_nanos() as u64); + } + println!( + "a copy of {} KB: the kernel's {:.1} us, a plain one {:.1} us (medians of 400)", + size >> 10, + median(&mut kernel).0, + median(&mut plain).0 + ); + } + } + } + let total = || COUNTS.iter().map(|c| c.0.load(Relaxed)).sum::(); + let round = Duration::from_millis(1000); + let rounds = 9; + // The timer the sampler ticks by. + { + let mut pace = Pace::new(1000, 0); + let (began, mut longest, mut last) = (Instant::now(), Duration::ZERO, Instant::now()); + for _ in 0..2000 { + pace.wait(); + longest = longest.max(last.elapsed()); + last = Instant::now(); + } + println!( + "the timer: 2000 ticks of a millisecond took {:.1} ms, the longest {:.2} ms (repeating: {})", + began.elapsed().as_secs_f64() * 1000.0, + longest.as_secs_f64() * 1000.0, + pace.repeats + ); + } + for (what, waits, reuse, budget) in [ + ( + "8 threads always running, no limit on what looks may cost (VICTORY_PROFILE_BUDGET=0)", + false, + true, + 0.0, + ), + ( + "8 threads always running, the usual limit of 3 %", + false, + true, + 0.03, + ), + ( + "8 threads that run and wait, the usual limit", + true, + true, + 0.03, + ), + ( + "8 threads that run and wait, every look a suspension (VICTORY_PROFILE_REUSE=0), no limit", + true, + false, + 0.0, + ), + ] { + WAITS.store(waits, Relaxed); + std::thread::sleep(Duration::from_millis(300)); + for hz in [1000u32, 4000] { + let (mut without, mut with) = (Vec::new(), Vec::new()); + let (mut half, mut most, mut longest, mut looks, mut reused, mut late, mut used) = + (0.0f64, 0.0f64, 0.0f64, 0, 0, 0, 0.0); + let (mut ticks, mut every) = (0, 1); + for _ in 0..rounds { + // Without the profiler. + let (from, began) = (total(), Instant::now()); + std::thread::sleep(round); + without.push((total() - from) as f64 / began.elapsed().as_secs_f64()); + // With it, on a thread of its own as in the game. + let ids = ids.clone(); + let measured = std::thread::spawn(move || { + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let mut settings = config(hz); + settings.reuse = reuse; + settings.budget = budget; + let mut sampler = Sampler::new(settings); + for &id in &ids { + sampler.follow(id, Role::Record, null_mut(), None); + } + sampler.resync(); + let mut pace = Pace::new(hz, 250); + let (cpu, from, began) = (own_cpu(), total(), Instant::now()); + while began.elapsed() < round { + pace.wait(); + sampler.tick(); + } + let rate = (total() - from) as f64 / began.elapsed().as_secs_f64(); + let used = (own_cpu() - cpu).as_secs_f64() / began.elapsed().as_secs_f64(); + let threads = &sampler.threads; + ( + rate, + used, + sampler.held_within(0.5), + sampler.held_within(0.99), + sampler.held_longest as f64 / 1000.0, + threads.iter().map(|t| t.looks).sum::(), + threads.iter().map(|t| t.reused).sum::(), + sampler.late, + threads.iter().map(|t| t.missed).sum::(), + sampler.ticks, + threads.iter().map(|t| t.every).max().unwrap_or(1), + ) + }) + .join() + .unwrap(); + with.push(measured.0); + used += measured.1 / rounds as f64; + half = half.max(measured.2); + most = most.max(measured.3); + longest = longest.max(measured.4); + looks += measured.5; + reused += measured.6; + late += measured.7; + assert_eq!(measured.8, 0, "looks that failed"); + ticks += measured.9; + every = every.max(measured.10); + } + let median = |values: &mut Vec| { + values.sort_by(f64::total_cmp); + values[values.len() / 2] + }; + let spread = |values: &[f64]| { + 100.0 * (values[values.len() - 1] - values[0]) / values[values.len() / 2] + }; + let (off, on) = (median(&mut without), median(&mut with)); + println!( + "{what}, {hz} looks a second: work done {:.2} % less with the profiler (medians of {rounds} \ + rounds of 1 s: {off:.0} against {on:.0} a second; the rounds without it differ by {:.1} %, \ + with it by {:.1} %); a suspension under {half:.0} us half the times, under {most:.0} us 99 \ + in 100, {longest:.0} us at longest; {ticks} ticks ({late} late), {looks} looks, {reused} \ + without a suspension, a thread looked at every {every} ticks at most; the sampler's \ + thread used {:.1} % of a processor", + 100.0 * (off - on) / off, + spread(&without), + spread(&with), + 100.0 * used, + ); + } + } + STOP.store(true, Relaxed); + for thread in running { + thread.join().unwrap(); + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 11d3a8c8..bccef27c 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -53,6 +53,11 @@ enum Held { Run(Vec, Vec), /// A signal of the queue's, due after what it holds before it. Signal(usize, u64), + /// With [`behind`]: the submission at the head of the line is being + /// prepared and sent by our thread, with the line unlocked, so the + /// title can add to its end meanwhile; whatever is added stays behind + /// this (the line is not empty), signals too. + Running, } /// The queues that hold something (their addresses). @@ -131,7 +136,7 @@ fn submit_cut(this: This, lists: &[This]) { let Some(host) = crate::host::host() else { return; }; - let first = if lock(&queue(this).held).is_empty() { + let first = if !behind() && lock(&queue(this).held).is_empty() { lists .iter() .position(|&l| crate::list::cut_list(l)) @@ -307,22 +312,121 @@ fn hold(this: This, what: impl FnOnce() -> Held) -> bool { /// one. #[cfg(windows)] pub(crate) fn release_held(all: bool) { + if !all && behind() { + // A thread of ours runs what is free to run ([`behind`]). + wake(); + return; + } + release_held_now(all); +} + +/// Whether a submission is only put in its queue's line by the thread +/// that submits it, and prepared and sent by a thread of ours +/// (`VICTORY_ASYNC_SUBMIT=1`; needs flights and lists cut at their waits, +/// both defaults). +/// +/// Why: the profile of run 213 (292 ms a frame) has the title's render +/// thread inside `queue::execute` for 202 ms of every frame: 155 ms in +/// `Host::submit` (preparing: the copies of title memory, the write +/// watch, descriptors, textures; and waiting for flights), while its five +/// recording threads stand idle 78 % of the time and the card 43 %. The +/// title's thread does nothing with the result of that work: it only has +/// to be done before the lists run, in order. +/// +/// With the switch a submission's lists are taken from the title's lists +/// (as they already are when the queue holds anything) and put behind +/// the queue's line; one thread of ours ([`worker`]) runs the line in +/// order. A signal of the queue goes behind them, as it does behind +/// anything held. Everything that must see earlier submissions done runs +/// the line itself first: a present, and every submission of ours that +/// is waited for ([`before_sync`]). +/// +/// What it assumes: title memory a submission reads is not rewritten by +/// the title between its submit call and the moment our thread prepares +/// it, some milliseconds later. On the console the card reads that +/// memory when it runs the list, later still, so a title that rewrote it +/// earlier would be wrong there too. +#[cfg(windows)] +pub(crate) fn behind() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") && crate::host::late() && cuts(); + if on { + tracing::info!("submissions are prepared and sent by a thread of ours, not by the thread that submits (VICTORY_ASYNC_SUBMIT=1)"); + let _ = std::thread::Builder::new().name("victory-submit".into()).spawn(worker); + } + on + }) +} + +/// Whether there is something for [`worker`] to look at. +#[cfg(windows)] +static WORK: (std::sync::Mutex, std::sync::Condvar) = (std::sync::Mutex::new(false), std::sync::Condvar::new()); + +#[cfg(windows)] +fn wake() { + *lock(&WORK.0) = true; + WORK.1.notify_one(); +} + +/// The thread of [`behind`]: runs what queues hold as far as it is free +/// to run, each time something was added or a fence moved. +#[cfg(windows)] +fn worker() { + loop { + { + let mut work = lock(&WORK.0); + while !*work { + work = WORK.1.wait(work).unwrap_or_else(|e| e.into_inner()); + } + *work = false; + } + release_held_now(false); + } +} + +#[cfg(windows)] +thread_local! { + /// This thread is inside [`release_held_now`]. + static RELEASING_HERE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Before a submission of ours that is waited for, with [`behind`]: what +/// the queues hold and is free to run runs first, on this thread, so the +/// submission keeps its place behind them. +#[cfg(windows)] +pub(crate) fn before_sync() { + if behind() && !RELEASING_HERE.get() { + release_held_now(false); + } +} + +#[cfg(windows)] +fn release_held_now(all: bool) { // One caller at a time, so a queue's submissions keep their order. static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); if lock(&WAITING).is_empty() { return; } let _one = lock(&RELEASING); + let was_here = RELEASING_HERE.replace(true); + struct Leave(bool); + impl Drop for Leave { + fn drop(&mut self) { + RELEASING_HERE.set(self.0); + } + } + let _leave = Leave(was_here); loop { let queues = lock(&WAITING).clone(); let mut moved = false; for q in queues { // SAFETY: a live queue: one released is taken off the list. - let held = unsafe { &(*(q as *const Queue)).held }; - let mut held = lock(held); + let line = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(line); loop { match held.first() { - None => break, + None | Some(Held::Running) => break, Some(&Held::Wait(fence, value)) if !all && crate::fence::completed(fence as This) < value => { @@ -332,7 +436,7 @@ pub(crate) fn release_held(all: bool) { Some(_) => {} } match held.remove(0) { - Held::Wait(..) => {} + Held::Wait(..) | Held::Running => {} Held::Value(wait) => { // Passed at a present without being met: what the // queue stood at. @@ -374,7 +478,20 @@ pub(crate) fn release_held(all: bool) { { // Not waited for: the host keeps the lists // until they are settled. - host.execute_late(lists, order); + if behind() && !all { + // The line is open while this part is + // prepared and sent: only this thread takes + // from its head (one releaser at a time). + held.insert(0, Held::Running); + drop(held); + host.execute_late(lists, order); + held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + } else { + host.execute_late(lists, order); + } } else { let ran = { let runs: Vec<&crate::host::HostList> = @@ -762,17 +879,24 @@ extern "system" fn present( ) -> HRESULT { #[cfg(all(windows, feature = "diagnostics"))] crate::copystat::present_begins(); + #[cfg(all(windows, feature = "diagnostics"))] + crate::profile::frame(); // Submissions sent to the card and not waited for are settled first, // and what that frees runs in its own order, before anything is forced. #[cfg(windows)] if crate::host::late() && !crate::host::late_free_present() { + // (With `behind`: what the queues hold runs here first, and what + // it sent is settled with the rest.) + if behind() { + release_held_now(false); + } crate::host::settle_for_present(); - release_held(false); + release_held_now(false); crate::host::settle_for_present(); } else if crate::host::late() { // The present is sent ahead too: what waits for a value a flight // will write runs behind that flight, and nothing is settled here. - release_held(false); + release_held_now(false); } // shortcut: what a queue still holds at a present runs now, whatever // its fence: a wait is not kept across frames. diff --git a/crates/victory-gpu/src/queue2.rs b/crates/victory-gpu/src/queue2.rs new file mode 100644 index 00000000..6d016d27 --- /dev/null +++ b/crates/victory-gpu/src/queue2.rs @@ -0,0 +1,1047 @@ +//! More queues on the card, for copies only (`VICTORY_QUEUE2`; off by +//! default): work of ours that does not depend on the order of the title's +//! draws goes to a copy queue of its own and no longer stands in the one +//! direct queue behind them. A copy queue runs on the card's copy engine, +//! beside the engine that draws. +//! +//! Two lanes, each a copy queue with a fence of its own, so that one never +//! stands behind the other: +//! +//! - **down** (bit 1): the fetch of the pieces shaders wrote in copies in +//! the card's memory (`Host::relay_card_back`, `Host::card_back`). With +//! the relay that fetch stood behind every flight sent since: 114-157 ms +//! a frame of the landing thread's 176-229 (run 118). +//! - **up** (bit 2): the title bytes that changed on the CPU's side of such +//! copies cross to the card's memory (`Host::card_before`), into a +//! landing buffer of ours there; the direct queue waits for them and +//! moves them on into the copies, inside the card's memory. +//! +//! What is synchronised, and with what: +//! +//! - A job of a lane may wait for fences of the direct queue +//! ([`Lane::send`]'s `after`: `ID3D12CommandQueue::Wait` on the lane's +//! queue). A fetch names the fence value behind the last flight it lands, +//! so it runs after that flight's lists and its compare. +//! - The direct queue waits for a job of the up lane ([`Second::hold`]: +//! `Wait` on the direct queue for the lane's fence), so nothing sent to +//! the direct queue afterwards runs before the bytes have landed. +//! - No wait can stand for ever: a job only ever waits for a value already +//! signalled on the direct queue, and the direct queue only for a job +//! already sent, so each wait's partner lies ahead of it in its queue. +//! - Only buffers go through the lanes. A buffer needs no state change for +//! a copy queue (it is promoted from the common state and falls back to +//! it), and it may be READ on one queue while another queue's work on it +//! is in the air; a texture may not, which is why no texture goes this +//! way. +//! - No lane WRITES a buffer that the direct queue's work in the air +//! names: the host's debug layer calls that an error ("not safe to start +//! write GPU operations now on this Command Queue", seen on the software +//! adapter with a first draft that copied title bytes straight into the +//! copies). Hence the landing buffers ([`Second::landing`]): each is +//! written by one job of the up lane and read by the direct queue behind +//! its wait for that job, and is given out again only when the card has +//! passed that read. The copies themselves change only on the direct +//! queue, in its order, as before. +//! - With the relay the sends of title bytes are numbered +//! (`crate::host::QUEUE_ORDER`). The direct queue signals each number +//! behind its send ([`Second::sent_up`]), and a fetch on the down lane +//! takes for "the sends ahead of me" those the card has finished +//! ([`Second::order_done`]). A later send that the card happens to run +//! before the fetch is left out by the merge as one that came after +//! (`Shadow::card_merge_relay`): the title's bytes stand, as they would. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +/// `VICTORY_QUEUE2`, a sum of bits; unset or 0: off, everything goes +/// through the one direct queue as before. +/// +/// - 1: fetches of what shaders wrote to copies in the card's memory go to +/// a copy queue (the gain is with `VICTORY_RELAY=1`/`2`; without the +/// relay nothing else is queued when they run, so it only shows that +/// the path works); +/// - 2: the title bytes sent up to copies in the card's memory cross from +/// the PC's memory on a copy queue, into landing buffers in the card's +/// memory ([`landing_most`] says how much of it), and the direct queue +/// moves them on from there. +/// +/// Read once, when the first submission asks. +pub(crate) fn bits() -> u32 { + static BITS: OnceLock = OnceLock::new(); + *BITS.get_or_init(|| std::env::var("VICTORY_QUEUE2").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) & 3) +} + +/// The most bytes of landing buffers in the card's memory, for title +/// bytes on their way to copies there (`VICTORY_QUEUE2_LANDING_MB`, 96; +/// a frame sent up 45-76 MB in runs 116-120, and a buffer is free again as +/// soon as the card has run the submission it was for). A send that finds +/// no room goes straight from the PC's memory on the direct queue, as +/// without the switch; the frame line counts those. +fn landing_most() -> u64 { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_QUEUE2_LANDING_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(96) << 20 + }) +} + +/// A buffer in the card's memory that title bytes land in. +struct Landing { + buffer: ID3D12Resource, + size: u64, + /// The value of the host's fence that the card passes after the direct + /// queue's last read of the buffer: free once it is reached. + until: u64, +} + +/// Which landing buffer (its size, and the fence value it is held until) +/// takes `bytes` when the host's fence has reached `completed`: the +/// smallest free one that holds them. +fn pick_landing(landings: &[(u64, u64)], bytes: u64, completed: u64) -> Option { + landings + .iter() + .enumerate() + .filter(|&(_, &(size, until))| until <= completed && size >= bytes) + .min_by_key(|&(_, &(size, _))| size) + .map(|(at, _)| at) +} + +/// An allocator and a list of the copy type. +pub(crate) type CopyList = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Since the last frame-rate line, of one lane: jobs, their bytes, +/// microseconds the lane had a job (sent and not finished: its time on the +/// card and its waits for the direct queue's fences), microseconds a thread +/// of ours stood waiting for its jobs. +#[derive(Default)] +pub(crate) struct LaneStats { + pub(crate) jobs: AtomicU64, + pub(crate) bytes: AtomicU64, + pub(crate) busy_us: AtomicU64, + pub(crate) waited_us: AtomicU64, +} + +struct LaneState { + /// Jobs sent: the last value signalled on the lane's fence. + sent: u64, + /// Lists not in use, each with the job it last ran in: free for the + /// next job once the card has run that one. + spare: Vec<(u64, CopyList)>, + /// To the lane's clock: a job and when it was sent. + clock: Option>, +} + +/// A copy queue with a fence of its own; its jobs run in the order sent. +pub(crate) struct Lane { + device: ID3D12Device, + queue: ID3D12CommandQueue, + /// Signalled on `queue` behind each job with the job's number. + fence: ID3D12Fence, + state: Mutex, + pub(crate) stats: LaneStats, +} + +// SAFETY: D3D12 devices, queues, fences, allocators and lists are +// free-threaded objects; the lists are recorded by the thread that took +// them and otherwise touched under `state`. +unsafe impl Send for Lane {} +// SAFETY: as above. +unsafe impl Sync for Lane {} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A lane's busy time grows by the stretch from `sent` (or from when the +/// job before it finished, `before`, if that was later: the lane was busy +/// with that one until then) to `done`. Returns the microseconds. +fn busy_stretch(before: Option, sent: Instant, done: Instant) -> u64 { + let from = before.map_or(sent, |b| b.max(sent)); + done.saturating_duration_since(from).as_micros() as u64 +} + +impl Lane { + fn new(device: &ID3D12Device, name: &str) -> windows::core::Result { + // SAFETY: plain object creation with valid descriptions. + unsafe { + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + })?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let wide: Vec = format!("victory copy queue ({name})").encode_utf16().chain([0]).collect(); + let _ = queue.SetName(windows::core::PCWSTR(wide.as_ptr())); + Ok(Lane { + device: device.clone(), + queue, + fence, + state: Mutex::new(LaneState { + sent: 0, + spare: Vec::new(), + clock: None, + }), + stats: LaneStats::default(), + }) + } + } + + /// Starts the lane's clock: a thread that waits for each job in turn + /// and adds up how long the lane had one ([`LaneStats::busy_us`]). + fn clocked(&'static self, name: &str) { + let (tx, rx) = channel(); + let started = std::thread::Builder::new().name(format!("victory-queue2-{name}")).spawn(move || self.watch(&rx)); + match started { + Ok(_) => lock(&self.state).clock = Some(tx), + Err(e) => tracing::warn!(error = %e, "no thread for a copy queue's clock: its milliseconds stay 0"), + } + } + + fn watch(&self, jobs: &Receiver<(u64, Instant)>) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut before = None; + while let Ok((job, sent)) = jobs.recv() { + if self.wait(job, event).is_err() { + return; + } + let done = Instant::now(); + self.stats.busy_us.fetch_add(busy_stretch(before, sent, done), Ordering::Relaxed); + before = Some(done); + } + } + + /// An open list of the copy type: one whose last job the card has run, + /// or a new one. + pub(crate) fn list(&self) -> windows::core::Result { + // SAFETY: a plain query; a list is reset only when the job it ran + // in is done; plain object creation otherwise. + unsafe { + let done = self.fence.GetCompletedValue(); + let free = { + let mut state = lock(&self.state); + state.spare.iter().position(|(job, _)| *job <= done).map(|at| state.spare.swap_remove(at).1) + }; + if let Some((allocator, list)) = free { + allocator.Reset()?; + list.Reset(&allocator, None)?; + return Ok((allocator, list)); + } + 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)?; + Ok((allocator, list)) + } + } + + /// Closes `list` (from [`Lane::list`], with copies recorded) and sends + /// it as the lane's next job, of `bytes` bytes. The job runs behind + /// the lane's earlier jobs and not before each fence of `after` (fences + /// of other queues) has reached its value: every value must have been + /// signalled on its queue already. Returns the job's number, for + /// [`Lane::wait`], [`Lane::done`] and [`Second::hold`]. + pub(crate) fn send(&self, list: CopyList, after: &[(&ID3D12Fence, u64)], bytes: u64) -> windows::core::Result { + // SAFETY: an open list of ours; the lane's queue and fence; live + // fences of the same device. + unsafe { + list.1.Close()?; + let lists = [Some(list.1.cast::()?)]; + // One job at a time from its waits to its signal: the jobs' + // numbers are the order they run in. + let mut state = lock(&self.state); + for &(fence, value) in after { + // (A fence is at 0 before anything is signalled on it: + // nothing to wait for.) + if value != 0 { + self.queue.Wait(fence, value)?; + } + } + self.queue.ExecuteCommandLists(&lists); + state.sent += 1; + let job = state.sent; + self.queue.Signal(&self.fence, job)?; + state.spare.push((job, list)); + if let Some(clock) = &state.clock { + let _ = clock.send((job, Instant::now())); + } + self.stats.jobs.fetch_add(1, Ordering::Relaxed); + self.stats.bytes.fetch_add(bytes, Ordering::Relaxed); + Ok(job) + } + } + + /// Whether the card has run `job`. + pub(crate) fn done(&self, job: u64) -> bool { + // SAFETY: a plain query. + unsafe { self.fence.GetCompletedValue() >= job } + } + + /// Waits on this thread, with its `event`, until the card has run + /// `job`. + pub(crate) fn wait(&self, job: u64, event: HANDLE) -> windows::core::Result<()> { + // SAFETY: the lane's fence and the caller's event. + unsafe { + if self.fence.GetCompletedValue() < job { + self.fence.SetEventOnCompletion(job, event)?; + WaitForSingleObject(event, INFINITE); + } + } + Ok(()) + } +} + +/// The copy queues and what ties them to the direct queue. +pub(crate) struct Second { + bits: u32, + device: ID3D12Device, + /// The landing buffers made so far ([`Second::landing`]). + landings: Mutex>, + /// The landing buffers' bytes alive; since the last frame-rate line, + /// the sends that found no room in them. + pub(crate) landing: [AtomicU64; 2], + /// Fetches (bit 1). + pub(crate) down: Lane, + /// Sends of title bytes to copies in the card's memory (bit 2). + pub(crate) up: Lane, + /// Signalled on the DIRECT queue behind each numbered send of title + /// bytes, with its number ([`Second::sent_up`]). + order: ID3D12Fence, + /// Signalled on the DIRECT queue just ahead of each wait for the up + /// lane ([`Second::hold`]), for the clock: when the direct queue got + /// there. Behind the lock: the holds made so far, and the way to the + /// thread that times them. + reached: ID3D12Fence, + holds: Mutex<(u64, Option>)>, + /// Since the last frame-rate line: waits of the direct queue for the up + /// lane, those of them at which it stood, and for how many + /// microseconds. + pub(crate) held: [AtomicU64; 3], +} + +// SAFETY: fences (free-threaded) and lanes. +unsafe impl Send for Second {} +// SAFETY: as above. +unsafe impl Sync for Second {} + +impl Second { + /// The lanes on `device`. `bits` as [`bits`]. + pub(crate) fn new(device: &ID3D12Device, bits: u32) -> windows::core::Result { + // SAFETY: plain fences on the device. + unsafe { + Ok(Second { + bits, + device: device.clone(), + landings: Mutex::new(Vec::new()), + landing: [const { AtomicU64::new(0) }; 2], + down: Lane::new(device, "down")?, + up: Lane::new(device, "up")?, + order: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + reached: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + holds: Mutex::new((0, None)), + held: [const { AtomicU64::new(0) }; 3], + }) + } + } + + /// Starts the clocks: the lanes' and the one that times the direct + /// queue's waits ([`Second::held`]). + pub(crate) fn clocked(&'static self) { + self.down.clocked("down"); + self.up.clocked("up"); + let (tx, rx) = channel(); + match std::thread::Builder::new().name("victory-queue2-holds".into()).spawn(move || self.watch_holds(&rx)) { + Ok(_) => lock(&self.holds).1 = Some(tx), + Err(e) => tracing::warn!(error = %e, "no thread to time the direct queue's waits for the copy queue: they stay 0"), + } + } + + /// Whether fetches go to the down lane. + pub(crate) fn fetches(&self) -> bool { + self.bits & 1 != 0 + } + + /// Whether title bytes go up through the up lane. + pub(crate) fn uploads(&self) -> bool { + self.bits & 2 != 0 + } + + /// A buffer in the card's memory for `bytes` title bytes on their way + /// up, for a job of the up lane to write and the direct queue to read + /// behind its wait for that job ([`Second::hold`]). `completed`: the + /// value the host's fence has reached; `until`: the value it reaches + /// when the card has run that read (the next one signalled behind + /// it). The buffer is not given out again before then, so no job + /// writes it while anything in the air names it. `None`: no room under + /// [`landing_most`], or no memory; the caller sends the bytes the old + /// way. + pub(crate) fn landing(&self, bytes: u64, completed: u64, until: u64) -> Option { + let mut landings = lock(&self.landings); + let sizes: Vec<(u64, u64)> = landings.iter().map(|l| (l.size, l.until)).collect(); + if let Some(at) = pick_landing(&sizes, bytes, completed) { + landings[at].until = until; + return Some(landings[at].buffer.clone()); + } + // A new one; free ones that are too small make room for it (the + // card has passed their last use: nothing names them). + let size = bytes.next_multiple_of(1 << 20); + let alive = |landings: &[Landing]| landings.iter().map(|l| l.size).sum::(); + if alive(&landings) + size > landing_most() { + landings.retain(|l| l.until > completed); + } + let made = if alive(&landings) + size > landing_most() { + None + } else { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a buffer in the card's memory. + let made = unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + }; + match (made, buffer) { + (Ok(()), Some(buffer)) => { + let wide: Vec = "victory landing buffer (title bytes on their way up)".encode_utf16().chain([0]).collect(); + // SAFETY: a live buffer and a terminated string. + let _ = unsafe { buffer.SetName(windows::core::PCWSTR(wide.as_ptr())) }; + landings.push(Landing { + buffer: buffer.clone(), + size, + until, + }); + Some(buffer) + } + _ => None, + } + }; + self.landing[0].store(alive(&landings), Ordering::Relaxed); + if made.is_none() { + self.landing[1].fetch_add(1, Ordering::Relaxed); + } + made + } + + /// The numbered send `number` of title bytes has just gone to `direct` + /// (or there was nothing to send under that number): the number is + /// signalled behind it. + pub(crate) fn sent_up(&self, direct: &ID3D12CommandQueue, number: u64) { + // SAFETY: a live queue and our fence. + let _ = unsafe { direct.Signal(&self.order, number) }; + } + + /// The last numbered send of title bytes the card has finished: every + /// send up to it is in what a fetch sent from now on brings down. + pub(crate) fn order_done(&self) -> u64 { + // SAFETY: a plain query. + unsafe { self.order.GetCompletedValue() } + } + + /// Makes `direct` wait for `job` of the up lane: nothing sent to it + /// from now on runs before the card has run the job. The job must have + /// been sent ([`Lane::send`]). + pub(crate) fn hold(&self, direct: &ID3D12CommandQueue, job: u64) -> windows::core::Result<()> { + let mut holds = lock(&self.holds); + holds.0 += 1; + // SAFETY: a live queue and our fences. + unsafe { + // For the clock only: the moment the queue gets to the wait. + let _ = direct.Signal(&self.reached, holds.0); + direct.Wait(&self.up.fence, job)?; + } + self.held[0].fetch_add(1, Ordering::Relaxed); + if let Some(clock) = &holds.1 { + let _ = clock.send((holds.0, job)); + } + Ok(()) + } + + /// Times the holds, in the order they were made: from the moment the + /// direct queue got to one until the job it waits for is done. (While + /// it stands at one it gets to no later one, so one thread sees each + /// in time.) + fn watch_holds(&self, holds: &Receiver<(u64, u64)>) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + while let Ok((hold, job)) = holds.recv() { + // SAFETY: our fence and this thread's event. + unsafe { + if self.reached.GetCompletedValue() < hold { + if self.reached.SetEventOnCompletion(hold, event).is_err() { + return; + } + WaitForSingleObject(event, INFINITE); + } + } + if self.up.done(job) { + continue; + } + let standing = Instant::now(); + if self.up.wait(job, event).is_err() { + return; + } + self.held[1].fetch_add(1, Ordering::Relaxed); + self.held[2].fetch_add(standing.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } +} + +/// The copy queues, made at the first ask if [`bits`] says so; `None` when +/// the switch is off or they could not be made (everything then goes +/// through the direct queue, as before). +pub(crate) fn second() -> Option<&'static Second> { + static SECOND: OnceLock> = OnceLock::new(); + static CLOCKS: std::sync::Once = std::sync::Once::new(); + if bits() == 0 { + return None; + } + let second = SECOND + .get_or_init(|| { + let host = crate::host::host()?; + match Second::new(&host.device, bits()) { + Ok(second) => { + tracing::info!( + fetches = second.fetches(), + uploads = second.uploads(), + landing_mb = landing_most() >> 20, + "copy queues on the card beside the direct queue (VICTORY_QUEUE2={})", + bits() + ); + Some(second) + } + Err(e) => { + tracing::warn!(error = %e, "no copy queues (VICTORY_QUEUE2): everything goes through the direct queue"); + None + } + } + }) + .as_ref()?; + CLOCKS.call_once(|| second.clocked()); + Some(second) +} + +/// For the frame-rate line: what the copy queues did per frame since the +/// last one. "On their queue" is from a job's send to its end with each +/// moment counted once: its time on the card and any wait of its queue +/// for the direct queue's fences. The direct queue "stood" at a wait if +/// the job was not done when it got there. +pub(crate) fn line(frames: f64) { + let Some(second) = second() else { + return; + }; + let take = |a: &AtomicU64| a.swap(0, Ordering::Relaxed) as f64 / frames; + let ms = |a: &AtomicU64| take(a) / 1000.0; + let mb = |a: &AtomicU64| take(a) / (1 << 20) as f64; + let (down, up) = (&second.down.stats, &second.up.stats); + let (down_jobs, down_mb, down_busy, down_waited) = (take(&down.jobs), mb(&down.bytes), ms(&down.busy_us), ms(&down.waited_us)); + let (up_jobs, up_mb, up_busy) = (take(&up.jobs), mb(&up.bytes), ms(&up.busy_us)); + let [holds, stood, stood_us] = [0, 1, 2].map(|i| take(&second.held[i])); + let (landing_mb, no_room) = (second.landing[0].load(Ordering::Relaxed) >> 20, take(&second.landing[1])); + tracing::info!( + "the copy queues per frame (VICTORY_QUEUE2={}): fetches of what shaders wrote: {down_jobs:.1} jobs, {down_mb:.1} MB, \ + {down_busy:.1} ms on their queue, our threads stood {down_waited:.1} ms waiting for them; title bytes sent up: \ + {up_jobs:.1} jobs, {up_mb:.1} MB, {up_busy:.1} ms on their queue; the direct queue was told to wait for them \ + {holds:.1} times and stood at {stood:.1} of those for {:.1} ms in all; landing buffers on the card: {landing_mb} MB, \ + {no_room:.1} sends found no room in them and went through the direct queue (VICTORY_QUEUE2_LANDING_MB)", + second.bits, + stood_us / 1000.0 + ); +} + +#[cfg(test)] +mod tests { + use super::*; + 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::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::core::s; + + /// A lane's busy time counts each moment once: a job sent while the + /// one before it still ran adds only what came after that one. + #[test] + fn a_lanes_busy_time_counts_each_moment_once() { + let t = Instant::now(); + let at = |ms: u64| t + std::time::Duration::from_millis(ms); + // Alone: from the send to the end. + assert_eq!(busy_stretch(None, at(10), at(14)), 4_000); + // Sent at 10 while the job before ran until 12: 12 to 14. + assert_eq!(busy_stretch(Some(at(12)), at(10), at(14)), 2_000); + // Sent after the one before had finished: from the send. + assert_eq!(busy_stretch(Some(at(5)), at(10), at(14)), 4_000); + // (The clock's own lateness never makes a stretch negative.) + assert_eq!(busy_stretch(Some(at(20)), at(10), at(14)), 0); + } + + /// A landing buffer is given out again only when the card has passed + /// its last use, and the smallest one that holds the bytes is taken. + #[test] + fn a_landing_buffer_is_free_when_the_card_has_passed_its_use() { + // (size, held until this value of the host's fence) + let landings = [(4 << 20, 10), (1 << 20, 12), (2 << 20, 7), (8 << 20, 7)]; + // The card is at 9: the third and fourth are free. + assert_eq!(pick_landing(&landings, 1 << 20, 9), Some(2)); + assert_eq!(pick_landing(&landings, 3 << 20, 9), Some(3)); + assert_eq!(pick_landing(&landings, 9 << 20, 9), None); + // At 10 the first is free too, and is the smallest for 3 MiB. + assert_eq!(pick_landing(&landings, 3 << 20, 10), Some(0)); + // At 6 none is: a use that the card has not passed holds its buffer. + assert_eq!(pick_landing(&landings, 1, 6), None); + // The value itself frees it (the signal is behind the read). + assert_eq!(pick_landing(&landings, 1, 7), Some(2)); + assert_eq!(pick_landing(&[], 1, u64::MAX), None); + } + + /// A shader of the direct queue that takes a while and then stores a + /// dword: `at` (bytes) gets `value`. + const SLOW_STORE: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), UAV(u0)" +cbuffer What : register(b0) { uint at; uint value; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = value; + [loop] + for (uint i = 0; i < spin; i++) { + h = (h ^ memory.Load((i & 63u) * 4u)) * 0x01000193u; + } + memory.Store(at, value + (h & 0u)); +} +"#; + + /// The software adapter with a direct queue and the copy queues. + struct Warp { + device: ID3D12Device, + direct: ID3D12CommandQueue, + /// The direct queue's fence and the last value signalled on it. + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + second: &'static Second, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// Direct lists sent and not waited for yet. + flown: Vec, + } + + impl Warp { + fn new(bits: u32) -> Option { + // SAFETY: plain DXGI and D3D12 set-up on the software adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let direct: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + // The clocks' threads live as long as the process: the + // queues of a test are kept for them. + let second: &'static Second = Box::leak(Box::new(Second::new(&device, bits).expect("copy queues on WARP"))); + second.clocked(); + let mut code: Option = None; + D3DCompile( + SLOW_STORE.as_ptr().cast(), + SLOW_STORE.len(), + s!("slow store"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + ) + .expect("the test's shader compiles"); + let code = code?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), 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()?; + Some(Warp { + device, + direct, + fence, + submitted: 0, + event, + second, + root, + pso, + flown: Vec::new(), + }) + } + } + + /// A buffer as the host makes them: in the card's own memory + /// (`Host::uav_buffer`), or in the PC's memory and mapped + /// (`Host::shared_buffer`). + fn buffer(&self, size: u64, mapped: bool) -> (ID3D12Resource, *mut u8) { + let heap = if mapped { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } else { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..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: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation, and a mapping of CPU-visible memory. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .expect("a test buffer"); + let buffer = buffer.expect("a test buffer"); + if mapped { + buffer.Map(0, None, Some(&mut data)).expect("a mapping"); + } + (buffer, data.cast()) + } + } + + /// Sends a list of the direct queue made by `record`, with a + /// signal behind it, and does not wait: the value signalled. + fn fly(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> u64 { + // SAFETY: plain creation; an open list of ours; our queue and + // fence. + unsafe { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("an allocator"); + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).expect("a list"); + record(&list); + list.Close().expect("the list closes"); + self.direct.ExecuteCommandLists(&[Some(list.cast().expect("a command list"))]); + self.submitted += 1; + self.direct.Signal(&self.fence, self.submitted).expect("a signal"); + self.flown.push((allocator, list)); + } + self.submitted + } + + /// A direct list that stores `value` at byte `at` of `memory` + /// after `spin` steps. + fn store(&mut self, memory: &ID3D12Resource, at: u32, value: u32, spin: u32) -> u64 { + let (root, pso) = (self.root.clone(), self.pso.clone()); + // SAFETY: a live buffer with unordered access; the shader's + // own root signature. + self.fly(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + let constants = [at, value, spin]; + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRootUnorderedAccessView(1, memory.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + }) + } + + /// Waits for everything sent to the direct queue and the lanes. + fn land(&mut self) { + // SAFETY: our fence and event. + unsafe { + self.fence.SetEventOnCompletion(self.submitted, self.event).expect("a wait"); + WaitForSingleObject(self.event, INFINITE); + } + for lane in [&self.second.down, &self.second.up] { + let last = lock(&lane.state).sent; + lane.wait(last, self.event).expect("a wait"); + } + assert!( + // SAFETY: a plain query. + unsafe { self.device.GetDeviceRemovedReason() }.is_ok(), + "the software adapter lost the device" + ); + self.flown.clear(); + } + } + + /// The dwords of a mapped buffer. + fn dwords(data: *mut u8, at: usize, n: usize) -> Vec { + // SAFETY: the caller's mapping holds them. + (0..n).map(|i| unsafe { data.cast::().add(at + i).read_volatile() }).collect() + } + + /// What shaders wrote, read back through the down lane, is what the + /// direct queue reads back: the same bytes of a buffer in the card's + /// memory come down both ways, and the lane's copy is behind the fence + /// of the submission that wrote them without any wait of ours between. + #[test] + fn warp_a_fetch_through_the_copy_queue_brings_what_the_direct_queue_brings() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + const DWORDS: usize = 4096; + let bytes = (DWORDS * 4) as u64; + let (card, _) = warp.buffer(bytes, false); + let (down_direct, direct_data) = warp.buffer(bytes, true); + let (down_lane, lane_data) = warp.buffer(bytes, true); + for round in 1..=3u32 { + // "Shader writes": a few dwords, each by a dispatch. + let mut behind = 0; + for i in 0..24u32 { + behind = warp.store(&card, (i * 163 % DWORDS as u32) * 4, round * 1000 + i, 20_000); + } + // Through the lane, behind the writes' fence; no wait of ours. + let second = warp.second; + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&down_lane, 0, &card, 0, bytes) }; + let job = second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + // And through the direct queue, as before. + // SAFETY: an open list; live buffers. + warp.fly(|list| unsafe { list.CopyBufferRegion(&down_direct, 0, &card, 0, bytes) }); + second.down.wait(job, warp.event).expect("the fetch is waited for"); + assert!(second.down.done(job)); + warp.land(); + let (direct, lane) = (dwords(direct_data, 0, DWORDS), dwords(lane_data, 0, DWORDS)); + assert_eq!(direct, lane, "round {round}: the two ways brought different bytes"); + for i in 0..24u32 { + assert_eq!(lane[(i * 163 % DWORDS as u32) as usize], round * 1000 + i, "round {round}, write {i}"); + } + } + assert_eq!(warp.second.down.stats.jobs.load(Ordering::Relaxed), 3); + } + + /// Ordering under the fences, nothing waited for on the CPU: write k + /// goes to the direct queue with a signal behind it, and fetch k, sent + /// at once to the lane behind that signal, must hold writes 1..=k + /// (later writes may or may not be in it: they are newer, never + /// older). Sixteen of each are in the air together. + #[test] + fn warp_a_fetch_behind_a_fence_holds_everything_sent_before_that_fence() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + const N: usize = 16; + let bytes = (N * 4) as u64; + let (card, _) = warp.buffer(64 << 10, false); + let (down, data) = warp.buffer(bytes * N as u64, true); + let second = warp.second; + for k in 0..N { + let behind = warp.store(&card, (k * 4) as u32, 0xA000 + k as u32, 60_000); + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers; the slot is inside. + unsafe { list.1.CopyBufferRegion(&down, k as u64 * bytes, &card, 0, bytes) }; + second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + } + warp.land(); + for k in 0..N { + let slot = dwords(data, k * N, N); + for (i, &got) in slot.iter().enumerate().take(k + 1) { + assert_eq!(got, 0xA000 + i as u32, "fetch {k} ran before write {i}, which was sent before its fence"); + } + for (i, &got) in slot.iter().enumerate().skip(k + 1) { + assert!(got == 0 || got == 0xA000 + i as u32, "fetch {k} holds {got:#x} for write {i}"); + } + } + } + + /// Title bytes sent up through the up lane are there when the direct + /// queue goes on: each of sixteen sends is followed, with no wait of + /// ours, by a direct list that reads the buffer back, and each read + /// holds its own send and all before it. Each send is made late on + /// purpose (it stands behind a slow list of the direct queue), so the + /// read would come first if the direct queue did not wait. The + /// numbered sends are signalled in order, and the clock saw the holds. + #[test] + fn warp_the_direct_queue_goes_on_only_when_what_was_sent_up_is_there() { + let Some(mut warp) = Warp::new(3) else { + return; + }; + const N: usize = 16; + const PART: u64 = 64 << 10; + let (staging, staged) = warp.buffer(PART * N as u64, true); + // A buffer in the card's memory per send: the lane writes one that + // nothing in the air names yet (as it writes landing buffers). + let cards: Vec = (0..N).map(|_| warp.buffer(PART, false).0).collect(); + let (other, _) = warp.buffer(64 << 10, false); + // What each read brings: the first dword of every part. + let (down, data) = warp.buffer((N * N * 4) as u64, true); + let second = warp.second; + for k in 0..N { + // The title's bytes of part k (the CPU's side of the copy). + for i in 0..(PART as usize / 4) { + // SAFETY: inside the mapping; nothing on the card reads + // part k before the send below. + unsafe { staged.cast::().add(k * (PART as usize / 4) + i).write_volatile(0xB000 + k as u32) }; + } + let slow = warp.store(&other, 0, k as u32, 80_000); + let list = second.up.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&cards[k], 0, &staging, k as u64 * PART, PART) }; + let job = second.up.send(list, &[(&warp.fence, slow)], PART).expect("the bytes are sent up"); + second.hold(&warp.direct, job).expect("the direct queue waits"); + second.sent_up(&warp.direct, k as u64 + 1); + // SAFETY: an open list; live buffers; the slots are inside. + warp.fly(|list| unsafe { + for (part, card) in cards.iter().enumerate().take(k + 1) { + list.CopyBufferRegion(&down, ((k * N + part) * 4) as u64, card, 0, 4); + } + }); + } + warp.land(); + assert_eq!(second.order_done(), N as u64); + for k in 0..N { + let read = dwords(data, k * N, N); + for (part, &got) in read.iter().enumerate().take(k + 1) { + assert_eq!(got, 0xB000 + part as u32, "the direct queue's read {k} ran before send {part} was on the card"); + } + } + assert_eq!(second.held[0].load(Ordering::Relaxed), N as u64); + assert_eq!(second.up.stats.bytes.load(Ordering::Relaxed), PART * N as u64); + } + + /// The way title bytes go up with bit 2, as `Host::card_before` does + /// it: a job of the up lane brings them into a landing buffer while a + /// slow list of the direct queue is still running, the direct queue + /// waits for the job and then copies from the landing buffer into the + /// copy. A shader's store to the same bytes, sent before, must lose to + /// them (the copy changes in the direct queue's order, as on one + /// queue), and what a fetch through the down lane brings is what the + /// direct queue reads. Twelve rounds in the air together, each with a + /// landing buffer of its own until the card has passed its use. + #[test] + fn warp_title_bytes_reach_the_copy_through_a_landing_buffer_in_the_direct_queues_order() { + let Some(mut warp) = Warp::new(3) else { + return; + }; + const N: usize = 12; + let (staging, staged) = warp.buffer(64 << 10, true); + let (card, _) = warp.buffer(64 << 10, false); + let (down, data) = warp.buffer((N * 4) as u64, true); + let (down_lane, lane_data) = warp.buffer((N * 4) as u64, true); + let second = warp.second; + let mut landings = Vec::new(); + for k in 0..N { + let at = (k * 256) as u64; + // SAFETY: inside the mapping; read by the card only through + // the job below. + unsafe { staged.add(at as usize).cast::().write_volatile(0xC000 + k as u32) }; + // A shader's (slow) store to the same dword, sent first. + warp.store(&card, at as u32, 0xDEAD_0000 + k as u32, 80_000); + // SAFETY: a plain query. + let completed = unsafe { warp.fence.GetCompletedValue() }; + let landing = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + let list = second.up.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&landing, 0, &staging, at, 4) }; + let job = second.up.send(list, &[], 4).expect("the bytes are sent up"); + second.hold(&warp.direct, job).expect("the direct queue waits"); + // SAFETY: an open list; live buffers. + let read = warp.fly(|list| unsafe { + list.CopyBufferRegion(&card, at, &landing, 0, 4); + list.CopyBufferRegion(&down, (k * 4) as u64, &card, at, 4); + }); + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&down_lane, (k * 4) as u64, &card, at, 4) }; + second.down.send(list, &[(&warp.fence, read)], 4).expect("the fetch is sent"); + landings.push(landing.as_raw() as usize); + } + warp.land(); + let want: Vec = (0..N).map(|k| 0xC000 + k as u32).collect(); + assert_eq!(dwords(data, 0, N), want, "the title's bytes did not reach the copy behind the shader's store"); + assert_eq!(dwords(lane_data, 0, N), want, "the copy queue's fetch differs from the direct queue's"); + // No buffer was given out while its last use was in the air: one + // given to two rounds was free in between. + landings.sort_unstable(); + landings.dedup(); + assert!(!landings.is_empty() && landings.len() <= N); + // Everything has run: the next ask takes one of them, makes none. + let alive = second.landing[0].load(Ordering::Relaxed); + // SAFETY: a plain query. + let completed = unsafe { warp.fence.GetCompletedValue() }; + let again = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + assert!(landings.contains(&(again.as_raw() as usize))); + assert_eq!(second.landing[0].load(Ordering::Relaxed), alive); + } + + /// Lists of a lane come back for the next job once the card has run + /// the job they were in, and not before. + #[test] + fn warp_a_lanes_lists_are_used_again_only_after_their_job() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + let (card, _) = warp.buffer(64 << 10, false); + let (down, _) = warp.buffer(64 << 10, true); + let second = warp.second; + // A job that cannot run yet: it waits for a fence value the direct + // queue reaches only after a slow store. + let behind = warp.store(&card, 0, 1, 400_000); + let first = second.down.list().expect("a copy list"); + let first_list = first.1.as_raw(); + // SAFETY: an open copy list; live buffers. + unsafe { first.1.CopyBufferRegion(&down, 0, &card, 0, 64) }; + let job = second.down.send(first, &[(&warp.fence, behind)], 64).expect("sent"); + if !second.down.done(job) { + // Still in the air: the next list is another one. + let next = second.down.list().expect("a copy list"); + assert_ne!(next.1.as_raw(), first_list, "a list was reset while its job had not run"); + second.down.send(next, &[], 0).expect("sent"); + } + warp.land(); + // Everything has run: a list of before comes back. + let again = second.down.list().expect("a copy list"); + let spare_left = lock(&second.down.state).spare.len(); + assert!(spare_left <= 1, "lists that have run are taken before new ones are made"); + second.down.send(again, &[], 0).expect("sent"); + warp.land(); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 756462d0..458583d6 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1747,6 +1747,46 @@ pub(crate) fn merged_stats() -> [u64; 3] { [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) } +/// `runs` (in order) with those a gap of `gap` bytes or fewer apart made +/// one run, the gap's bytes included. +fn joined_over(runs: Vec<(usize, usize)>, gap: usize) -> Vec<(usize, usize)> { + if gap == 0 || runs.len() < 2 { + return runs; + } + let mut out: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for (at, n) in runs { + match out.last_mut() { + Some(last) if at - (last.0 + last.1) <= gap => last.1 = at + n - last.0, + _ => out.push((at, n)), + } + } + out +} + +/// The gap, in bytes, over which the title bytes put into a copy in the +/// card's memory under flights' shader writes are joined into one run +/// (`VICTORY_MERGE_GAP`, 0 to 64; 0 by default: only the bytes the title +/// changed go up, as before). +/// +/// Run 219: the title rewrites some hundred pages of its big buffer a +/// frame while flights that may write that buffer are in the air, and +/// byte by byte the new content differs from the old in 38,000 runs a +/// frame (equal bytes in between, mostly zeros), far over the 512 runs a +/// submission may send, so the flights were settled twice a frame, 50 ms +/// of the submitting thread. Joined over small gaps the same pages are a +/// few runs. +/// +/// What it gives up: a gap byte is equal in title memory and on the CPU +/// side of the copy, and goes up with its run. If a flight in the air +/// wrote exactly that byte on the card (a shader store within `gap` bytes +/// between two bytes the title changed in the same frame), the store is +/// overwritten with the old value, and no compare finds it. Exact (0) is +/// the default for that reason. +fn merge_gap() -> usize { + static GAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *GAP.get_or_init(|| std::env::var("VICTORY_MERGE_GAP").ok().and_then(|v| v.trim().parse::().ok()).map_or(0, |n| n.min(64))) +} + /// The runs of bytes where `now` differs from `was` (of one length), as /// (offset, bytes) in order: every differing byte is in a run and no equal /// byte is. @@ -2485,6 +2525,7 @@ impl Shadow { continue; }; let at = at + first; + crate::host::shaders_write(start + at, &title[..n.min(title.len())]); crate::watch::writing(start + at, n); // Only the GPU's bytes (upstream #2009): the rest of the // stretch is the title's as read, and a title write landing @@ -2581,6 +2622,7 @@ impl Shadow { if !merge_piece(now, held, title) { return 0; } + crate::host::shaders_write(start + at, &title[..]); crate::watch::writing(start + at, n); merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); @@ -2836,7 +2878,7 @@ impl Shadow { // SAFETY: inside the mapping of the copy's CPU side, // which only the submitting thread writes. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let runs = changed_runs(title, held); + let runs = joined_over(changed_runs(title, held), merge_gap()); if runs.len() > *runs_left { return true; } @@ -3201,6 +3243,7 @@ impl Shadow { *o = merged; } if differs != 0 { + crate::host::shaders_write(start + at, &title[..]); crate::watch::writing(start + at, n); merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); @@ -3280,6 +3323,7 @@ impl Shadow { if !mapped || !changed { return 0; } + crate::host::shaders_write(start + at, &title[..]); crate::watch::writing(start + at, n); merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index bdac9f75..a3e7c163 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -69,6 +69,62 @@ pub(crate) struct Staging { /// recorded again about a second later if the card has room by then /// ([`upload`]). waiting: std::sync::atomic::AtomicU64, + /// The size of the buffer if it came from the pool of spare staging + /// buffers and goes back to it ([`staging_buffer`]); 0: a buffer of its + /// own, released when this is dropped. + pooled: u64, +} + +/// A staging buffer nothing holds: the buffer and where it is mapped. +struct Spare(ID3D12Resource, usize); + +// SAFETY: a D3D12 buffer and its mapping, touched by nobody while it is +// spare. +unsafe impl Send for Spare {} + +/// Spare staging buffers by size (a power of two), and their bytes in all. +static SPARE: Mutex<(std::collections::BTreeMap>, u64)> = + Mutex::new((std::collections::BTreeMap::new(), 0)); +/// The most bytes kept spare, and the largest buffer that is pooled. +const SPARE_MOST: (u64, u64) = (256 << 20, 8 << 20); +/// Staging buffers taken from the spare ones, and made, since the start. +pub(crate) static SPARE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// A mapped upload buffer of `total` bytes for a texture's staging, all +/// zeros, and its pool size (0: not pooled). +/// +/// Every texture the title streams in got a buffer of its own from the +/// host and gave it back when its staging went: about a quarter of a +/// millisecond to make (run 213's profile: 25 ms a frame on the recording +/// threads for some 100 uploads, most of it the graphics kernel waiting) +/// and more to free on the thread that submits. A streaming burst is 200 +/// to 500 uploads in a frame (run 222), and those are the frames that +/// dip. Buffers of up to 8 MiB are now kept by size and used again, +/// zeroed as a new one is (levels not there yet must read as zeros). +/// `VICTORY_STAGING_POOL=0`: made and freed each time, as before. +fn staging_buffer(host: &crate::host::Host, total: u64) -> Option<(ID3D12Resource, *mut u8, u64)> { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + let size = total.max(64 << 10).next_power_of_two(); + if size > SPARE_MOST.1 || !*ON.get_or_init(|| std::env::var_os("VICTORY_STAGING_POOL").is_none_or(|v| v != "0")) { + return host.upload_buffer(total).map(|(buffer, data)| (buffer, data, 0)); + } + let spare = { + let mut all = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + let taken = all.0.get_mut(&size).and_then(Vec::pop); + if taken.is_some() { + all.1 -= size; + } + taken + }; + if let Some(Spare(buffer, data)) = spare { + SPARE_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // SAFETY: the buffer's own mapping, `size` bytes, which nothing + // else holds. + unsafe { std::ptr::write_bytes(data as *mut u8, 0, total as usize) }; + return Some((buffer, data as *mut u8, size)); + } + SPARE_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + host.upload_buffer(size).map(|(buffer, data)| (buffer, data, size)) } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -401,6 +457,15 @@ impl Drop for Staging { use std::sync::atomic::Ordering::Relaxed; STAGED[0].fetch_sub(1, Relaxed); STAGED[1].fetch_sub(self.bytes, Relaxed); + // Nothing holds the staging any more (lists keep it until they are + // reset, after their submission has run): its buffer is spare. + if self.pooled != 0 { + let mut all = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if all.1 + self.pooled <= SPARE_MOST.0 { + all.1 += self.pooled; + all.0.entry(self.pooled).or_default().push(Spare(self.buffer.clone(), self.data as usize)); + } + } } } @@ -1395,7 +1460,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { Some(&mut total), ); } - let (buffer, data) = host.upload_buffer(total)?; + let (buffer, data, pooled) = staging_buffer(host, total)?; crate::host::name(&buffer, || { format!( "staging of {resource:?} {}x{}x{} f{}", @@ -1424,6 +1489,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { detiled: std::sync::atomic::AtomicU32::new(0), judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], waiting: std::sync::atomic::AtomicU64::new(0), + pooled, }); map.insert(resource as usize, s.clone()); Some(s) From a25370661ed1343e2f2d5e79669ec8db4e60dc68 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:06:42 -0500 Subject: [PATCH 05/16] Frame rate, third session: a frame log and a card meter, the driver watch, a forbidden self-copy removed; draw windows measured at 6.0 -> 8.9 frames a second - VICTORY_FRAME_LOG (on in diagnostics builds): every frame's length, and what the usual frame and each long frame were made of; VICTORY_CARD_METER adds the card's time by kind of list. - VICTORY_CAPTURE_WORLD_EVERY: a saved frame costs 235 ms inside the present, which was the regular dip of test runs (every 8th frame). - A driver watch (VICTORY_DRIVER_WATCH=0: off): entries of a display driver in the system's event log are logged as they are recorded; the first one turns draw windows off for the rest of the run. Every device loss here was announced that way 2.7 to 55 seconds ahead. - A copy between two title textures that share one host texture is left out (the host does not allow a texture copied onto itself): 402 in a five-minute run. - The list of shader-visible heaps is a reader-writer lock; the heap sync takes a changed page's records under one lock; guarded view memory is left out of the write-watch askings ahead (after triippywhale cc368c7c, d0581a55). - Behind switches, off by default: VICTORY_COPY_PLAIN, VICTORY_REFRESH_ONCE (after upstream 6d021fe), VICTORY_VIEW_KNOWN, VICTORY_BACK_OWN_VIEW, VICTORY_ASYNC_PRESENT, VICTORY_BVH_HOLD (refused: the picture loses its indirect light), VICTORY_CARD_REHASH_RUNS=alt. - The process opts out of the system's efficiency mode. - README: what the instruments measured and what is still open. Measured on an RTX 4070 in the first room: 6.0 frames a second on average with windows off, 8.9 with VICTORY_INDIRECT_WINDOW=1 (one run each, the second with the driver watch; no driver entry, no device loss). This merged tree was built; the unit tests of the changed parts were run on the development tree, the whole suite was not. One test of the indirect budget on the software adapter is flaky (it was before these changes). Co-Authored-By: Claude Fable 5.2 --- README.md | 68 ++- crates/victory-gpu/Cargo.toml | 2 +- crates/victory-gpu/src/capture.rs | 18 +- crates/victory-gpu/src/cardmeter.rs | 242 +++++++++ crates/victory-gpu/src/copystat.rs | 13 +- crates/victory-gpu/src/descriptor.rs | 45 +- crates/victory-gpu/src/descriptor/host.rs | 68 +++ crates/victory-gpu/src/draw.rs | 19 +- crates/victory-gpu/src/drvwatch.rs | 188 +++++++ crates/victory-gpu/src/frame.rs | 6 + crates/victory-gpu/src/framelog.rs | 584 +++++++++++++++++++++ crates/victory-gpu/src/host.rs | 321 ++++++++++- crates/victory-gpu/src/inplace.rs | 115 ++++ crates/victory-gpu/src/lib.rs | 8 + crates/victory-gpu/src/list.rs | 50 +- crates/victory-gpu/src/pipeline.rs | 95 ++++ crates/victory-gpu/src/pipeline/make.rs | 1 + crates/victory-gpu/src/plaincopy.rs | 239 +++++++++ crates/victory-gpu/src/queue.rs | 183 ++++++- crates/victory-gpu/src/shadow.rs | 57 ++ crates/victory-gpu/src/texture.rs | 11 +- crates/victory-gpu/src/watch.rs | 107 +++- crates/victory-hle/src/modules/dstorage.rs | 7 + crates/victory-hle/src/runtime.rs | 14 +- 24 files changed, 2400 insertions(+), 61 deletions(-) create mode 100644 crates/victory-gpu/src/cardmeter.rs create mode 100644 crates/victory-gpu/src/drvwatch.rs create mode 100644 crates/victory-gpu/src/framelog.rs create mode 100644 crates/victory-gpu/src/plaincopy.rs diff --git a/README.md b/README.md index 1f9fdd09..c535ede2 100644 --- a/README.md +++ b/README.md @@ -85,10 +85,11 @@ What did it, on top of the list below: checker (`VICTORY_INDIRECT_WINDOW_CHECK=1`) then showed one list drawing 90 records of 2^24 vertices from a window, where the per-draw path lets eight through; a record of 2^23 vertices an instance or more now runs - empty. Since that fix: five runs with windows on, no device loss, the - card's time per frame roughly halved. One loss after the fix had the - in-flight fetch (#648) on as well; do not combine the two. The in-flight - fetch itself measured slower here in two runs and stays off. + empty. Since that fix: eight runs with windows on, seven without a + device loss and one that lost the device 44 s into the world (cause not + found; see the driver watch below). One earlier loss after the fix had + the in-flight fetch (#648) on as well; do not combine the two. The + in-flight fetch itself measured slower here in two runs and stays off. - Frame rate, second night (an RTX 4070; the first room went from about 3.5-4 to 6-7 frames a second with ALL of the switches below; the defaults are unchanged and give about 4.5-5): @@ -113,11 +114,60 @@ What did it, on top of the list below: reused instead of made and freed every frame. - `VICTORY_PROFILE=1` (diagnostics builds): a sampling profiler inside the layer; it is how the above was found. - Still open: the frame rate dips (5-second readings of 300-500 ms among - 150-215); in some of them texture uploads are 3-5 times the usual, in - others nothing logged stands out. Not shader compiles (checked: 4-9 - first uses and no waiting in those readings). A per-frame logger is the - next step. +- Frame rate, third session: measuring first (same RTX 4070, first room). + - A frame log (`VICTORY_FRAME_LOG`, on in diagnostics builds): every + frame's length, and for the usual frame and each long one what it was + made of (the render thread's time in the present call, the submit + thread's work, copies, copy-back, recording, texture work, faults, + disk). A card meter (`VICTORY_CARD_METER`) adds the card's time by + kind of list from a timestamp at each list's start and end. + - What they showed, windows off: a usual frame of 136 ms; the title's + render thread waits 77 ms of it in the present call for the submit + thread, which works 118 ms (copies of title memory 41, copy-back 40); + the card is 85-98 % busy, of about 130 ms a frame 16 ms in our lists + that bring card copies up to date, 10 ms in our compare lists and 102 + ms in the title's own lists with the per-record clamp. Frame time is + linear in draws (about 32 microseconds a draw all-in): the title draws + about twice as much on some frames, which are the long ones. + - The regular dips of earlier test runs were the test harness: a saved + frame (`VICTORY_CAPTURE_WORLD`, every 8th world frame) is read back + and written as a PNG inside the present, 235 ms each. + `VICTORY_CAPTURE_WORLD_EVERY=64` for runs that measure speed. + - `VICTORY_INDIRECT_WINDOW=1` measured again with those instruments: + 6.0 -> 8.9 frames a second on average in the first room, 3.1 -> 4.2 + in the opening cutscene. + - A driver watch (on by default; `VICTORY_DRIVER_WATCH=0` off): the + layer subscribes to the system's event log and logs every entry of a + display driver as it is recorded; the first one turns draw windows + off for the rest of the run. Every device loss here had such entries + 2.7 to 55 seconds before the device was removed, and no run without + them lost its device. + - A copy between two title textures that share one host texture is no + longer recorded (the host does not allow a texture copied onto + itself): 402 of them in a five-minute run. + - The list of shader-visible heaps is a reader-writer lock (recording + threads waited 48 ms a frame, summed, behind the heap sync); the heap + sync looks at a changed page's records under one lock, fingerprint + first; guarded view memory is left out of a submission's write-watch + askings ahead (after triippywhale). + - Behind switches, built and unit-tested, not yet shown to pay: + `VICTORY_COPY_PLAIN=1` (copies of title memory made in place by this + process, with a handler that falls back to the kernel's copy on a + missing page), `VICTORY_REFRESH_ONCE=1`, `VICTORY_VIEW_KNOWN=1`, + `VICTORY_BACK_OWN_VIEW=1` (picture to be checked), + `VICTORY_ASYNC_PRESENT=1` (the present goes behind the queue's line; + no gain while the card is the limit). + - Tried and refused: `VICTORY_BVH_HOLD=1` holds back the 64 programs + that walk ray-tracing structures nothing has built; the picture loses + its indirect light with it, so it stays off. + - The process opts out of the system's efficiency mode + (`VICTORY_EFFICIENCY_MODE=1` leaves it); on a hybrid processor the + frame log found the title's render and recording threads on fast + cores in every look of a run, and the layer's submit thread on a slow + core in 6 % of its looks. + Still open: the per-record clamp is most of the card's time, and the + copies between the PC's memory and the card's are most of the submit + thread's; the cause of the one device loss with windows is not known. - Known and counted, not fixed yet: an indirect compute pass asks for about 77,500 thread groups in x where one dispatch runs 65,535 (the rest is cut off). diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index d380f3a9..fca8c785 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -27,7 +27,7 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_EventLog", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 19947f3c..64695fe1 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -120,6 +120,22 @@ fn world_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some()) } +/// Every how many world frames a picture is saved with +/// `VICTORY_CAPTURE_WORLD` (`VICTORY_CAPTURE_WORLD_EVERY`, 8 unless said). +/// +/// A saved frame is read back at once and written as a PNG inside the +/// present: run 225's frame log has every saved frame of the cell at 371 ms +/// against a usual 136 (the present's own copy and show 137 ms instead of +/// 2, and 123 ms more waiting for the card). At every 8th frame that was +/// the regular dip of every test run, and a fifth of its time. A run that +/// measures speed asks for 64 or more. +fn world_every() -> u64 { + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + std::env::var("VICTORY_CAPTURE_WORLD_EVERY").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(8) + }) +} + /// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`). static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); @@ -151,7 +167,7 @@ pub(crate) fn wanted(n: u64) -> bool { // cutscene (its shots do not fall on the same frame numbers from run to // run, so single frames cannot be compared between runs). let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); - let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(8); + let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(world_every()); folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) } diff --git a/crates/victory-gpu/src/cardmeter.rs b/crates/victory-gpu/src/cardmeter.rs new file mode 100644 index 00000000..9491f06f --- /dev/null +++ b/crates/victory-gpu/src/cardmeter.rs @@ -0,0 +1,242 @@ +//! What the card's time goes to, by kind of list, in every run. +//! +//! The card's clock (`crate::host`) says how long the card had work of +//! ours, not which work. The timing run (`VICTORY_GPU_TIMING`) names every +//! title command but sends each list on its own, which changes the frame, +//! and it never timed the lists the layer adds for itself: the one that +//! brings copies in the card's memory up to date and hashes their pieces +//! again, and the one that compares pieces after a submission's lists. +//! Run 187's table left 64 ms a frame of card time unexplained beside +//! them (40 ms by the count outside timing runs); with draw windows off +//! the card is the frame's limit (run 225: 85 to 98 % busy), so that sum +//! decides what is worth changing. +//! +//! Here a list gets one timestamp where it begins and one where it ends, +//! both resolved into one read-back buffer by the list itself. The card +//! writes them when it gets there; a pair is read a second and a half +//! after it was recorded, when every flight of that time has long landed, +//! and its length goes to the frame log's totals by kind. So the frame +//! log's card columns are of the frames of a moment ago: right for the +//! usual frame, not for placing one long frame. +//! +//! On by default in diagnostics builds; `VICTORY_CARD_METER=0` or `1` says +//! otherwise. Two queries and a resolve a list. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +/// What a timed list is. +#[derive(Clone, Copy)] +pub(crate) enum Kind { + /// Ours: changed bytes go up to copies in the card's memory and their + /// pieces are hashed again (`Host::card_before`). + Sync, + /// Ours: the compare of the pieces a submission's shaders may have + /// written, and the fetch of the flagged ones inside the flight. + Check, + /// Every other host list: the title's own, our present copies. + Lists, +} + +/// Pairs of timestamps in the ring. +const PAIRS: u32 = 8192; +/// A pair is read this long after it was recorded. +const AFTER: std::time::Duration = std::time::Duration::from_millis(1500); + +/// A pair being recorded: its place in the ring, or none. +#[derive(Clone, Copy)] +pub(crate) struct Span(u32); + +impl Span { + pub(crate) const NONE: Span = Span(u32::MAX); + /// For keeping in an atomic. + pub(crate) fn raw(self) -> u32 { + self.0 + } + pub(crate) fn from_raw(raw: u32) -> Span { + Span(raw) + } +} + +struct Meter { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + /// The read-back buffer's bytes, mapped for good. + mapped: usize, + /// Ticks a second of the queue's clock. + frequency: u64, + next: u32, + /// Pairs recorded and not read yet: place, kind, when recorded. + pending: std::collections::VecDeque<(u32, Kind, std::time::Instant)>, + /// What each place held when it was last read: a place the card has + /// not written since (its list never ran) still holds that, and is + /// not counted again. + seen: Vec<(u64, u64)>, +} + +// SAFETY: host objects (free-threaded) and a mapping only read, behind a lock. +unsafe impl Send for Meter {} + +static METER: Mutex>> = Mutex::new(None); + +/// Whether lists are timed. +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var_os("VICTORY_CARD_METER") { + Some(v) => v != "0", + None => cfg!(feature = "diagnostics"), + }) +} + +fn make() -> Option { + let host = crate::host::host()?; + let device = host.device(); + let mut heap: Option = None; + let mut back: Option = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(PAIRS) * 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation; the buffer is mapped once and stays so. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: PAIRS * 2, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + device + .CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) + .ok()?; + let (heap, back) = (heap?, back?); + let mut mapped = std::ptr::null_mut(); + back.Map(0, None, Some(&mut mapped)).ok()?; + let frequency = host.timestamp_frequency(); + if mapped.is_null() || frequency == 0 { + return None; + } + tracing::info!( + "the card's time is measured by kind of list, a timestamp where each list begins and ends (VICTORY_CARD_METER=0: not)" + ); + Some(Meter { heap, back, mapped: mapped as usize, frequency, next: 0, pending: Default::default(), seen: vec![(0, 0); PAIRS as usize] }) + } +} + +/// A list of `kind` begins here: the first timestamp of a pair. +pub(crate) fn begin(list: &ID3D12GraphicsCommandList, kind: Kind) -> Span { + if !on() { + return Span::NONE; + } + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = meter.get_or_insert_with(make) else { + return Span::NONE; + }; + // The ring must not come round to pairs that were not read yet. + if m.pending.len() as u32 >= PAIRS - 64 { + return Span::NONE; + } + let pair = m.next; + m.next = (m.next + 1) % PAIRS; + m.pending.push_back((pair, kind, std::time::Instant::now())); + // SAFETY: an open list and our query heap. + unsafe { list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, pair * 2) }; + Span(pair) +} + +/// The list ends here: the pair's second timestamp, and both go to the +/// read-back buffer when the card has run the list. +pub(crate) fn end(list: &ID3D12GraphicsCommandList, span: Span) { + if span.0 == u32::MAX { + return; + } + let meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(m)) = meter.as_ref() else { + return; + }; + // SAFETY: an open list, our heap and our read-back buffer, the pair's + // own sixteen bytes of it. + unsafe { + list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2 + 1); + list.ResolveQueryData(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2, 2, &m.back, u64::from(span.0) * 16); + } +} + +/// Microseconds between two timestamps of a clock of `frequency` ticks a +/// second; 0 if the second is not after the first (a pair the card has not +/// written, or a list that never ran). +fn micros(begin: u64, end: u64, frequency: u64) -> u64 { + if end <= begin || frequency == 0 { + return 0; + } + ((end - begin) as u128 * 1_000_000 / frequency as u128).min(10_000_000) as u64 +} + +/// The pairs recorded long enough ago are read and added to the frame +/// log's totals. Called once a frame. +pub(crate) fn collect() { + if !on() { + return; + } + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(m)) = meter.as_mut() else { + return; + }; + let now = std::time::Instant::now(); + while let Some(&(pair, kind, at)) = m.pending.front() { + if now.duration_since(at) < AFTER { + break; + } + m.pending.pop_front(); + // SAFETY: the pair's sixteen bytes of the mapped read-back buffer; + // the card wrote them long ago or never. + let (begin, end) = unsafe { + let p = (m.mapped as *const u64).add(pair as usize * 2); + (p.read_volatile(), p.add(1).read_volatile()) + }; + if std::mem::replace(&mut m.seen[pair as usize], (begin, end)) == (begin, end) { + continue; + } + let us = micros(begin, end, m.frequency); + use crate::framelog::{T, add}; + match kind { + Kind::Sync => { + add(T::CardSyncUs, us); + add(T::CardSyncLists, 1); + } + Kind::Check => { + add(T::CardCheckUs, us); + add(T::CardCheckLists, 1); + } + Kind::Lists => { + add(T::CardListsUs, us); + add(T::CardLists, 1); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pairs_length_is_in_microseconds_of_the_queues_clock() { + assert_eq!(micros(1_000, 11_000, 10_000_000), 1_000); + assert_eq!(micros(0, 25_000_000, 25_000_000), 1_000_000); + // Not written, or the wrong way round: nothing. + assert_eq!(micros(5, 5, 1_000), 0); + assert_eq!(micros(9, 5, 1_000), 0); + assert_eq!(micros(1, 2, 0), 0); + // A stale second stamp from the ring's last round cannot add hours. + assert_eq!(micros(1, u64::MAX, 1), 10_000_000); + } +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index cae74b24..a86d1e82 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -984,6 +984,9 @@ pub(crate) fn recorded(started: std::time::Instant) { let ns = started.elapsed().as_nanos() as u64; add(C::RecordCalls, 1); add(C::RecordNs, ns); + crate::framelog::add(crate::framelog::T::RecordCalls, 1); + crate::framelog::add(crate::framelog::T::RecordNs, ns); + crate::framelog::here(crate::framelog::H::RecordNs, ns); if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { let began = now_us().saturating_sub(ns / 1000); add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); @@ -997,6 +1000,12 @@ pub(crate) fn recorded(started: std::time::Instant) { return; } UNSENT.with(|u| u.set((0, 0))); + if crate::framelog::on() { + crate::framelog::add(crate::framelog::T::RecordLooks, 1); + if crate::framelog::on_slow_core() { + crate::framelog::add(crate::framelog::T::RecordSlow, 1); + } + } let id = thread_id(); let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner()); match all.iter_mut().find(|r| r.0 == id) { @@ -1272,9 +1281,11 @@ pub(crate) fn log(frames: f64) { } tracing::info!( " write-watch askings per frame that failed in the kernel: {:.0}; not made because the range \ - is known guarded view memory: {:.0} (VICTORY_VIEW_ASK=1 asks the kernel anyway)", + is known guarded view memory: {:.0} (VICTORY_VIEW_ASK=1 asks the kernel anyway); such ranges left \ + out of the submissions' askings ahead: {:.0}", c[C::WatchFailed as usize], c[C::WatchKnownView as usize], + crate::watch::AHEAD_VIEWS.swap(0, Relaxed) as f64 / frames, ); tracing::info!( " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 2ea083e7..c96ff17e 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -125,13 +125,24 @@ const SHADER_VISIBLE: u32 = 1; /// Shader-visible heaps by address range, for mirroring descriptor writes: /// start, end, heap. +/// +/// Read by every lookup and by [`sync_heaps`], written only when a heap is +/// made or dropped. It was a mutex, and [`sync_heaps`] holds it for its +/// whole pass (15 ms a frame on the submitting thread): the profile of run +/// 225 has the title's six recording threads waiting 48.5 ms a frame in +/// [`shader_slot`] for it, each lookup itself a few nanoseconds. Readers no +/// longer wait for each other. Nothing a holder calls takes it again. +#[cfg(windows)] +static SHADER_HEAPS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); + +/// One [`sync_heaps`] at a time, as when the list above was a mutex. #[cfg(windows)] -static SHADER_HEAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +static SYNCING: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// The shader-visible heap holding `handle`, and the descriptor's index. #[cfg(windows)] fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); let &(_, _, at) = heaps .iter() .find(|&&(start, end, _)| (start..end).contains(&handle))?; @@ -178,7 +189,8 @@ pub(crate) fn sync_heaps() { let started = std::time::Instant::now(); let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); let mut page_bytes: Vec = Vec::new(); - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let _one = SYNCING.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); for &(start, end, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). let heap = unsafe { &*(at as *const Heap) }; @@ -203,6 +215,17 @@ pub(crate) fn sync_heaps() { if crate::host::read_into(from as *const u8, &mut page_bytes) { pages += 1; let slots = changed_slots(from, to, start as usize, step, mirrored_count); + // The page's records in one go, under one lock + // (`HostHeap::mirror_copied_page`); one by one below + // with `VICTORY_HEAP_SYNC_PAGE=0`. + let slots = if page_at_once() { + let (seen, made) = host.mirror_copied_page(slots, (start, step), from, &page_bytes); + looked += seen; + mirrored += made; + 0..0 + } else { + slots + }; for index in slots { let handle = start + index * step; // A record that straddles the range's ends is left @@ -256,6 +279,16 @@ pub(crate) fn sync_line(frames: f64) { ); } +/// Whether [`sync_heaps`] hands a changed page's records to the host heap +/// in one go (`host::HostHeap::mirror_copied_page`). On by default: the +/// same records are mirrored either way. `VICTORY_HEAP_SYNC_PAGE=0`: one +/// by one, as before. +#[cfg(windows)] +fn page_at_once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC_PAGE").is_none_or(|v| v != "0")) +} + /// Title descriptor slots in a changed byte range that have host counterparts. /// `range_end` is exclusive. #[cfg(windows)] @@ -277,7 +310,7 @@ fn changed_slots( /// `heap`, if that heap still exists. #[cfg(windows)] pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + 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() @@ -290,7 +323,7 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { impl Drop for Heap { fn drop(&mut self) { let at = std::ptr::from_ref::(self) as usize; - let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.retain(|&(_, _, h)| h != at); } } @@ -1096,7 +1129,7 @@ pub(crate) extern "system" fn create_heap( #[cfg(windows)] if visible { let at = std::ptr::from_ref::(&heap) as usize; - let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.push((start, start + size, at)); } #[cfg(not(windows))] diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 21cc1948..7970fc5f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1850,6 +1850,74 @@ impl HostHeap { true } + /// [`HostHeap::mirror_copied`] for every record of one changed page of + /// the title's heap (`super::sync_heaps`): title slots `slots`, the + /// record of slot `i` at title address `start + i * step`, and `page` + /// the bytes read from title address `from` on. Returns the records + /// looked at and those mirrored. + /// + /// The same records are mirrored as one by one. What differs is the + /// work for the others, which are nearly all of them (some 330,000 + /// looked at a frame for 14,000 mirrored, 16 ms, run 225): the lock of + /// the fingerprints is taken once for the page and not once for each + /// record, and a record whose fingerprint is the one last seen is done + /// with before the question whether its slot was a table's lately. So + /// the count of slots "left to the draws" is now of records that + /// changed, not of every record on the page. The slots to mirror are + /// made after the page's walk, in slot order as before. + pub(crate) fn mirror_copied_page( + &self, + slots: std::ops::Range, + (start, step): (u64, u64), + from: usize, + page: &[u8], + ) -> (u64, u64) { + let (frame, tables) = (crate::frame::current(), sync_tables()); + let mut looked = 0u64; + let mut due: Vec<(u32, u64)> = Vec::new(); + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left to the + // range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // None past the host heap's slots, as `mirror_copied`. + let Some(last) = copied.get_mut(index as usize) else { + continue; + }; + // Never 0, which is "never looked at". + let print = record_print(record) | 1; + // The record last seen, or a slot never looked at that + // holds nothing: as it was. + if *last == print || (*last == 0 && record.iter().all(|&b| b == 0)) { + continue; + } + // A table's slot lately: left to its draws, and looked at + // again next time. + if !tables && self.tabled_lately(index as u32, frame) { + COPIED_TABLED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + continue; + } + *last = print; + due.push((index as u32, handle)); + } + } + for &(index, handle) in &due { + self.mirror(index, handle, false); + } + (looked, due.len() as u64) + } + /// Makes host slot `index` from the record the title has at `handle` /// if it changed since, and returns the view recorded there. Buffer /// views are made only for draws (`for_draw`), which also copy their diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ca67721e..c5e7655d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -181,9 +181,13 @@ const WINDOW_MOST: u64 = 64; /// (`crate::indirect::bound_ahead`); a tail record that looks real is /// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as /// before, at the next submission. +/// +/// Off for the rest of the run from the first error the card's driver +/// reports to the system (`crate::drvwatch`): every loss of the card in a +/// run with windows was announced that way seconds ahead. fn windows() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) && !crate::drvwatch::tripped() } /// What one title list has set, and what its host list was last given. @@ -2040,6 +2044,12 @@ impl State { crate::pipeline::note_drop(self.pipeline as This); return; } + // A program that walks ray-tracing structures nothing has built. + if crate::pipeline::walk_held(self.pipeline as This) { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)".to_owned()); + 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); @@ -2884,6 +2894,13 @@ impl State { if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { return false; } + // A program that walks ray-tracing structures nothing has built: + // dropped before the argument clamp, like a skipped one. + if crate::pipeline::walk_held(self.pipeline as This) { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)".to_owned()); + return false; + } const DRAW: u32 = 0; const INDEXED: u32 = 1; const DISPATCH: u32 = 2; diff --git a/crates/victory-gpu/src/drvwatch.rs b/crates/victory-gpu/src/drvwatch.rs new file mode 100644 index 00000000..6024346b --- /dev/null +++ b/crates/victory-gpu/src/drvwatch.rs @@ -0,0 +1,188 @@ +//! The graphics driver's errors, seen as the system records them. +//! +//! A card is not lost out of nothing. Every loss of runs 201, 204, 208 and +//! 224 has entries of the card's driver in the system's event log (NVIDIA: +//! provider `nvlddmkm`, event 153, "Error occurred on GPUID") from 2.7 to +//! 6.3 seconds BEFORE the device was removed, several of them; run 210 has +//! three and kept its device; the runs with no such entry lost nothing. +//! Nothing in the layer saw them: the first it knew was the device gone. +//! +//! Here the layer subscribes to that log. Each entry of a display driver +//! is written to our log when the system records it, with our own clock, +//! so it can be laid beside what the layer did in that moment; it is +//! counted; and the first one trips a switch ([`tripped`]) that the paths +//! under suspicion ask before they run (the draw windows of `crate::draw` +//! turn themselves off for the rest of the run). So a driver error costs a +//! slower frame from then on, and not the card. +//! +//! On by default; `VICTORY_DRIVER_WATCH=0` subscribes to nothing. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + +use windows_sys::Win32::System::EventLog::{ + EVT_HANDLE, EVT_SUBSCRIBE_NOTIFY_ACTION, EvtSubscribe, EvtSubscribeActionDeliver, EvtSubscribeToFutureEvents, +}; + +/// Entries of a display driver seen since the start. +static ERRORS: AtomicU64 = AtomicU64::new(0); +/// Whether one was seen ([`tripped`]). +static TRIPPED: AtomicBool = AtomicBool::new(false); + +/// Whether the card's driver has reported an error in this run: what could +/// have caused it stops for the rest of the run. +pub(crate) fn tripped() -> bool { + TRIPPED.load(Relaxed) +} + +/// Driver errors seen since the start. +pub(crate) fn errors() -> u64 { + ERRORS.load(Relaxed) +} + +/// An entry of a display driver was recorded. +fn seen() { + let n = ERRORS.fetch_add(1, Relaxed) + 1; + let first = !TRIPPED.swap(true, Relaxed); + tracing::error!( + n, + "the graphics driver reported an error to the system's event log{}", + if first { + ": from now on the paths under suspicion are off for this run (draw windows clamp each record again)" + } else { + "" + } + ); +} + +unsafe extern "system" fn on_event(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _context: *const core::ffi::c_void, _event: EVT_HANDLE) -> u32 { + if action == EvtSubscribeActionDeliver { + seen(); + } + 0 +} + +/// Subscribes to the display drivers' entries in the system's event log, +/// once. Entries from before the call are not delivered. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + if std::env::var_os("VICTORY_DRIVER_WATCH").is_some_and(|v| v == "0") { + return; + } + let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let channel = wide("System"); + // The kernel drivers of the three vendors, and the system's own + // "display driver stopped responding" source. + let query = wide( + "*[System[Provider[@Name='nvlddmkm' or @Name='amdkmdag' or @Name='amdwddmg' or @Name='igfx' or @Name='igfxn' \ + or @Name='Display']]]", + ); + // SAFETY: valid strings for the call's length; the callback is a + // plain function that touches only statics; the subscription is + // kept for the life of the process. + let subscription = unsafe { + EvtSubscribe( + 0, + std::ptr::null_mut(), + channel.as_ptr(), + query.as_ptr(), + 0, + std::ptr::null(), + Some(on_event), + EvtSubscribeToFutureEvents, + ) + }; + if subscription == 0 { + tracing::warn!( + error = %std::io::Error::last_os_error(), + "no subscription to the system's event log: the graphics driver's errors are not seen as they happen" + ); + } else { + tracing::info!( + "the graphics driver's errors in the system's event log are watched: each is logged here as it is recorded, and \ + the first turns the paths under suspicion off (VICTORY_DRIVER_WATCH=0: not watched)" + ); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_first_error_trips_the_switch_and_every_one_is_counted() { + // (Other tests do not touch these statics.) + assert!(!tripped()); + assert_eq!(errors(), 0); + seen(); + assert!(tripped()); + seen(); + assert_eq!(errors(), 2); + assert!(tripped()); + } + + /// End to end, by hand (`--ignored`): an entry written to the + /// Application log under a name of our own reaches a subscription made + /// the same way as [`start`]'s, within a second. It leaves one + /// information entry in that log. + #[test] + #[ignore = "writes one entry to the Application event log: run it by name with --ignored"] + fn an_entry_written_reaches_a_subscription() { + use windows_sys::Win32::System::EventLog::{ + DeregisterEventSource, EVENTLOG_INFORMATION_TYPE, EvtClose, RegisterEventSourceW, ReportEventW, + }; + static GOT: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn got(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _: *const core::ffi::c_void, _: EVT_HANDLE) -> u32 { + if action == EvtSubscribeActionDeliver { + GOT.fetch_add(1, Relaxed); + } + 0 + } + let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let (channel, query) = (wide("Application"), wide("*[System[Provider[@Name='victory-drvwatch-test']]]")); + // SAFETY: as in `start`. + let subscription = unsafe { + EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(got), EvtSubscribeToFutureEvents) + }; + assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); + let (name, text) = (wide("victory-drvwatch-test"), wide("a test entry of the VIctory layer's driver watch")); + // SAFETY: a source of our own name, one string, no data. + unsafe { + let source = RegisterEventSourceW(std::ptr::null(), name.as_ptr()); + assert!(!source.is_null(), "{}", std::io::Error::last_os_error()); + let strings = [text.as_ptr()]; + assert_ne!( + ReportEventW(source, EVENTLOG_INFORMATION_TYPE, 0, 1, std::ptr::null_mut(), 1, 0, strings.as_ptr(), std::ptr::null()), + 0, + "{}", + std::io::Error::last_os_error() + ); + DeregisterEventSource(source); + } + let started = std::time::Instant::now(); + while GOT.load(Relaxed) == 0 && started.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let after = started.elapsed(); + // SAFETY: our own subscription. + unsafe { EvtClose(subscription) }; + assert_eq!(GOT.load(Relaxed), 1, "the entry was not delivered in 5 s"); + eprintln!("delivered after {} ms", after.as_millis()); + } + + /// The subscription itself: the system accepts the channel and the + /// query (a query it cannot read is refused at once). + #[test] + fn the_system_takes_the_subscription() { + let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let (channel, query) = (wide("System"), wide("*[System[Provider[@Name='nvlddmkm' or @Name='Display']]]")); + // SAFETY: as in `start`. + let subscription = unsafe { + EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(on_event), EvtSubscribeToFutureEvents) + }; + assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); + // SAFETY: our own subscription. + unsafe { windows_sys::Win32::System::EventLog::EvtClose(subscription) }; + } +} diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 798b7606..468812c5 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -150,6 +150,12 @@ pub(crate) extern "system" fn wait( last(kind).fetch_max(tick, Ordering::Relaxed); S_OK }; + #[cfg(windows)] + { + let us = wait.min(limit).as_micros() as u64; + crate::framelog::add(crate::framelog::T::PaceUs, us); + crate::framelog::here(crate::framelog::H::PaceUs, us); + } #[cfg(all(windows, feature = "diagnostics"))] { use crate::copystat::{C, add}; diff --git a/crates/victory-gpu/src/framelog.rs b/crates/victory-gpu/src/framelog.rs new file mode 100644 index 00000000..bebc9d72 --- /dev/null +++ b/crates/victory-gpu/src/framelog.rs @@ -0,0 +1,584 @@ +//! Every frame's length, and what the long ones were made of. +//! +//! The frame-rate line averages over a second or more, and its counters +//! are reset at each line: a single long frame is lost in it, and so is +//! what that frame was made of. Run 222's dips (150 ms frames with some of +//! 250 to 500 ms among them) could not be placed from those lines. +//! +//! Here every counter runs from the start and is never reset. At the end +//! of each present call the totals are read, and their differences since +//! the present before are that frame's. Every five seconds one line gives +//! the frame times (each one, the shortest, the median, the longest), one +//! gives the usual frame's make-up (the mean of the frames that were not +//! long), and each long frame gets a line of its own in the same form, so +//! a long frame is read against a usual one column by column. +//! +//! On by default in diagnostics builds, off in others; +//! `VICTORY_FRAME_LOG=1` or `0` says otherwise. The counters themselves +//! are plain atomic adds in every build. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Totals since the start (microseconds unless said otherwise). +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum T { + /// The title's present call, all of it; of it, running the queues' + /// lines and settling submissions before our copy; and our copy to the + /// window with the host's present. + PresentUs, + PresentLineUs, + PresentShowUs, + /// The title's submit calls (`queue::execute`), on every thread. + ExecuteUs, + /// The submit thread of ours (`VICTORY_ASYNC_SUBMIT=1`) at work: wall + /// time running the queues' lines, and its processor time doing so. + WorkerUs, + WorkerUserUs, + WorkerKernelUs, + /// Submissions sent; preparing them and waiting for the card, on + /// whichever thread (the frame-rate line's "preparing" and "on the + /// GPU"). + Submissions, + PrepareUs, + CardWaitUs, + /// The card with nothing of ours queued, and how much of that while + /// the submitting thread was working. + CardIdleUs, + CardIdleBehindUs, + /// Copies of title memory for submissions (time, bytes), and what + /// shaders wrote copied back (time, bytes). + CopyUs, + CopyBytes, + CopyBackUs, + CopyBackBytes, + /// List calls that record into host lists, on every thread + /// (nanoseconds, calls). Diagnostics builds only. + RecordNs, + RecordCalls, + /// The runtime changing what title memory shows: calls, the time from + /// asking for the lock to letting it go, and of that the wait for + /// readers. + Remaps, + RemapUs, + RemapWaitUs, + /// Texture refreshes on every thread, and of them the wait for title + /// memory to hold still; uploads recorded. + RefreshUs, + RefreshStillUs, + Uploads, + /// Waiting for host pipelines being made. + PipelineWaitUs, + /// Writes taken by the guards on view memory. + GuardFaults, + /// The title's frame waits: time slept, on every thread. + PaceUs, + /// DirectStorage requests finished, their destination bytes, and the + /// workers' time in them. + DiskReads, + DiskBytes, + DiskUs, + /// The card's time by kind of list (`crate::cardmeter`), as read a + /// second and a half after the lists were recorded: our lists that + /// bring copies in the card's memory up to date and hash their pieces, + /// our compare lists, and every other list; and how many of each. + CardSyncUs, + CardSyncLists, + CardCheckUs, + CardCheckLists, + CardListsUs, + CardLists, + /// Looks at which processor a thread is on ([`on_slow_core`]), and how + /// many found a slow one (an efficiency core of a hybrid processor): + /// the thread that presents (one look a present), our submit thread + /// (one a turn), and the recording threads (one every couple of + /// milliseconds of list calls). + RenderLooks, + RenderSlow, + WorkerLooks, + WorkerSlow, + RecordLooks, + RecordSlow, + Count, +} + +const N: usize = T::Count as usize; +static TOTAL: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; + +/// Adds to a total. +pub fn add(t: T, n: u64) { + TOTAL[t as usize].fetch_add(n, Relaxed); +} + +/// Takes from a total (a time that was summed over threads is corrected +/// to the time it took). +pub fn sub(t: T, n: u64) { + TOTAL[t as usize].fetch_sub(n, Relaxed); +} + +/// What a thread did inside our calls since its last present: for the +/// thread that presents (the title's render thread). +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum H { + /// List calls, nanoseconds. + RecordNs, + /// Submit calls, microseconds. + ExecuteUs, + /// Frame waits, microseconds slept. + PaceUs, + Count, +} + +const HN: usize = H::Count as usize; + +thread_local! { + static HERE: std::cell::Cell<[u64; HN]> = const { std::cell::Cell::new([0; HN]) }; +} + +/// Adds to this thread's own count. +pub fn here(h: H, n: u64) { + HERE.with(|c| { + let mut v = c.get(); + v[h as usize] += n; + c.set(v); + }); +} + +/// Whether the processor this thread runs on right now is a slow one: on a +/// processor with two kinds of cores (the console has eight alike; an Intel +/// hybrid has fast cores and efficiency cores at about half their speed), +/// one of a lower efficiency class than the best. Always false where all +/// cores are alike. +pub fn on_slow_core() -> bool { + use windows_sys::Win32::System::SystemInformation::{ + GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessorNumber}; + /// By logical processor (of group 0): whether it is slow. + static SLOW: std::sync::OnceLock> = std::sync::OnceLock::new(); + let slow = SLOW.get_or_init(|| { + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { + GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) + }; + let mut classes: Vec<(u8, u8)> = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + classes.push((set.LogicalProcessorIndex, set.EfficiencyClass)); + } + at += info.Size as usize; + } + let best = classes.iter().map(|c| c.1).max().unwrap_or(0); + let mut slow = vec![false; classes.iter().map(|c| c.0 as usize + 1).max().unwrap_or(0)]; + for (processor, class) in &classes { + slow[*processor as usize] = *class < best; + } + tracing::info!( + "processors: {} logical, {} of them slow ones (a lower efficiency class than the best); the frame log counts how \ + often the render, submit and recording threads are found on a slow one", + slow.len(), + slow.iter().filter(|&&s| s).count() + ); + slow + }); + // SAFETY: a plain query. + let processor = unsafe { GetCurrentProcessorNumber() } as usize; + slow.get(processor).copied().unwrap_or(false) +} + +/// Whether frames are logged. +pub fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var_os("VICTORY_FRAME_LOG") { + Some(v) => v != "0", + None => cfg!(feature = "diagnostics"), + }) +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +pub fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's page faults so far (soft and hard). +fn page_faults() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: plain data the call fills in. + let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; + c.cb = size_of::() as u32; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// The PC's free physical memory, in MiB. +fn free_mb() -> u64 { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + m.ullAvailPhys >> 20 +} + +/// Values read when a frame ends, all running totals but the last. +const S: usize = 11; +const S_THREAD_USER: usize = 0; +const S_THREAD_KERNEL: usize = 1; +const S_PROCESS_USER: usize = 2; +const S_PROCESS_KERNEL: usize = 3; +const S_PAGE_FAULTS: usize = 4; +const S_DRAWS: usize = 5; +const S_PIPELINES_MADE: usize = 6; +const S_PIPELINES_LOADED: usize = 7; +const S_STAGING_REUSED: usize = 8; +const S_STAGING_MADE: usize = 9; +/// Not a total: the free memory then. +const S_FREE_MB: usize = 10; + +fn sample() -> [u64; S] { + let (tu, tk) = thread_times(); + let (pu, pk) = process_times(); + [ + tu, + tk, + pu, + pk, + page_faults(), + crate::draw::drawn(), + crate::pipeline::frame_log_counts().0, + crate::pipeline::frame_log_counts().1, + crate::texture::SPARE_STATS[0].load(Relaxed), + crate::texture::SPARE_STATS[1].load(Relaxed), + free_mb(), + ] +} + +/// One frame: its number, when it ended (seconds since the first), its +/// length in microseconds, and the differences of the totals, the sampled +/// values and the presenting thread's own counts over it. +#[derive(Clone)] +struct Frame { + number: u64, + at: f64, + us: f64, + t: [f64; N], + s: [f64; S], + h: [f64; HN], +} + +struct State { + first: std::time::Instant, + /// The last frame's end: when, the totals and samples then, and the + /// thread that presented. + last: Option<(std::time::Instant, [u64; N], [u64; S], u32)>, + number: u64, + frames: Vec, + since: std::time::Instant, + /// The lengths of the last frames (microseconds), for the usual one. + recent: std::collections::VecDeque, +} + +static STATE: Mutex> = Mutex::new(None); + +fn median(values: impl Iterator) -> f64 { + let mut v: Vec = values.collect(); + if v.is_empty() { + return 0.0; + } + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// A frame's make-up as text (`f` may be a mean of frames). +fn text(f: &Frame) -> String { + let t = |x: T| f.t[x as usize]; + let ms = |x: T| f.t[x as usize] / 1e3; + let s = |i: usize| f.s[i]; + let h = |x: H| f.h[x as usize]; + format!( + "{:.0} ms | render thread: ran {:.0} ms (user {:.0}, kernel {:.0}); in the present call {:.1} (lines and settling \ + {:.1}, copy and show {:.1}), in submit calls {:.1}, in list calls {:.1}, paced {:.1} | submit thread: at work \ + {:.1} ms (user {:.1}, kernel {:.1}); {:.0} submissions, preparing {:.1}, waiting for the card {:.1}; copies {:.1} \ + ms {:.1} MB; copy-back {:.1} ms {:.2} MB | card: idle {:.1} ms ({:.1} behind us); by its own clock, of the lists of a moment ago: our \ + send-and-hash lists {:.1} ms in {:.0}, our compare lists {:.1} ms in {:.0}, all other lists {:.1} ms in {:.0} | \ + recording, all threads: {:.1} ms in {:.0} calls; all submit calls {:.1} ms | textures: refresh {:.1} ms ({:.1} waiting for memory to hold \ + still), {:.0} uploads, staging {:.0} made {:.0} reused | remapping: {:.0} calls {:.1} ms ({:.1} waiting for \ + readers) | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \ + faults: {:.0} page, {:.0} guard | process: {:.0} user {:.0} kernel ms | pacing, all threads {:.1} ms | {:.0} \ + draws | {:.0} MB free | found on a slow core: the render thread {:.0} of {:.0} looks, the submit thread {:.0} of {:.0}, recording threads {:.0} of {:.0}", + f.us / 1e3, + (s(S_THREAD_USER) + s(S_THREAD_KERNEL)) / 1e3, + s(S_THREAD_USER) / 1e3, + s(S_THREAD_KERNEL) / 1e3, + ms(T::PresentUs), + ms(T::PresentLineUs), + ms(T::PresentShowUs), + h(H::ExecuteUs) / 1e3, + h(H::RecordNs) / 1e6, + h(H::PaceUs) / 1e3, + ms(T::WorkerUs), + ms(T::WorkerUserUs), + ms(T::WorkerKernelUs), + t(T::Submissions), + ms(T::PrepareUs), + ms(T::CardWaitUs), + ms(T::CopyUs), + t(T::CopyBytes) / 1e6, + ms(T::CopyBackUs), + t(T::CopyBackBytes) / 1e6, + ms(T::CardIdleUs), + ms(T::CardIdleBehindUs), + ms(T::CardSyncUs), + t(T::CardSyncLists), + ms(T::CardCheckUs), + t(T::CardCheckLists), + ms(T::CardListsUs), + t(T::CardLists), + t(T::RecordNs) / 1e6, + t(T::RecordCalls), + ms(T::ExecuteUs), + ms(T::RefreshUs), + ms(T::RefreshStillUs), + t(T::Uploads), + s(S_STAGING_MADE), + s(S_STAGING_REUSED), + t(T::Remaps), + ms(T::RemapUs), + ms(T::RemapWaitUs), + s(S_PIPELINES_MADE), + s(S_PIPELINES_LOADED), + ms(T::PipelineWaitUs), + t(T::DiskReads), + t(T::DiskBytes) / 1e6, + ms(T::DiskUs), + s(S_PAGE_FAULTS), + t(T::GuardFaults), + s(S_PROCESS_USER) / 1e3, + s(S_PROCESS_KERNEL) / 1e3, + ms(T::PaceUs), + s(S_DRAWS), + s(S_FREE_MB), + t(T::RenderSlow), + t(T::RenderLooks), + t(T::WorkerSlow), + t(T::WorkerLooks), + t(T::RecordSlow), + t(T::RecordLooks), + ) +} + +/// The mean of `frames` (not empty). +fn mean(frames: &[&Frame]) -> Frame { + let n = frames.len() as f64; + let mut out = Frame { number: 0, at: 0.0, us: 0.0, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + for f in frames { + out.us += f.us / n; + for i in 0..N { + out.t[i] += f.t[i] / n; + } + for i in 0..S { + out.s[i] += f.s[i] / n; + } + for i in 0..HN { + out.h[i] += f.h[i] / n; + } + } + out +} + +/// Over how many microseconds a frame is long, the usual one being +/// `usual`: half as long again, and at least 40 ms more. +fn long_over(usual: f64) -> f64 { + (usual * 1.5).max(usual + 40_000.0) +} + +/// The lines of a reading: the frame times, the usual frame, the long ones. +fn lines(frames: &[Frame], usual: f64, seconds: f64) -> Vec { + let over = long_over(usual); + let (long, plain): (Vec<&Frame>, Vec<&Frame>) = frames.iter().partition(|f| f.us > over); + let each: Vec = frames.iter().map(|f| format!("{:.0}", f.us / 1e3)).collect(); + let shortest = frames.iter().map(|f| f.us).fold(f64::INFINITY, f64::min); + let longest = frames.iter().map(|f| f.us).fold(0.0, f64::max); + let mut out = vec![format!( + "frame times: {} frames in {seconds:.1} s: shortest {:.0} ms, median {:.0}, longest {:.0}; {} long (over {:.0} ms, \ + the usual frame of the last {RECENT} being {:.0}); each: {}", + frames.len(), + shortest / 1e3, + median(frames.iter().map(|f| f.us)) / 1e3, + longest / 1e3, + long.len(), + over / 1e3, + usual / 1e3, + each.join(" ") + )]; + if !plain.is_empty() { + out.push(format!("usual frame (the mean of {} not long): {}", plain.len(), text(&mean(&plain)))); + } + for f in long.iter().take(LONG_MOST) { + out.push(format!("long frame {} at {:.1} s: {}", f.number, f.at, text(f))); + } + if long.len() > LONG_MOST { + out.push(format!("long frames: {} more in this reading are not listed", long.len() - LONG_MOST)); + } + out +} + +/// Frames whose lengths give the usual one, and the long frames listed in +/// a reading at most. +const RECENT: usize = 64; +const LONG_MOST: usize = 8; + +/// A frame ends: called at the end of the title's present call, on the +/// thread that made it. +pub fn frame() { + if !on() { + return; + } + crate::cardmeter::collect(); + add(T::RenderLooks, 1); + if on_slow_core() { + add(T::RenderSlow, 1); + } + let now = std::time::Instant::now(); + let totals: [u64; N] = std::array::from_fn(|i| TOTAL[i].load(Relaxed)); + let sampled = sample(); + let here = HERE.with(|c| c.replace([0; HN])); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.get_or_insert_with(|| State { + first: now, + last: None, + number: 0, + frames: Vec::new(), + since: now, + recent: std::collections::VecDeque::new(), + }); + state.number += 1; + if let Some((then, t0, s0, thread0)) = state.last.replace((now, totals, sampled, thread)) { + let mut f = Frame { + number: state.number, + at: (now - state.first).as_secs_f64(), + us: (now - then).as_micros() as f64, + t: std::array::from_fn(|i| totals[i].wrapping_sub(t0[i]) as i64 as f64), + s: std::array::from_fn(|i| sampled[i].wrapping_sub(s0[i]) as i64 as f64), + h: here.map(|v| v as f64), + }; + f.s[S_FREE_MB] = sampled[S_FREE_MB] as f64; + if thread != thread0 { + // Another thread presented: its processor time is not this frame's. + (f.s[S_THREAD_USER], f.s[S_THREAD_KERNEL]) = (0.0, 0.0); + } + state.frames.push(f); + } + let elapsed = state.since.elapsed(); + if elapsed < std::time::Duration::from_secs(5) || state.frames.is_empty() { + return; + } + let frames = std::mem::take(&mut state.frames); + state.since = now; + // The usual frame: the median of the last frames, this reading's with + // those before it. + for f in &frames { + if state.recent.len() == RECENT { + state.recent.pop_front(); + } + state.recent.push_back(f.us); + } + let usual = median(state.recent.iter().copied()); + for line in lines(&frames, usual, elapsed.as_secs_f64()) { + tracing::info!("{line}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(number: u64, ms: f64) -> Frame { + let mut f = Frame { number, at: number as f64, us: ms * 1e3, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + f.t[T::PresentUs as usize] = ms * 100.0; + f.t[T::Uploads as usize] = ms; + f + } + + #[test] + fn a_long_frame_is_listed_beside_the_usual_one() { + let frames: Vec = [150.0, 160.0, 140.0, 400.0, 150.0].iter().enumerate().map(|(i, &ms)| frame(i as u64, ms)).collect(); + let out = lines(&frames, 150_000.0, 1.0); + assert_eq!(out.len(), 3, "{out:#?}"); + assert!(out[0].starts_with("frame times: 5 frames in 1.0 s: shortest 140 ms, median 150, longest 400; 1 long (over 225 ms"), "{}", out[0]); + assert!(out[0].ends_with("each: 150 160 140 400 150"), "{}", out[0]); + // The usual frame is the mean of the four that are not long. + assert!(out[1].starts_with("usual frame (the mean of 4 not long): 150 ms |"), "{}", out[1]); + assert!(out[1].contains("in the present call 15.0 "), "{}", out[1]); + assert!(out[1].contains(" 150 uploads"), "{}", out[1]); + assert!(out[2].starts_with("long frame 3 at 3.0 s: 400 ms |"), "{}", out[2]); + assert!(out[2].contains("in the present call 40.0 "), "{}", out[2]); + assert!(out[2].contains(" 400 uploads"), "{}", out[2]); + } + + #[test] + fn long_is_half_as_long_again_and_at_least_40_ms_more() { + assert_eq!(long_over(150_000.0), 225_000.0); + assert_eq!(long_over(30_000.0), 70_000.0); + } + + #[test] + fn more_long_frames_than_are_listed_are_counted() { + let mut frames: Vec = (0..12).map(|i| frame(i, 500.0)).collect(); + frames.push(frame(12, 100.0)); + let out = lines(&frames, 100_000.0, 5.0); + assert_eq!(out.iter().filter(|l| l.starts_with("long frame ")).count(), LONG_MOST); + assert!(out.last().unwrap().starts_with("long frames: 4 more"), "{out:#?}"); + } + + #[test] + fn totals_and_a_threads_own_counts_add_up() { + let before = TOTAL[T::DiskReads as usize].load(Relaxed); + add(T::DiskReads, 3); + sub(T::DiskReads, 1); + assert_eq!(TOTAL[T::DiskReads as usize].load(Relaxed) - before, 2); + here(H::PaceUs, 5); + here(H::PaceUs, 6); + assert_eq!(HERE.with(|c| c.get())[H::PaceUs as usize], 11); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index ecf79d5e..b559f646 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -277,6 +277,13 @@ pub(crate) fn trail(what: impl FnOnce() -> String) { return; } let entry = (now_us(), thread_id(), what()); + // Sweeps also go to the log as they happen: the trail is only said at + // a loss, and the driver's errors in the system's event log (run 224's + // first fell inside a sweep of 4,711 host textures) need the sweeps of + // clean runs beside them. + if entry.2.starts_with("sweep:") { + tracing::info!("{}", entry.2); + } let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); if trail.len() >= TRAIL_MOST { trail.pop_front(); @@ -342,6 +349,38 @@ pub(crate) fn log_removal_context() { static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +/// Adds to [`SUBMISSION_US`] and to the frame log's totals. +fn submission_us(i: usize, us: u64) { + SUBMISSION_US[i].fetch_add(us, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::PrepareUs, crate::framelog::T::CardWaitUs][i], us); + if i == 0 { + crate::framelog::add(crate::framelog::T::Submissions, 1); + } +} + +/// Adds to [`PREPARING`]'s copies (time, bytes) and to the frame log's totals. +fn preparing(i: usize, n: u64) { + PREPARING[i].fetch_add(n, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::CopyUs, crate::framelog::T::CopyBytes][i], n); +} + +/// Adds to [`COPY_BACK`] and to the frame log's totals. +fn copy_back(i: usize, n: u64) { + COPY_BACK[i].fetch_add(n, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::CopyBackUs, crate::framelog::T::CopyBackBytes][i], n); +} + +/// Adds to [`CARD_CLOCK_US`] and, for the card's idle times, to the frame +/// log's totals. +fn card_clock_us(i: usize, us: u64) { + CARD_CLOCK_US[i].fetch_add(us, Ordering::Relaxed); + match i { + 0 => crate::framelog::add(crate::framelog::T::CardIdleUs, us), + 1 => crate::framelog::add(crate::framelog::T::CardIdleBehindUs, us), + _ => {} + } +} + /// After submissions: shader-written ranges compared and copied back into /// title memory (microseconds, bytes that differed), since the last /// frame-rate line. @@ -386,7 +425,7 @@ fn worked() -> u64 { /// The thread that holds the submission lock stood waiting for the card /// from `since` until now ([`CARD_CLOCK_US`]). fn stood(since: std::time::Instant) { - CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); + card_clock_us(2, since.elapsed().as_micros() as u64); } /// What [`CARD_CLOCK_US`] is measured with. @@ -550,6 +589,7 @@ pub(crate) fn host() -> Option<&'static Host> { } fn create() -> windows::core::Result { + crate::drvwatch::start(); // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. @@ -803,6 +843,9 @@ pub(crate) struct HostList { window_check: OnceLock>, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, + /// The pair of timestamps its run is timed with since its last reset + /// (`crate::cardmeter`), or none. + meter: AtomicU32, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -1741,9 +1784,34 @@ void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) { /// ranges a frame: 514 such passes. The same pieces are hashed either way; /// a piece hashed when it need not be, or not hashed when it should, costs /// a fetch that finds nothing and loses no shader write. +/// +/// `VICTORY_CARD_REHASH_RUNS=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log: one run then measures both on the +/// same scene (the card meter's "send-and-hash lists" in the frame log). +/// Runs 105-110 found no change in the frame, but the card was not the +/// frame's limit then. fn rehash_runs() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1")) + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_REHASH_RUNS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + let joined = (now_us() / 20_000_000) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(joined), Ordering::Relaxed) != u8::from(joined) { + tracing::info!( + "card rehash passes from now (VICTORY_CARD_REHASH_RUNS=alt): {}", + if joined { "JOINED, one pass a run of touching pieces" } else { "one pass a range sent up, as usual" } + ); + } + joined + } + } } /// Since the last frame-rate line, of our own passes over copies in the @@ -3138,7 +3206,7 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { let us = waiting.elapsed().as_micros() as u64; LATE_STATS[12].fetch_add(us, Ordering::Relaxed); LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); - SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); + submission_us(1, us); } /// What the thread that lands flights fetches card copies' pieces with @@ -3258,7 +3326,7 @@ fn relay_hand_back(back: &[Declared]) { for (at, n) in found { written += shadow.relay_merge(at, n, &mut now, &mut title); } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + copy_back(1, written as u64); #[cfg(feature = "diagnostics")] crate::copystat::compared(*from, to - from, written); let _ = (from, to); @@ -3555,7 +3623,7 @@ fn hand_back(back: &[Declared]) { crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); for ((shadow, from, to), found) in work.iter().zip(found) { let written = shadow.copy_back_with(*from, to - from, Some(found)); - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + copy_back(1, written as u64); #[cfg(feature = "diagnostics")] crate::copystat::compared(*from, to - from, written); } @@ -3587,7 +3655,7 @@ fn hand_back(back: &[Declared]) { } for (from, to) in spans { let written = shadow.copy_back(from, to - from); - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + copy_back(1, written as u64); #[cfg(feature = "diagnostics")] crate::copystat::compared(from, to - from, written); } @@ -3727,6 +3795,7 @@ impl Host { indirect_args: Mutex::default(), window_check: OnceLock::new(), _alive: Counted::new(), + meter: AtomicU32::new(u32::MAX), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -3770,8 +3839,8 @@ impl Host { // SAFETY: our queue and the clock's fence. let _ = unsafe { self.queue.Signal(&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); + card_clock_us(0, since.elapsed().as_micros() as u64); + card_clock_us(1, worked().saturating_sub(worked_then)); } drop(state); clock.sent.notify_one(); @@ -4072,6 +4141,7 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Sync); // Where the next range lies in the landing buffer. let mut at = 0u64; for (shadow, ranges) in &dirty { @@ -4123,6 +4193,7 @@ impl Host { list.Dispatch(run.pieces.div_ceil(64), 1, 1); } } + crate::cardmeter::end(list, timed); list.Close()?; self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); Ok(()) @@ -4188,6 +4259,7 @@ impl Host { (|| -> windows::core::Result { allocator.Reset()?; list.Reset(allocator, None)?; + let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Check); // What the submission's shaders wrote, first. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -4246,6 +4318,7 @@ impl Host { plan.inflight = every; plan.inflight_landed = inflight.landed; } + crate::cardmeter::end(list, timed); list.Close()?; list.cast() })() @@ -4533,7 +4606,7 @@ impl Host { shadow.walls_merged(gpu.len(), merged); written += merged; } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + copy_back(1, written as u64); // Sends up to `after` are of no use to any later merge; with the // fetch inside flights only those up to these plans' are // (`fallback_fetched_mark`). @@ -4681,7 +4754,7 @@ impl Host { crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); } } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + copy_back(1, written as u64); INFLIGHT_STATS[0].fetch_add(pieces.len() as u64, Ordering::Relaxed); INFLIGHT_STATS[1].fetch_add(bytes, Ordering::Relaxed); // The next merge is of a later plan, or a fetch the old way sent now. @@ -4749,7 +4822,7 @@ impl Host { shadow.copy_back_done(ranges); } } - COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + copy_back(0, landing.elapsed().as_micros() as u64); RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); } @@ -4959,7 +5032,7 @@ impl Host { } } for (r, written) in plan.ranges.iter().zip(written) { - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + copy_back(1, written as u64); let (from, to) = r.declared; #[cfg(feature = "diagnostics")] crate::copystat::compared(from, to - from, written); @@ -5131,7 +5204,7 @@ impl Host { let gpu = waiting.elapsed(); LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); - SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + submission_us(1, gpu.as_micros() as u64); #[cfg(feature = "diagnostics")] crate::copystat::card_waited(gpu.as_micros() as u64, || { format!("{flights} submissions sent ahead, settled together") @@ -5178,7 +5251,7 @@ impl Host { } } hand_back(&back); - COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); + copy_back(0, copying.elapsed().as_micros() as u64); } // In the order given: what tells the title the card is done. let mut last = 0; @@ -5367,7 +5440,7 @@ impl Host { } let back = declared_writes(runs); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); - SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); + submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); submitting(0, 0); #[cfg(feature = "diagnostics")] crate::copystat::submission_ends(lock); @@ -5445,8 +5518,8 @@ impl Host { FINISHED.store(this_submission, Ordering::Release); bury(this_submission); let gpu = prepared.elapsed(); - SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); - SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + submission_us(0, (prepared - started).as_micros() as u64); + submission_us(1, gpu.as_micros() as u64); #[cfg(feature = "diagnostics")] crate::copystat::card_waited(gpu.as_micros() as u64, || { let pipelines: std::collections::BTreeSet = runs @@ -5502,7 +5575,7 @@ impl Host { add(C::NothingBack, 1); add(C::NothingBackUs, gpu.as_micros() as u64); } - COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); + copy_back(0, copying.elapsed().as_micros() as u64); for list in runs { // Read backs first: a value written at the bottom of the pipe // may be what tells the title that they are there. @@ -5633,6 +5706,68 @@ impl Host { text } + /// With the frame line (`VICTORY_D3D12_DEBUG=1`, diagnostics builds): + /// the debug layer's messages since the last call go to our log, the + /// first five of each kind in full, the rest counted, with one line of + /// the counts by kind. + /// + /// They were only read when the device was lost ([`fail`]): a run that + /// survived (run 205) said nothing of what the layer had found, and + /// what it finds is what a driver's fault would have to be traced back + /// to (an object let go while the card uses it, a resource in the + /// wrong state, a view of something gone). + pub(crate) fn drain_messages(&self) { + let Some(queue) = &self.messages else { + return; + }; + static SEEN: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + let stored = unsafe { + let stored = queue.GetNumStoredMessages(); + for i in 0..stored { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let kind = seen.entry(m.ID.0).or_insert((0, m.Severity.0)); + kind.0 += 1; + if kind.0 <= 5 { + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + tracing::warn!(id = m.ID.0, severity = m.Severity.0, nth = kind.0, "D3D12 debug layer: {text}"); + } + } + } + queue.ClearStoredMessages(); + stored + }; + if stored > 0 { + let counts: Vec = seen.iter().map(|(id, (n, severity))| format!("id {id} (severity {severity}) x{n}")).collect(); + tracing::info!( + "D3D12 debug layer messages so far by kind (severity 0 corruption, 1 error, 2 warning, 3 info, 4 message): {}", + counts.join(", ") + ); + } + } + + /// The host device (`crate::cardmeter`). + pub(crate) fn device(&self) -> &ID3D12Device { + &self.device + } + + /// Ticks a second of the queue's timestamps; 0 if it has none. + pub(crate) fn timestamp_frequency(&self) -> u64 { + // SAFETY: a plain query. + unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(0) + } + /// Moves the debug layer's messages into our log; returns the first /// error among them. pub(crate) fn log_messages(&self) -> Option { @@ -5786,6 +5921,7 @@ impl HostList { self.indirect_common(&scratch); } self.card_budget_out(); + crate::cardmeter::end(&self.list, crate::cardmeter::Span::from_raw(self.meter.swap(u32::MAX, Ordering::Relaxed))); #[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); @@ -5833,6 +5969,8 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } + self.meter + .store(crate::cardmeter::begin(&self.list, crate::cardmeter::Kind::Lists).raw(), Ordering::Relaxed); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } @@ -6592,7 +6730,7 @@ impl HostList { add(C::Copies, 1); add(C::CopyBytes, len as u64); } - batch.title_written(); + batch.title_wrote(dst, len); #[cfg(feature = "diagnostics")] fill_check::copy_runs(dst, src, len); copy_mapped(dst as *mut u8, src as *const u8, len, true); @@ -6660,8 +6798,8 @@ impl HostList { continue; } }; - PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + preparing(0, started.elapsed().as_micros() as u64); + preparing(1, copied as u64); } } } @@ -6683,6 +6821,30 @@ fn wide_refresh() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_REFRESH").is_some_and(|v| v == "1")) } +/// Whether a range of a host copy brought up to date in a submission is +/// left alone for the rest of that submission, until a step of ours writes +/// title memory there (`VICTORY_REFRESH_ONCE=1`; off by default). After +/// upstream VIctory 6d021fe ("a copy's range brought up to date is not +/// copied again in the submission until a step writes title memory"). +/// +/// A list of dispatches records "refresh this range, shaders write it" for +/// every dispatch, and each of those refreshes was done on its own +/// (`Batch::flush_one`): a walk of the guards or a failed kernel asking +/// for a copy of view memory, some 1,800 to 2,700 a frame and 23 to 29 ms +/// (runs 222 and 225, "watches"), nearly all finding nothing new. +/// +/// What changes: what the title's other threads write into a range while +/// its submission is being prepared is taken by the next submission, not +/// by a later step of this one, as `crate::watch::once` already has it for +/// write-watched memory. What this submission's lists read was written +/// before they were submitted. A title buffer copy of ours takes its +/// bytes out of what counts as up to date ([`Batch::title_wrote`]); any +/// other step that writes title memory takes everything out. +fn refresh_once() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_ONCE").is_some_and(|v| v == "1")) +} + /// A submission's refreshes not done yet, merged per buffer copy into the /// range that covers them: done before a step that writes title memory or /// gives a range to shaders, and before the lists run. @@ -6699,6 +6861,11 @@ struct Batch { /// for every refresh of a submission was tens of millions of /// comparisons a frame. index: std::collections::HashMap, + /// With [`refresh_once`], by copy (its address; the copy is held, so + /// that the address names no other): the range of title addresses + /// brought up to date in this submission that no step of ours has + /// written since. + current: std::collections::HashMap, usize, usize)>, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -6707,6 +6874,19 @@ impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { let end = address + len; let key = std::sync::Arc::as_ptr(shadow) as usize; + // Brought up to date in this submission already ([`refresh_once`]; + // nothing is in `current` without the switch). + if let Some(&(_, from, to)) = self.current.get(&key) + && from <= address + && end <= to + { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::Skipped, 1); + crate::copystat::add(crate::copystat::C::SkippedBytes, len as u64); + } + return; + } match self.index.get(&key) { Some(&at) => { let r = &mut self.refreshes[at]; @@ -6731,6 +6911,29 @@ impl Batch { self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } Self::update(&shadow, from, to); + Self::brought(&mut self.current, &shadow, from, to); + } + + /// With [`refresh_once`]: `[from, to)` of `shadow`'s copy was brought + /// up to date. Kept: its union with what was up to date if they touch, + /// else the larger of the two. + fn brought( + current: &mut std::collections::HashMap, usize, usize)>, + shadow: &std::sync::Arc, + from: usize, + to: usize, + ) { + if !refresh_once() || from >= to { + return; + } + let entry = current + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert_with(|| (shadow.clone(), from, to)); + if from <= entry.2 && entry.1 <= to { + (entry.1, entry.2) = (entry.1.min(from), entry.2.max(to)); + } else if to - from > entry.2 - entry.1 { + (entry.1, entry.2) = (from, to); + } } /// Brings `[from, to)` of a copy up to date, timed. @@ -6740,8 +6943,8 @@ impl Batch { let us = started.elapsed().as_micros() as u64; #[cfg(feature = "diagnostics")] crate::copystat::range(from, to - from, us, 0); - PREPARING[0].fetch_add(us, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + preparing(0, us); + preparing(1, copied as u64); } /// Whether `staging` is still to be refreshed in this submission (and @@ -6755,6 +6958,31 @@ impl Batch { fn title_written(&mut self) { self.flush(); self.textures.clear(); + // Where it writes is not known: no copy counts as up to date. + self.current.clear(); + } + + /// [`Batch::title_written`] for a write of ours whose place is known + /// (a title buffer copy into `[at, at + len)`): of a copy up to date + /// in this submission that holds some of those bytes, the larger part + /// beside them stays so. + fn title_wrote(&mut self, at: usize, len: usize) { + self.flush(); + self.textures.clear(); + let end = at + len; + self.current.retain(|_, entry| { + let (from, to) = (entry.1, entry.2); + if end <= from || to <= at { + return true; + } + let (left, right) = (at.saturating_sub(from), to.saturating_sub(end)); + if left >= right { + entry.2 = from + left; + } else { + entry.1 = end; + } + entry.1 < entry.2 + }); } fn flush(&mut self) { @@ -6771,7 +6999,7 @@ impl Batch { .map(|r| (r.1, r.2)) .collect(); crate::watch::ask_ahead(&ranges); - PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + preparing(0, started.elapsed().as_micros() as u64); } if wide_refresh() && self.refreshes.len() >= 4 { // Each copy on its own, several at a time: a copy's refresh @@ -6779,6 +7007,10 @@ impl Batch { // The time counted is the time it took, not the threads' sum. let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); + // Noted now: nothing reads the notes before the jobs are done. + for (shadow, from, to) in &self.refreshes { + Self::brought(&mut self.current, shadow, *from, *to); + } let jobs: Vec> = self .refreshes .drain(..) @@ -6786,10 +7018,13 @@ impl Batch { .collect(); crate::shadow::wide_run(jobs); let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); - PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); + let over = summed.saturating_sub(started.elapsed().as_micros() as u64); + PREPARING[0].fetch_sub(over, Ordering::Relaxed); + crate::framelog::sub(crate::framelog::T::CopyUs, over); } else { for (shadow, from, to) in self.refreshes.drain(..) { Self::update(&shadow, from, to); + Self::brought(&mut self.current, &shadow, from, to); } } if ahead { @@ -6840,7 +7075,9 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b } #[cfg(feature = "diagnostics")] let moved = std::time::Instant::now(); - let whole = read(src, dst, len); + // Into host memory: in place first, if asked for (`crate::plaincopy`); + // through the kernel if that is off or met a page that was not there. + let whole = (!title_dst && crate::plaincopy::copy(dst, src, len)) || read(src, dst, len); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { @@ -7213,6 +7450,19 @@ impl Meter { late_line(frames); card_clock_line(frames, ms); crate::queue2::line(frames); + crate::plaincopy::line(frames); + if let Some(host) = host() { + host.drain_messages(); + } + { + let held = crate::pipeline::WALKS_HELD.swap(0, Ordering::Relaxed); + if held > 0 { + tracing::info!( + "dispatches of programs that walk ray-tracing structures held back per frame (VICTORY_BVH_HOLD=1; the builder has not built them): {:.1}", + held as f64 / frames + ); + } + } crate::shadow::back_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); @@ -7274,6 +7524,16 @@ impl Meter { "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) ); + tracing::info!( + "copies left out since the start because both sides were one host texture: {}", + crate::list::SELF_COPIES.load(Ordering::Relaxed) + ); + if crate::drvwatch::errors() > 0 { + tracing::warn!( + "errors the graphics driver reported to the system since the start: {} (the paths under suspicion are off)", + crate::drvwatch::errors() + ); + } crate::tiles::status(); { let [queued, due, away, partly, oldest] = @@ -7417,6 +7677,13 @@ impl Host { /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { + let showing = std::time::Instant::now(); + let shown = self.present_now(texture, state, frame); + crate::framelog::add(crate::framelog::T::PresentShowUs, showing.elapsed().as_micros() as u64); + shown + } + + fn present_now(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 60751b53..6ecf22e6 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -401,6 +401,121 @@ pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<( runs } +/// Whether what shaders wrote goes back into title view memory through a +/// view of our own (`VICTORY_BACK_OWN_VIEW=1`; off by default). +/// +/// The copy-back writes title memory at the title's address, so it opens +/// the guard on the 64 KiB block first (and on every other view of the +/// page), and the block then counts as written by the title: the host +/// copy that just put the bytes there copies all 64 KiB of it back in at +/// its next refresh, and sends them up to the card again if it lives +/// there. In runs 218-222 the bytes copied in went with the bytes copied +/// back, 0.83 MB for each MB (78 readings), some 50 MB of 142 MB a frame. +/// +/// With the switch the bytes are stored through a view of our own on the +/// same section, which no guard covers: the title's views stay read-only +/// (a title write still faults and is seen), the write-watch journal is +/// told the page was written (`crate::watch::wrote_own`) so that every +/// other copy of it takes it again, and the copy that wrote it notes the +/// page current (`put_back_own` in `crate::shadow`). +pub(crate) fn back_own() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BACK_OWN_VIEW").is_some_and(|v| v == "1")) +} + +/// A view of our own on a whole section of the title's physical pages: +/// where it is, its bytes, and which of its 64 KiB blocks we have asked +/// to be committed through it (a bit each). +struct Own { + base: usize, + bytes: u64, + committed: Vec, +} + +/// Our own views by section handle; `None` in a section's place if the +/// host refused the view (not asked again). +static OWN: Mutex>>> = Mutex::new(None); + +/// Stores `bytes` at title address `at` through a view of our own +/// ([`back_own`]), if `[at, at + bytes.len())` lies in one 64 KiB page of +/// a title view of a section. Gives the addresses of that page in every +/// title view that shows it (the page of `at` among them), or `None` with +/// nothing written: not view memory, a page of very many views, the +/// runtime changing mappings at this moment, or the host refusing. +pub(crate) fn write_own(at: usize, bytes: &[u8]) -> Option> { + if bytes.is_empty() || at / K64 != (at + bytes.len() - 1) / K64 { + return None; + } + // No mapping changes until the bytes are in: the view found below + // shows these pages for as long as this is held. + let _still = crate::watch::title_memory_reading_now()?; + let (section, offset, shown, section_bytes) = { + let v = views(); + let (&base, &(len, section, offset)) = v.views.range(..=at).next_back()?; + if at + bytes.len() > base + len { + return None; + } + let offset = offset + (at - base) as u64; + let shown = v.pages.get(&(section, offset - offset % K64 as u64))?.clone(); + if shown.len() > crate::watch::MANY_VIEWS { + return None; + } + let section_bytes = v.sections.iter().find(|s| s.0 == section)?.1; + (section, offset, shown, section_bytes) + }; + if offset + bytes.len() as u64 > section_bytes { + return None; + } + let mut own = OWN.lock().unwrap_or_else(|e| e.into_inner()); + let view = own + .get_or_insert_with(Default::default) + .entry(section) + .or_insert_with(|| { + // SAFETY: a section handle the runtime gave us, alive as long + // as the title's views of it are; the view is ours and stays. + let at = unsafe { mem::MapViewOfFile(section as *mut c_void, mem::FILE_MAP_WRITE, 0, 0, 0) }; + if at.Value.is_null() { + tracing::warn!( + section, + error = %std::io::Error::last_os_error(), + "no view of our own on a section of title pages: what shaders wrote goes back the old way there" + ); + return None; + } + tracing::info!( + section, + mb = section_bytes >> 20, + "a view of our own on a section of title pages, for what shaders wrote (VICTORY_BACK_OWN_VIEW=1)" + ); + Some(Own { + base: at.Value as usize, + bytes: section_bytes, + committed: vec![0; (section_bytes as usize).div_ceil(K64).div_ceil(64)], + }) + }) + .as_mut()?; + if offset + bytes.len() as u64 > view.bytes { + return None; + } + let block = offset as usize / K64; + if (view.committed[block / 64] & (1u64 << (block % 64))) == 0 { + // The title's view committed these pages of the section; asked + // once more through ours, which changes nothing if they are. + // SAFETY: a block inside our own view. + let there = unsafe { + mem::VirtualAlloc((view.base + block * K64) as *const c_void, K64, mem::MEM_COMMIT, mem::PAGE_READWRITE) + }; + if there.is_null() { + return None; + } + view.committed[block / 64] |= 1u64 << (block % 64); + } + // SAFETY: committed bytes inside our own view; the source is the + // caller's slice. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), (view.base + offset as usize) as *mut u8, bytes.len()) }; + Some(shown) +} + /// How the views cover `[at, at + len)`. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub(crate) enum Cover { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 54e12518..d4936077 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -17,17 +17,23 @@ #[cfg(all(windows, feature = "diagnostics"))] mod capture; +#[cfg(windows)] +mod cardmeter; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; pub mod descriptor; pub mod device; #[cfg(windows)] +mod drvwatch; +#[cfg(windows)] mod draw; pub mod dxgi; pub mod fence; pub mod frame; #[cfg(windows)] +pub mod framelog; +#[cfg(windows)] mod host; #[cfg(windows)] mod indirect; @@ -37,6 +43,8 @@ pub mod list; pub mod object; pub mod pipeline; #[cfg(windows)] +mod plaincopy; +#[cfg(windows)] mod primitive; #[cfg(all(windows, feature = "diagnostics"))] mod profile; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 516ba261..3bf89f3c 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -847,6 +847,11 @@ fn unlike(dst: This, src: This) -> bool { unlike } +/// Copies left out because both sides were one host texture +/// ([`copy_resource`], [`copy_texture_region`]), since the start. +#[cfg(windows)] +pub(crate) static SELF_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(windows)] { @@ -860,6 +865,17 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { if unlike(dst, src) { return; } + // 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 + // nothing. It was recorded all the same, with the texture left + // in the source state as the copy's destination (run 205's + // debug layer: "CopyResource with its destination in the + // COPY_SOURCE state", 37 times, a 2560x1440 depth texture). + // Only the two state changes and the copy are left out: what + // is noted of the textures stays as it was. After + // triippywhale 6e502b3b. + let same = windows::core::Interface::as_raw(to) == windows::core::Interface::as_raw(from); // A source the title fills itself is uploaded first (upstream // PR #671): a copy read whatever the host texture held. if crate::texture::title_written(from) { @@ -871,9 +887,21 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { // A destination made level by level gets its levels' memory // ahead of this list (`crate::tiles`). crate::texture::card_writes(list, dst, to, None); + crate::texture::host_written(dst); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + ?dst, + ?src, + "a copy between two title textures that share one host texture is left out: the first one" + ); + }); + return; + } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. @@ -966,6 +994,8 @@ extern "system" fn copy_texture_region( return; } let mut from = src; + // Both sides are the same subresource of one host texture (set below). + let mut same = false; let _upload; // keeps the source alive while this call records it #[cfg(feature = "diagnostics")] let mut read = None; @@ -994,11 +1024,21 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; + // The same subresource of one host texture on both sides (two + // title textures over one memory): not a copy the host allows. + // The states and the copy are left out below; the rest is + // noted as before. + same = texture.as_raw() == to.as_raw() + && src.kind != FOOTPRINT + && dst.kind != FOOTPRINT + && src.footprint.offset as u32 == dst.footprint.offset as u32; list.twin_use(src.resource, false, false); if crate::texture::title_written(texture) { crate::texture::upload(list, src.resource, texture); } - ensure_state(list, src.resource, COPY_SOURCE); + if !same { + ensure_state(list, src.resource, COPY_SOURCE); + } from.resource = texture.as_raw().cast_const().cast(); } // A depth texture shaders also write: what they wrote, first (the @@ -1009,8 +1049,12 @@ extern "system" fn copy_texture_region( // of its result into a block-compressed texture of that kind, and // a copy into a level without memory is dropped. crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32)); - ensure_state(list, dst.resource, COPY_DEST); crate::texture::host_written(dst.resource); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return; + } + ensure_state(list, dst.resource, COPY_DEST); let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::()); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 60ed05c0..327f07aa 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -63,6 +63,10 @@ pub(crate) struct Shader { container: Vec, #[cfg(windows)] translated: OnceLock>, + /// Whether its code walks the ray-tracing structures, once looked at + /// ([`Shader::walks`]). + #[cfg(windows)] + walks: OnceLock, } impl std::fmt::Debug for Shader { @@ -113,6 +117,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { container: bytes.to_vec(), #[cfg(windows)] translated: OnceLock::new(), + #[cfg(windows)] + walks: OnceLock::new(), }) }) .clone() @@ -263,6 +269,87 @@ pub(crate) fn builder_quarantined(this: This) -> bool { is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1")) } +#[cfg(windows)] +impl Shader { + /// Whether the program walks the ray-tracing structures: its code has + /// an `image_bvh_intersect_ray` or `image_bvh64_intersect_ray`. Looked + /// at once, when a dispatch first asks. + fn walks(&self) -> bool { + *self.walks.get_or_init(|| container_walks(&self.container)) + } +} + +/// Whether a console container's code tests rays against the nodes of a +/// ray-tracing structure. +#[cfg(windows)] +fn container_walks(container: &[u8]) -> bool { + use victory_shader::{Container, FourCC}; + let Ok(c) = Container::parse(container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| victory_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(|p| code_walks(&p.code))) +} + +/// Whether native code has a ray-tracing node test. +#[cfg(windows)] +fn code_walks(code: &[u8]) -> bool { + victory_shader::gfx10::decode(code).is_ok_and(|code| code.iter().any(|i| i.name().is_some_and(|n| n.starts_with("image_bvh")))) +} + +/// Dispatches held back by [`walk_held`] since the last frame line. +#[cfg(windows)] +pub(crate) static WALKS_HELD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a dispatch with the title's pipeline `this` is held back +/// because its program walks ray-tracing structures nothing has built +/// (`VICTORY_BVH_HOLD=1`; off by default). +/// +/// The structure builder does not run (see [`Builder`]: only with +/// `VICTORY_BVH_BUILDER=1`, and then only whole, which a host of 32-lane +/// waves does not manage yet). The title's ray-traced passes run all the +/// same: 64 programs of its shader pack test rays against structure nodes +/// (ray-traced shadows, screen probes, reflections, the irradiance cache; +/// one of them, `CS_IrradianceCache_ShadowTrace_WithFar` f607780aa8e502d0, +/// from the first world frame on in every run). Each walks, in a loop the +/// title bounds at 65,535 steps a wave, whatever bytes lie where the +/// structure would be: what it returns is not a picture of the scene, and +/// how long it runs depends on those bytes. Upstream's pull request 2311 +/// measured a card hung in exactly that dispatch on an NVIDIA card, every +/// run, and both card losses of ours since the draw windows' own fault was +/// fixed (runs 208 and 224) came within a second of the first use of the +/// programs that shade those rays' hits (`CS_RaytracingResolve`). +/// +/// With the switch such a dispatch is dropped until the builder has run +/// whole. What the passes would have written stays as the title left it +/// (their targets are not cleared by us): the picture has to be looked at. +#[cfg(windows)] +pub(crate) fn walk_held(this: This) -> bool { + static ON: OnceLock = OnceLock::new(); + if this.is_null() || !*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_HOLD").is_some_and(|v| v == "1")) { + return false; + } + let p = pipeline(this); + if !p.shaders.iter().any(|s| s.stage == "compute" && s.walks()) { + return false; + } + // (Asked only for the few programs that walk: the lock is the builder's.) + if BUILDER.lock().unwrap_or_else(|e| e.into_inner()).whole { + return false; + } + if WALKS_HELD.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + shaders = ?p.shaders, + "a dispatch of a program that walks ray-tracing structures is held back: the structure builder has not built them (VICTORY_BVH_HOLD=1); the first one" + ); + }); + } + true +} + /// Whether the title's pipeline `this` is one of the structure builder's. #[cfg(windows)] pub(crate) fn is_builder(this: This) -> bool { @@ -692,6 +779,14 @@ static FUNCTIONS: Table<24> = { pub(crate) mod host; #[cfg(windows)] mod library; + +/// Host pipelines created and loaded from the library since the start +/// (`crate::framelog`). +#[cfg(windows)] +pub(crate) fn frame_log_counts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (library::MADE.load(Relaxed), library::LOADED.load(Relaxed)) +} #[cfg(windows)] mod make; diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 98624460..b21b7163 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -206,6 +206,7 @@ fn wait(p: &Pending, frame: u64) { } } } + crate::framelog::add(crate::framelog::T::PipelineWaitUs, started.elapsed().as_micros() as u64); #[cfg(feature = "diagnostics")] crate::copystat::add( crate::copystat::C::PipelineWaitUs, diff --git a/crates/victory-gpu/src/plaincopy.rs b/crates/victory-gpu/src/plaincopy.rs new file mode 100644 index 00000000..be8ad343 --- /dev/null +++ b/crates/victory-gpu/src/plaincopy.rs @@ -0,0 +1,239 @@ +//! Copies of title memory made in place, by this process, with a way back +//! when a page is not there (`VICTORY_COPY_PLAIN=1`; off by default). +//! +//! Every copy of title memory into a host buffer goes through the kernel +//! (`ReadProcessMemory` on our own process, `crate::host::copy_mapped`): +//! the title unmaps and remaps its memory while we read it, a read in +//! place of a page that is gone is an access violation, and the kernel's +//! copy fails instead. It costs what a system call that locks and probes +//! every page costs: run 225's profile has the submitting thread 35 ms a +//! frame inside `ZwReadVirtualMemory` for about 100 MB (3 GB a second), +//! where the processor's own copy moves that much in a third of the time. +//! +//! Here the copy is one `rep movsb` in a function of ours that uses no +//! stack. An exception handler, first in the line, looks at every access +//! violation: one that is a READ and happened at exactly that instruction +//! continues at the function's other exit, which returns 0, and the +//! caller falls back to the kernel's copy as before (it says which page +//! is gone and fills in zeros). A write that faults is not ours to take: +//! the destination is host memory, which is always there; such a fault +//! goes on to the handlers after this one. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +#[cfg(target_arch = "x86_64")] +core::arch::global_asm!( + ".globl victory_copy_guarded", + ".globl victory_copy_guarded_at", + ".globl victory_copy_guarded_fault", + "victory_copy_guarded:", + // rcx: to, rdx: from, r8: bytes. rsi and rdi are the caller's: kept in + // r9 and r10, which are ours to use, so nothing is on the stack. + " mov r9, rsi", + " mov r10, rdi", + " mov rdi, rcx", + " mov rsi, rdx", + " mov rcx, r8", + "victory_copy_guarded_at:", + " rep movsb", + " mov rsi, r9", + " mov rdi, r10", + " mov eax, 1", + " ret", + "victory_copy_guarded_fault:", + " mov rsi, r9", + " mov rdi, r10", + " xor eax, eax", + " ret", +); + +#[cfg(target_arch = "x86_64")] +unsafe extern "C" { + fn victory_copy_guarded(to: *mut u8, from: *const u8, len: usize) -> u32; + static victory_copy_guarded_at: u8; + static victory_copy_guarded_fault: u8; +} + +/// Whether copies of title memory into host memory are made in place +/// (`VICTORY_COPY_PLAIN=1`). +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = cfg!(target_arch = "x86_64") && std::env::var_os("VICTORY_COPY_PLAIN").is_some_and(|v| v == "1"); + if on { + install(); + tracing::info!( + "copies of title memory into host buffers are made in place, with the kernel's copy behind them for a \ + page that is not there (VICTORY_COPY_PLAIN=1)" + ); + } + on + }) +} + +/// Copies made in place, their bytes, and the copies that met a page that +/// was not there (and went to the kernel's copy), since the last line. +static COUNT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// The handler that turns a read fault inside [`guarded`] into its return +/// of false; put first in the line, once. +#[cfg(target_arch = "x86_64")] +fn install() { + use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_GUARD_PAGE, EXCEPTION_IN_PAGE_ERROR, + }; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_fault(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched and the + // context it will continue with. + let (r, context) = unsafe { (&*(*info).ExceptionRecord, &mut *(*info).ContextRecord) }; + // Only at the copy's own instruction. + if context.Rip != (&raw const victory_copy_guarded_at) as u64 { + return EXCEPTION_CONTINUE_SEARCH; + } + const READ: usize = 0; + let read = r.NumberParameters >= 1 && r.ExceptionInformation[0] == READ; + let gone = (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION || r.ExceptionCode == EXCEPTION_IN_PAGE_ERROR) && read; + if gone || r.ExceptionCode == EXCEPTION_GUARD_PAGE { + context.Rip = (&raw const victory_copy_guarded_fault) as u64; + return EXCEPTION_CONTINUE_EXECUTION; + } + EXCEPTION_CONTINUE_SEARCH + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: a handler that reads the record it is given and nothing else. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_fault)); + }); +} + +#[cfg(not(target_arch = "x86_64"))] +fn install() {} + +/// Copies `len` bytes from `from` to `to` in place; false if a page of the +/// source was not there (then some of `to` may have been written). +/// +/// `to` must be writable memory of `len` bytes that is ours (host memory); +/// `from` may be anything. +#[cfg(target_arch = "x86_64")] +fn guarded(to: *mut u8, from: *const u8, len: usize) -> bool { + install(); + // SAFETY: the destination is the caller's to write; a source page that + // is not there ends the copy with 0 instead of a fault ([`install`]). + unsafe { victory_copy_guarded(to, from, len) != 0 } +} + +#[cfg(not(target_arch = "x86_64"))] +fn guarded(_: *mut u8, _: *const u8, _: usize) -> bool { + false +} + +/// With [`on`]: copies title memory at `from` into host memory at `to`; +/// false if it is off or a source page was not there (the caller then +/// copies through the kernel, as before). +pub(crate) fn copy(to: *mut u8, from: *const u8, len: usize) -> bool { + if !on() { + return false; + } + let whole = guarded(to, from, len); + if whole { + COUNT[0].fetch_add(1, Relaxed); + COUNT[1].fetch_add(len as u64, Relaxed); + } else { + COUNT[2].fetch_add(1, Relaxed); + } + whole +} + +/// With the frame line: what [`copy`] did per frame over `frames`. +pub(crate) fn line(frames: f64) { + if !on() { + return; + } + let [copies, bytes, gone] = [0, 1, 2].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); + tracing::info!( + "copies of title memory made in place per frame (VICTORY_COPY_PLAIN=1): {copies:.0}, {:.1} MB; {gone:.1} met a page \ + that was not there and went through the kernel's copy", + bytes / 1e6 + ); +} + +#[cfg(all(test, target_arch = "x86_64"))] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + + const PAGE: usize = 4096; + + #[test] + fn memory_that_is_there_is_copied() { + let from: Vec = (0..100_000u32).map(|i| (i * 7 + 3) as u8).collect(); + let mut to = vec![0u8; from.len()]; + assert!(guarded(to.as_mut_ptr(), from.as_ptr(), from.len())); + assert_eq!(to, from); + // Nothing to copy is a copy. + assert!(guarded(to.as_mut_ptr(), from.as_ptr(), 0)); + } + + /// Three pages reserved, the first committed: a copy that stays in the + /// first page is whole; one that runs into the second ends with false, + /// the bytes before the hole copied, and the thread goes on. + #[test] + fn a_page_that_is_not_there_ends_the_copy_without_a_fault() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as *mut u8; + assert!(!base.is_null()); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + // SAFETY: committed and writable. + unsafe { std::slice::from_raw_parts_mut(base, PAGE) }.fill(0xAB); + let mut to = vec![0u8; 2 * PAGE]; + assert!(guarded(to.as_mut_ptr(), base, PAGE)); + assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); + to.fill(0); + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE / 2), PAGE)); + assert!(to[..PAGE / 2].iter().all(|&b| b == 0xAB), "the bytes before the hole"); + assert!(to[PAGE / 2..].iter().all(|&b| b == 0), "nothing after it"); + // A source that is not there at all. + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE), PAGE)); + // Committed but closed to reads. + // SAFETY: the third page of the reservation. + assert!(!unsafe { VirtualAlloc(base.wrapping_add(2 * PAGE).cast(), PAGE, MEM_COMMIT, PAGE_NOACCESS) }.is_null()); + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(2 * PAGE), 16)); + // And the registers the caller owns came back: this still works. + assert!(guarded(to.as_mut_ptr(), base, PAGE)); + assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); + // SAFETY: the test's reservation. + unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; + } + + /// Many threads at once, half of them faulting: each gets its own answer. + #[test] + fn threads_fault_and_copy_side_by_side() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(base, 0); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + let threads: Vec<_> = (0..8) + .map(|t| { + std::thread::spawn(move || { + let mut to = vec![0u8; PAGE]; + for _ in 0..2_000 { + let from = (base + if t % 2 == 0 { 0 } else { PAGE }) as *const u8; + assert_eq!(guarded(to.as_mut_ptr(), from, PAGE), t % 2 == 0); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + // SAFETY: the test's reservation. + unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index bccef27c..3c1f2713 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -58,8 +58,104 @@ enum Held { /// title can add to its end meanwhile; whatever is added stays behind /// this (the line is not empty), signals too. Running, + /// With [`present_behind`]: the title's present of a frame, due after + /// what the queue holds before it: the host texture shown, the state + /// the title's lists leave it in, and the frame's number. + Present(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32, u64), } +/// Presents that are in a queue's line and have not run ([`Held::Present`]). +#[cfg(windows)] +static PRESENTS_HELD: AtomicU64 = AtomicU64::new(0); + +/// Whether a present goes behind the queue's line and returns at once +/// (`VICTORY_ASYNC_PRESENT=1`; needs [`behind`] and presents that do not +/// settle the flights, `crate::host::late_free_present`). +/// +/// Why: with [`behind`] our thread prepares and sends the submissions, but +/// the title's present still ran the line itself first, that is: it stood +/// until our thread had prepared every submission of the frame. Run 225's +/// frame log (the cell, 136 ms a frame): the title's render thread is 77 ms +/// of every frame inside the present waiting for that, using 3 ms of +/// processor itself, and only then begins to record the next frame (about +/// 57 ms), during which our thread has nothing to prepare. The two phases +/// ran one after the other. +/// +/// With the switch the present is one more thing in the line +/// ([`Held::Present`]): our thread shows the frame when it gets there, in +/// order, and the title records the next frame meanwhile. +/// +/// The title is one frame ahead at most: a present that finds the one +/// before it still in a line runs the old way (the lines first, then +/// itself), and so does a frame that is saved or listed, and a present +/// that finds its queue's line empty. A wait nothing ever meets is +/// therefore still forced, by the present after it. +/// +/// What it assumes, beyond what [`behind`] does: title memory a submission +/// reads stays as it was until the submission's fence is signalled, also +/// across the title's present. On the console the card reads that memory +/// when it runs the list, after the present call has returned. +#[cfg(windows)] +fn present_behind() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_ASYNC_PRESENT").is_some_and(|v| v == "1") + && behind() + && crate::host::late_free_present(); + if on { + tracing::info!("presents go behind the queue's line and return at once (VICTORY_ASYNC_PRESENT=1)"); + } + on + }) +} + +/// With [`present_behind`]: puts the present of the next frame behind what +/// the queue `this` holds. False if it has to run the old way. +#[cfg(windows)] +fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool { + if this.is_null() || planes == 0 || PRESENTS_HELD.load(Ordering::Relaxed) != 0 { + return false; + } + let frame = FRAMES.load(Ordering::Relaxed) + 1; + // A frame that is saved or listed is read back at once. + #[cfg(feature = "diagnostics")] + if crate::capture::wanted(frame) || crate::capture::listed(frame) { + return false; + } + // SAFETY: the title passes `planes` plane descriptions. + let Some(plane) = (unsafe { plane_parameters.as_ref() }) else { + return false; + }; + if plane.count == 0 || plane.resources.is_null() { + return false; + } + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + let Some(texture) = crate::resource::host_resource(resource) else { + return false; + }; + // The state the lists recorded so far leave the texture in: what our + // copy finds it in when it runs behind them (looked at, not changed). + const COPY_SOURCE: u32 = 0x800; + let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + crate::resource::host_transition(resource, state); + let texture = texture.clone(); + let sent = hold(this, || { + PRESENTS_HELD.fetch_add(1, Ordering::Relaxed); + Held::Present(texture, state, frame) + }); + if sent { + PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed); + wake(); + } + sent +} + +/// Presents sent behind their queue's line since the start +/// ([`send_behind`]), for the line every 512 of them. +#[cfg(windows)] +static PRESENTS_BEHIND: AtomicU64 = AtomicU64::new(0); + /// The queues that hold something (their addresses). #[cfg(windows)] static WAITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -381,7 +477,19 @@ fn worker() { } *work = false; } + let started = std::time::Instant::now(); + let (user, kernel) = crate::framelog::thread_times(); + if crate::framelog::on() { + crate::framelog::add(crate::framelog::T::WorkerLooks, 1); + if crate::framelog::on_slow_core() { + crate::framelog::add(crate::framelog::T::WorkerSlow, 1); + } + } release_held_now(false); + let (user_now, kernel_now) = crate::framelog::thread_times(); + crate::framelog::add(crate::framelog::T::WorkerUs, started.elapsed().as_micros() as u64); + crate::framelog::add(crate::framelog::T::WorkerUserUs, user_now.saturating_sub(user)); + crate::framelog::add(crate::framelog::T::WorkerKernelUs, kernel_now.saturating_sub(kernel)); } } @@ -520,6 +628,27 @@ fn release_held_now(all: bool) { } } } + Held::Present(texture, state, frame) => { + let show = || { + if let Some(host) = crate::host::host() { + let _ = host.present(&texture, state, frame); + } + }; + if all { + show(); + } else { + // The line is open while the frame is shown, + // as it is while a submission is prepared. + held.insert(0, Held::Running); + drop(held); + show(); + held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + } + PRESENTS_HELD.fetch_sub(1, Ordering::Relaxed); + } // Behind what was sent to the card and not waited // for, if anything was. Held::Signal(fence, value) => { @@ -631,6 +760,18 @@ extern "system" fn release(this: This) -> u32 { /// Runs the lists' host lists and waits for them (decision 0007). A queue /// that waits for a fence keeps them until the fence is reached. extern "system" fn execute(this: This, count: u32, lists: *const This) { + #[cfg(windows)] + let started = std::time::Instant::now(); + execute_now(this, count, lists); + #[cfg(windows)] + { + let us = started.elapsed().as_micros() as u64; + crate::framelog::add(crate::framelog::T::ExecuteUs, us); + crate::framelog::here(crate::framelog::H::ExecuteUs, us); + } +} + +fn execute_now(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } @@ -872,19 +1013,40 @@ pub(crate) fn presented() -> u64 { /// shortcut: one plane, no scaling or placement, the source expected in /// the common state. extern "system" fn present( - _: This, + this: This, planes: u32, plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + #[cfg(windows)] + let presenting = std::time::Instant::now(); + let hr = present_now(this, planes, plane_parameters); + #[cfg(windows)] + { + crate::framelog::add(crate::framelog::T::PresentUs, presenting.elapsed().as_micros() as u64); + crate::framelog::frame(); + } + hr +} + +fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESULT { + #[cfg(windows)] + let presenting = std::time::Instant::now(); #[cfg(all(windows, feature = "diagnostics"))] crate::copystat::present_begins(); #[cfg(all(windows, feature = "diagnostics"))] crate::profile::frame(); + // With `present_behind`: the frame is shown by our thread, behind what + // the queue holds, and nothing is run or waited for here. + #[cfg(windows)] + let sent_behind = present_behind() && send_behind(this, planes, plane_parameters); + #[cfg(not(windows))] + let _ = this; // Submissions sent to the card and not waited for are settled first, // and what that frees runs in its own order, before anything is forced. #[cfg(windows)] - if crate::host::late() && !crate::host::late_free_present() { + if sent_behind { + } else if crate::host::late() && !crate::host::late_free_present() { // (With `behind`: what the queues hold runs here first, and what // it sent is settled with the rest.) if behind() { @@ -901,8 +1063,20 @@ extern "system" fn present( // shortcut: what a queue still holds at a present runs now, whatever // its fence: a wait is not kept across frames. #[cfg(windows)] - release_held(forces()); + if !sent_behind { + release_held(forces()); + } + #[cfg(windows)] + crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(windows)] + if sent_behind && PRESENTS_BEHIND.load(Ordering::Relaxed).is_multiple_of(512) { + tracing::info!( + frame, + behind = PRESENTS_BEHIND.load(Ordering::Relaxed), + "presents sent behind their queue's line so far (VICTORY_ASYNC_PRESENT=1); the others ran the old way" + ); + } if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); #[cfg(windows)] @@ -939,7 +1113,8 @@ extern "system" fn present( } } #[cfg(windows)] - if planes > 0 + if !sent_behind + && planes > 0 // SAFETY: the title passes `planes` plane descriptions. && let Some(plane) = unsafe { plane_parameters.as_ref() } && plane.count > 0 diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 458583d6..da0a2683 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2623,12 +2623,66 @@ impl Shadow { return 0; } crate::host::shaders_write(start + at, &title[..]); + if self.put_back_own(start + at, &title[..]) { + return n; + } crate::watch::writing(start + at, n); merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } + /// With `crate::inplace::back_own` (`VICTORY_BACK_OWN_VIEW=1`): stores + /// what a merge made of title memory `[at, at + bytes.len())` (inside + /// one 64 KiB page, as every merged stretch is) through a view of our + /// own, tells the journal, and notes the page current for this copy if + /// it was current before: the copy holds the same bytes (the merge put + /// them into both), so the next refresh need not take the page again. + /// The guards are not touched: a title write to the page still faults + /// and is reported at a later asking, which every copy then takes, + /// this one too. False with nothing done if the switch is off or the + /// memory cannot be written that way (the caller writes as before). + fn put_back_own(&self, at: usize, bytes: &[u8]) -> bool { + /// Since the start: stretches and bytes stored this way, pages + /// noted current for their copy, stretches written the old way. + static OWN_WRITES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + if !crate::inplace::back_own() { + return false; + } + let Some(shown) = crate::inplace::write_own(at, bytes) else { + OWN_WRITES[3].fetch_add(1, Ordering::Relaxed); + return false; + }; + let page = at / PAGE; + let others: Vec = shown.iter().map(|&a| a / PAGE).filter(|&p| p != page).collect(); + let (before, now) = crate::watch::wrote_own(page, &others); + // A placed texture there changed with no descriptor written (what + // `crate::watch::writing` tells the texture table on the old way). + crate::descriptor::host::remapped(at, bytes.len()); + let base = self.start as usize / PAGE; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(taken) = page.checked_sub(base).and_then(|i| copied.get_mut(i)) + && *taken != 0 + && *taken >= before + { + *taken = (*taken).max(now); + OWN_WRITES[2].fetch_add(1, Ordering::Relaxed); + } + } + OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); + let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; + if n % 16384 == 0 { + tracing::info!( + "what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way", + OWN_WRITES[1].load(Ordering::Relaxed) >> 20, + OWN_WRITES[2].load(Ordering::Relaxed), + OWN_WRITES[3].load(Ordering::Relaxed) + ); + } + true + } + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of /// `[from, to)` of the copy that differ from `before` (the bytes from /// `from` on), as (offset, bytes) in order; compared on several threads @@ -3324,6 +3378,9 @@ impl Shadow { return 0; } crate::host::shaders_write(start + at, &title[..]); + if self.put_back_own(start + at, &title[..]) { + return n; + } crate::watch::writing(start + at, n); merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index a3e7c163..b9cf5719 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -401,7 +401,11 @@ pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { st fn waited(slot: usize, f: impl FnOnce() -> T) -> T { let started = std::time::Instant::now(); let out = f(); - REFRESH_WAITS[slot].fetch_add(started.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + let us = started.elapsed().as_micros() as u64; + REFRESH_WAITS[slot].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + if slot == 2 { + crate::framelog::add(crate::framelog::T::RefreshStillUs, us); + } out } @@ -693,6 +697,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); + crate::framelog::add(crate::framelog::T::Uploads, 1); const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); // The staging buffer lives as long as `staging`, which the deferred @@ -975,7 +980,9 @@ impl Staging { fn refresh_now(&self) -> usize { let whole = std::time::Instant::now(); let read = self.refresh_timed(); - REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + let us = whole.elapsed().as_micros() as u64; + REFRESH_WAITS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + crate::framelog::add(crate::framelog::T::RefreshUs, us); read } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 02d066f2..057f938f 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -112,6 +112,17 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { if j.kept { return; } + // View memory the guards hold is left to `writes`, which answers it + // from the guards ([`known_view`]): the kernel's write watch can only + // fail there. Asked here with the others, a run holding such a range + // failed, was asked again by halves down to single ranges, failing + // each time, and the range then went to `writes` all the same (after + // triippywhale d0581a55). `VICTORY_VIEW_ASK=1` asks as before. + #[cfg(feature = "diagnostics")] + let all = pieces.len(); + pieces.retain(|&(first, _)| !known_view(first * PAGE)); + #[cfg(feature = "diagnostics")] + AHEAD_VIEWS.fetch_add((all - pieces.len()) as u64, std::sync::atomic::Ordering::Relaxed); j.asked += 1; j.ahead_asked = j.asked; j.ahead.clear(); @@ -151,6 +162,12 @@ fn slow(us: u64) { SLOW[2].fetch_max(us, Relaxed); } +/// Since the last frame line: ranges of view memory the guards hold that a +/// submission's askings ahead ([`ask_ahead`], [`ask_once`]) left out. Each +/// was a kernel asking that failed, or several, before. +#[cfg(feature = "diagnostics")] +pub(crate) static AHEAD_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// [`SLOW`], taken. #[cfg(feature = "diagnostics")] pub(crate) fn slow_asks() -> [u64; 3] { @@ -214,6 +231,15 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { if start >= end { continue; } + // View memory the guards hold is not asked about: the asking can + // only fail there, one failed kernel call for each such copy at + // every submission, and `writes` answers it from the guards + // (after triippywhale cc368c7c). + if known_view(start) { + #[cfg(feature = "diagnostics")] + AHEAD_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + continue; + } let (first, last) = (start / PAGE, end.div_ceil(PAGE)); if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) { j.ahead.push((first, last)); @@ -253,6 +279,34 @@ pub(crate) fn wrote(at: usize, len: usize) { } } +/// We wrote the 64 KiB page numbered `page` of title memory through a +/// view of our own (`crate::inplace::write_own`): no guard was opened and +/// no kernel write-watch bit set, so the journal is told here. The page, +/// and the same physical page at its other title addresses (`others`, +/// page numbers), count as written at a new asking, which every host copy +/// that holds them takes at its next refresh. Returns the asking that had +/// last found `page` written (0: never) and the new one, for the copy +/// that wrote to note itself current. +pub(crate) fn wrote_own(page: usize, others: &[usize]) -> (u64, u64) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + j.asked += 1; + let now = j.asked; + // As in [`wrote`]: an asking that stands for a submission, or for a + // flush, moves with it, or a copy taking the page at the standing + // asking would find it written "later" at every refresh. + if j.kept || !j.ahead.is_empty() { + j.ahead_asked = now; + } + let before = j.written.insert(page, now).unwrap_or(0); + for &other in others { + if other != page { + j.written.insert(other, now); + } + } + (before, now) +} + /// 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`]. @@ -467,7 +521,7 @@ fn known_view(start: usize) -> bool { } let g = guards(); let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) } struct Guards { @@ -482,6 +536,27 @@ struct Guards { /// (those views' blocks are in it too): a write to one opens them all. /// A write range can be huge (`fread`), so only these are looked up. aliased: BTreeSet, + /// With [`view_known`]: blocks made read-only at least once since the + /// runtime last mapped or unmapped them. They are view memory whether + /// their guard stands now or a write has opened it. + viewed: BTreeSet, +} + +/// Whether a block once guarded stays known as view memory while its +/// guard is open (`VICTORY_VIEW_KNOWN=1`; off by default). +/// +/// A range whose first block the title wrote since the last check has +/// that block neither read-only nor noted absent, so nothing says it is a +/// view: the kernel's write watch is asked and fails, and then Windows is +/// asked what the memory is (`is_view`), a walk of the page tables to the +/// end of the pages that share the first one's state. In runs 222 and 225 +/// that was 338-450 failed askings a frame and 6.5-7.8 ms a frame of the +/// submitting thread in `VirtualQuery`. With the switch the block is +/// remembered from the time it was first made read-only until the runtime +/// maps or unmaps it ([`title_memory_remapped`]). +fn view_known() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_KNOWN").is_some_and(|v| v == "1")) } static GUARDS: Mutex = Mutex::new(Guards { @@ -489,6 +564,7 @@ static GUARDS: Mutex = Mutex::new(Guards { clean: BTreeSet::new(), absent: BTreeSet::new(), aliased: BTreeSet::new(), + viewed: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -510,7 +586,7 @@ fn guard(start: usize, end: usize) -> Option> { let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { let g = guards(); let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) }; if !known && !is_view(start, end) { return None; @@ -678,6 +754,9 @@ fn protect_alias(g: &mut Guards, block: usize) { // SAFETY: title view memory; only its protection changes. if unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0 { g.protected.insert(block); + if view_known() { + g.viewed.insert(block); + } } } @@ -699,6 +778,9 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) { let note = |g: &mut Guards, from: usize, to: usize| { g.protected.extend(from..to); g.clean.extend(from..to); + if view_known() { + g.viewed.extend(from..to); + } }; if set(from, to) { note(g, from, to); @@ -897,14 +979,25 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); /// What the runtime holds while it changes what title memory shows /// ([`title_memory_remapping`]). -pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); +pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, std::time::Instant); + +impl Drop for Remapping { + fn drop(&mut self) { + // From asking for the lock until it is let go (the frame log). + crate::framelog::add(crate::framelog::T::RemapUs, self.1.elapsed().as_micros() as u64); + } +} /// The runtime is about to map, unmap or move physical pages of title /// memory: until what it returns is dropped, no read of title memory in /// place is under way and none begins ([`title_memory_reading`]). Taken /// around the whole change, the unmapping and the mapping again. pub fn title_memory_remapping() -> Remapping { - Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) + let asked = std::time::Instant::now(); + let held = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + crate::framelog::add(crate::framelog::T::Remaps, 1); + crate::framelog::add(crate::framelog::T::RemapWaitUs, asked.elapsed().as_micros() as u64); + Remapping(held, asked) } /// What a read of title memory in place holds ([`title_memory_reading`]). @@ -955,6 +1048,11 @@ pub fn title_memory_remapped(at: usize, len: usize) { for block in aliased { g.aliased.remove(&block); } + // What the range shows is new: no longer known to be a view. + let viewed: Vec = g.viewed.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in viewed { + g.viewed.remove(&block); + } } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -983,6 +1081,7 @@ fn install() { if open(&mut g, at, at + 1) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::GuardFaults, 1); + crate::framelog::add(crate::framelog::T::GuardFaults, 1); return EXCEPTION_CONTINUE_EXECUTION; } if writable(at) { diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 8208880e..5a320690 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -517,6 +517,13 @@ impl Lanes { *requests += 1; *bytes += u64::from(job.request.destination_size); *busy += started.elapsed(); + #[cfg(windows)] + { + use victory_gpu::framelog::{T, add}; + add(T::DiskReads, 1); + add(T::DiskBytes, u64::from(job.request.destination_size)); + add(T::DiskUs, started.elapsed().as_micros() as u64); + } if job.request.options & BCPACK != 0 { self.bcpack.0 += u64::from(job.request.destination_size); self.bcpack.1 += started.elapsed(); diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index cc13821c..e566bafa 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -185,13 +185,23 @@ pub fn title() -> Title { pub fn use_console_timers() { use windows_sys::Win32::Media::timeBeginPeriod; use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, ProcessPowerThrottling, SetProcessInformation, }; + // Also: the system does not run this process at reduced speed (its + // "efficiency mode": lower clock, the slow cores of a hybrid processor) + // when its window is not the one in front, as while its owner works in + // another window or streams. The console has eight cores alike and no + // such mode. `VICTORY_EFFICIENCY_MODE=1` leaves the system its choice. + let execution = if std::env::var_os("VICTORY_EFFICIENCY_MODE").is_some_and(|v| v == "1") { + 0 + } else { + PROCESS_POWER_THROTTLING_EXECUTION_SPEED + }; let keep = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, - ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION | execution, StateMask: 0, }; // SAFETY: plain process settings; `keep` outlives the call. From 0b0074e0b2765e574c622e9a3de566f20f04135b Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:43:36 -0500 Subject: [PATCH 06/16] Copies in place measured and fixed, our threads on the fast cores, and a corrected comparison of draw windows - VICTORY_COPY_PLAIN=1 also serves reads of title memory into buffers of the layer; reads under 256 bytes stay with the kernel and a source that faulted is left alone for two seconds (the first form took the layer's one-byte askings too: 1,000 to 1,300 faults a frame). - The submit and copy-back threads ask for the fast cores of a hybrid processor (VICTORY_FAST_CORES=0: not). - VICTORY_DISK_CORES=slow (off): the DirectStorage workers ask for the slow cores. - README: the 6.0 against 8.9 frames a second given for draw windows compared runs in different scenes and is withdrawn; frame time against draws per frame is given instead. A first play session past the first rooms lost the device in the open world with the card out of room for new textures; cause not known. Measured on an RTX 4070 (one run each): at 4,500 draws a frame 145 ms with windows off, 124 ms with windows on and copies in place; 7-8 frames a second in the first rooms, 10-12 in lighter views. No driver entry, no device loss in that run. This merged tree was built; the unit tests of the changed parts were run on the development tree. Co-Authored-By: Claude Fable 5.2 --- README.md | 36 +++++- crates/victory-gpu/src/framelog.rs | 123 ++++++++++++++++----- crates/victory-gpu/src/host.rs | 6 +- crates/victory-gpu/src/plaincopy.rs | 89 ++++++++++++++- crates/victory-gpu/src/queue.rs | 1 + crates/victory-hle/src/modules/dstorage.rs | 10 ++ 6 files changed, 223 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index c535ede2..d43f5286 100644 --- a/README.md +++ b/README.md @@ -133,9 +133,15 @@ What did it, on top of the list below: frame (`VICTORY_CAPTURE_WORLD`, every 8th world frame) is read back and written as a PNG inside the present, 235 ms each. `VICTORY_CAPTURE_WORLD_EVERY=64` for runs that measure speed. - - `VICTORY_INDIRECT_WINDOW=1` measured again with those instruments: - 6.0 -> 8.9 frames a second on average in the first room, 3.1 -> 4.2 - in the opening cutscene. + - `VICTORY_INDIRECT_WINDOW=1` measured again with those instruments. A + CORRECTION: the first figures given here (6.0 against 8.9 frames a + second) compared two runs that stood in different scenes during the + measured window (about 4,300 against 1,550 draws a frame) and are + withdrawn. Compared at equal draws, by a line fitted to each run's + frame times against its draws per frame: windows off 145 ms at 4,500 + draws and 271 ms at 10,000; windows on with `VICTORY_COPY_PLAIN=1` + 124 ms and 211 ms. On screen: 7-8 frames a second in the first rooms, + 10-12 in their lighter views. - A driver watch (on by default; `VICTORY_DRIVER_WATCH=0` off): the layer subscribes to the system's event log and logs every entry of a display driver as it is recorded; the first one turns draw windows @@ -150,10 +156,22 @@ What did it, on top of the list below: sync looks at a changed page's records under one lock, fingerprint first; guarded view memory is left out of a submission's write-watch askings ahead (after triippywhale). - - Behind switches, built and unit-tested, not yet shown to pay: - `VICTORY_COPY_PLAIN=1` (copies of title memory made in place by this + - `VICTORY_COPY_PLAIN=1`: copies of title memory made in place by this process, with a handler that falls back to the kernel's copy on a - missing page), `VICTORY_REFRESH_ONCE=1`, `VICTORY_VIEW_KNOWN=1`, + missing page. Its first form also took the layer's one-byte "is this + page there" reads, 1,000 to 1,300 faults a frame, and won nothing; + reads under 256 bytes now stay with the kernel and a source that + faulted is left alone for two seconds (4 to 9 faults a frame). The + submit thread's kernel time fell from 44 to 20 ms a frame; the + picture is the same. + - The layer's submit and copy-back threads ask for the fast cores of a + hybrid processor (`VICTORY_FAST_CORES=0`: not): the submit thread was + found on a slow core in 6 % of its looks, now in none of 21,059. + `VICTORY_DISK_CORES=slow` (off, not measured) asks the slow cores for + the DirectStorage workers, which are as many as the logical + processors and free to run anywhere. + - Behind switches, built and unit-tested, not yet shown to pay: + `VICTORY_REFRESH_ONCE=1`, `VICTORY_VIEW_KNOWN=1`, `VICTORY_BACK_OWN_VIEW=1` (picture to be checked), `VICTORY_ASYNC_PRESENT=1` (the present goes behind the queue's line; no gain while the card is the limit). @@ -168,6 +186,12 @@ What did it, on top of the list below: Still open: the per-record clamp is most of the card's time, and the copies between the PC's memory and the card's are most of the submit thread's; the cause of the one device loss with windows is not known. + A first play session past the first rooms reached the open world and + lost the device there with no driver entry (reason "device removed"): + the card had no room for new textures from the opening cutscene on + (9.2 of a 10.3 GB budget on a 12 GB card; 2,073 passes made no texture + for lack of room; 44,613 textures let go and made again in 13 minutes). + Cause of that removal not known either. - Known and counted, not fixed yet: an indirect compute pass asks for about 77,500 thread groups in x where one dispatch runs 65,535 (the rest is cut off). diff --git a/crates/victory-gpu/src/framelog.rs b/crates/victory-gpu/src/framelog.rs index bebc9d72..0d90bae5 100644 --- a/crates/victory-gpu/src/framelog.rs +++ b/crates/victory-gpu/src/framelog.rs @@ -152,39 +152,14 @@ pub fn here(h: H, n: u64) { /// one of a lower efficiency class than the best. Always false where all /// cores are alike. pub fn on_slow_core() -> bool { - use windows_sys::Win32::System::SystemInformation::{ - GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION, - }; - use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessorNumber}; + use windows_sys::Win32::System::Threading::GetCurrentProcessorNumber; /// By logical processor (of group 0): whether it is slow. static SLOW: std::sync::OnceLock> = std::sync::OnceLock::new(); let slow = SLOW.get_or_init(|| { - let mut bytes = 0u32; - // SAFETY: a size query, then the call into a buffer of that size. - unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; - let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; - // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. - let ok = unsafe { - GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) - }; - let mut classes: Vec<(u8, u8)> = Vec::new(); - let mut at = 0usize; - while ok != 0 && at + size_of::() <= bytes as usize { - // SAFETY: a record inside the buffer; each says its own size. - let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; - if info.Size == 0 { - break; - } - // SAFETY: the record's type is CpuSet (the only one there is). - let set = unsafe { &info.Anonymous.CpuSet }; - if set.Group == 0 { - classes.push((set.LogicalProcessorIndex, set.EfficiencyClass)); - } - at += info.Size as usize; - } - let best = classes.iter().map(|c| c.1).max().unwrap_or(0); - let mut slow = vec![false; classes.iter().map(|c| c.0 as usize + 1).max().unwrap_or(0)]; - for (processor, class) in &classes { + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let mut slow = vec![false; sets.iter().map(|c| c.1 as usize + 1).max().unwrap_or(0)]; + for (_, processor, class) in &sets { slow[*processor as usize] = *class < best; } tracing::info!( @@ -200,6 +175,94 @@ pub fn on_slow_core() -> bool { slow.get(processor).copied().unwrap_or(false) } +/// The system's processor sets of group 0: each one's id, its logical +/// processor and its efficiency class (higher is faster). +fn cpu_sets() -> Vec<(u32, u8, u8)> { + use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let mut sets = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + sets.push((set.Id, set.LogicalProcessorIndex, set.EfficiencyClass)); + } + at += info.Size as usize; + } + sets +} + +/// Asks the system to run the calling thread on the fast cores only, where +/// the processor has two kinds (`VICTORY_FAST_CORES=0`: not asked). +/// +/// The title keeps its own threads on fast cores (run 229: its render +/// thread in 3,484 looks of 3,484, its recording threads in 104,254 of +/// 104,254), as on the console, whose eight cores are alike. The layer's +/// submit thread was found on a slow one in 1,529 looks of 24,021, and the +/// frame waits for that thread. A set of processors selected for a thread +/// is a preference the scheduler keeps unless nothing of it is free. +pub fn keep_on_fast_cores(what: &str) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_FAST_CORES").is_none_or(|v| v != "0")) { + return; + } + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let fast: Vec = sets.iter().filter(|c| c.2 == best).map(|c| c.0).collect(); + // All alike (or nothing known): nothing to ask for. + if fast.is_empty() || fast.len() == sets.len() { + return; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + if ok == 0 { + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + } else { + tracing::info!(what, fast = fast.len(), of = sets.len(), "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + } +} + +/// Asks the system to run the calling thread on the slow cores only, where +/// the processor has two kinds and at least eight slow logical processors +/// (a helper that must not take a fast core from the title's threads). +/// True if it was asked. +/// +/// The title pins its threads as on the console, where disk decompression +/// is the hardware's: measured on a 14700KF, 31 of its threads are tied to +/// logical processors 0-13, the fast cores. The layer decompresses on as +/// many worker threads as there are logical processors (28), free to run +/// anywhere: in the opening cutscene's streaming stretch about ten of them +/// were busy while the title's recording calls took three times as long. +pub fn keep_on_slow_cores(what: &str) -> bool { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let slow: Vec = sets.iter().filter(|c| c.2 < best).map(|c| c.0).collect(); + if slow.len() < 8 { + return false; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), slow.as_ptr(), slow.len() as u32) } != 0; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!(what, slow = slow.len(), of = sets.len(), ok, "helper threads are kept on the slow cores: the first one"); + }); + ok +} + /// Whether frames are logged. pub fn on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b559f646..766e735d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3110,6 +3110,7 @@ fn late_helper() { let Some(host) = host() else { return; }; + crate::framelog::keep_on_fast_cores("victory-late-wait"); // SAFETY: a plain event of our own. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { tracing::warn!("no event for the thread that settles submissions sent ahead"); @@ -3232,6 +3233,7 @@ fn relay_worker() { let Some(host) = host() else { return; }; + crate::framelog::keep_on_fast_cores("victory-relay"); // SAFETY: a plain event of our own. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)")); @@ -7157,7 +7159,9 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { /// Reads title memory at `src` into `dst`; false if a page of it is not /// readable. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { - read(src, dst.as_mut_ptr(), dst.len()) + // In place first, if asked for (`crate::plaincopy`): the destination is + // memory of ours, as in `copy_mapped`. + crate::plaincopy::copy(dst.as_mut_ptr(), src, dst.len()) || read(src, dst.as_mut_ptr(), dst.len()) } /// Copies `len` bytes from `src` to `dst` unless a source page is not diff --git a/crates/victory-gpu/src/plaincopy.rs b/crates/victory-gpu/src/plaincopy.rs index be8ad343..4f3e9a41 100644 --- a/crates/victory-gpu/src/plaincopy.rs +++ b/crates/victory-gpu/src/plaincopy.rs @@ -71,9 +71,60 @@ pub(crate) fn on() -> bool { }) } -/// Copies made in place, their bytes, and the copies that met a page that -/// was not there (and went to the kernel's copy), since the last line. -static COUNT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// Copies made in place, their bytes, the copies that met a page that was +/// not there (and went to the kernel's copy), and the copies not tried in +/// place because their source faulted lately ([`RECENT`]) or they were +/// under [`LEAST`] bytes, since the last line. +static COUNT: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// The fewest bytes copied in place. A read of a byte or a word is how the +/// layer ASKS whether a page is there (a texture's first page, a record): +/// it is expected to fail, and a failed kernel read costs a microsecond +/// where a fault and its handler cost tens (run 230: 1,000 to 1,300 faults +/// a frame, nearly all of them such askings, took back most of what the +/// copies in place had won). +const LEAST: usize = 256; + +/// The 64 KiB blocks of title memory a copy in place faulted in lately: +/// their copies go straight to the kernel's, which reads round the hole. +/// By the block's number, in the place its low bits name (a later block +/// with the same low bits takes the place). Forgotten every two seconds: +/// the title maps the memory in the end. +static RECENT: [std::sync::atomic::AtomicUsize; 1024] = [const { std::sync::atomic::AtomicUsize::new(0) }; 1024]; +/// When [`RECENT`] was last emptied (milliseconds of [`now_ms`]). +static EMPTIED: AtomicU64 = AtomicU64::new(0); + +fn now_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// The numbers of the first and last 64 KiB block of `[from, from + len)`, +/// never 0 (0 is an empty place). +fn blocks(from: usize, len: usize) -> (usize, usize) { + ((from >> 16) | 1 << 63, ((from + len.max(1) - 1) >> 16) | 1 << 63) +} + +/// Whether a copy from there faulted lately. +fn faulted_lately(from: usize, len: usize) -> bool { + let now = now_ms(); + let emptied = EMPTIED.load(Relaxed); + if now.saturating_sub(emptied) >= 2_000 && EMPTIED.compare_exchange(emptied, now, Relaxed, Relaxed).is_ok() { + for place in &RECENT { + place.store(0, Relaxed); + } + return false; + } + let (first, last) = blocks(from, len); + RECENT[first & 1023].load(Relaxed) == first || RECENT[last & 1023].load(Relaxed) == last +} + +/// A copy from there faulted. +fn note_fault(from: usize, len: usize) { + let (first, last) = blocks(from, len); + RECENT[first & 1023].store(first, Relaxed); + RECENT[last & 1023].store(last, Relaxed); +} /// The handler that turns a read fault inside [`guarded`] into its return /// of false; put first in the line, once. @@ -137,12 +188,21 @@ pub(crate) fn copy(to: *mut u8, from: *const u8, len: usize) -> bool { if !on() { return false; } + if len < LEAST { + COUNT[4].fetch_add(1, Relaxed); + return false; + } + if faulted_lately(from as usize, len) { + COUNT[3].fetch_add(1, Relaxed); + return false; + } let whole = guarded(to, from, len); if whole { COUNT[0].fetch_add(1, Relaxed); COUNT[1].fetch_add(len as u64, Relaxed); } else { COUNT[2].fetch_add(1, Relaxed); + note_fault(from as usize, len); } whole } @@ -152,10 +212,11 @@ pub(crate) fn line(frames: f64) { if !on() { return; } - let [copies, bytes, gone] = [0, 1, 2].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); + let [copies, bytes, gone, lately, small] = [0, 1, 2, 3, 4].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); tracing::info!( "copies of title memory made in place per frame (VICTORY_COPY_PLAIN=1): {copies:.0}, {:.1} MB; {gone:.1} met a page \ - that was not there and went through the kernel's copy", + that was not there and went through the kernel's copy; left to the kernel's copy untried: {lately:.0} whose source \ + faulted in the last two seconds, {small:.0} of under {LEAST} bytes", bytes / 1e6 ); } @@ -211,6 +272,24 @@ mod tests { unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; } + /// A source that faulted is remembered by its 64 KiB blocks, and only + /// those. + #[test] + fn a_source_that_faulted_is_remembered_by_its_blocks() { + // (Addresses no other test uses; the table is shared.) + let at = 0x7654_3210_0000usize; + assert!(!faulted_lately(at, 4096)); + note_fault(at + 100, 4096); + assert!(faulted_lately(at, 16)); + assert!(faulted_lately(at + 0xffff, 1)); + // A copy that ends in the block, and one that begins in it. + assert!(faulted_lately(at - 4096, 8192)); + // The blocks beside it are not remembered. + assert!(!faulted_lately(at + 0x10000, 4096)); + assert!(!faulted_lately(at - 0x10000, 4096)); + assert_eq!(blocks(0, 0), (1 << 63, 1 << 63)); + } + /// Many threads at once, half of them faulting: each gets its own answer. #[test] fn threads_fault_and_copy_side_by_side() { diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 3c1f2713..52dff4e6 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -469,6 +469,7 @@ fn wake() { /// to run, each time something was added or a fence moved. #[cfg(windows)] fn worker() { + crate::framelog::keep_on_fast_cores("victory-submit"); loop { { let mut work = lock(&WORK.0); diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 5a320690..ae859256 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -490,6 +490,16 @@ fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std:: /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { + // `VICTORY_DISK_CORES=slow`: the workers leave the fast cores to the + // title's threads (`victory_gpu::framelog::keep_on_slow_cores`; off by + // default until it is measured). + #[cfg(windows)] + { + static SLOW: OnceLock = OnceLock::new(); + if *SLOW.get_or_init(|| std::env::var_os("VICTORY_DISK_CORES").is_some_and(|v| v == "slow")) { + victory_gpu::framelog::keep_on_slow_cores("dstorage worker"); + } + } let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { From 81e13c9e0789db999674209e05fa980ab4eeb22f Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:13:44 +0000 Subject: [PATCH 07/16] Integrate fxceless round 2: baseline infra + additive files fxceless/main (0b0074e) as the new base: first-room rendering, frame rate chain measured at 6.0 -> 8.9 fps, submit thread, copy queue, levels on demand, warm-up. This commit adds the fork's infrastructure (Linux/Proton chain, extended CI, docs) and the purely additive files (mesh emulation modules, bcpack streaming, tests). Overlap files are merged in follow-ups. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 31 +- .github/workflows/linux-subset.yml | 1150 ++++++++++++++ .../examples/texture_layout_bench.rs | 89 ++ crates/victory-formats/src/bcpack.rs | 1148 +++++++++----- crates/victory-gpu/src/mesh_emu.rs | 335 +++++ crates/victory-loader/src/lib.rs | 1 + crates/victory-shader/src/emit/host.rs | 454 +++++- .../src/emit/intersect_tests.rs | 3 + .../src/emit/lower/code_table_tests.rs | 26 + .../src/emit/lower/mesh_emulation.rs | 137 ++ crates/victory-shader/src/emit/mesh_emu.rs | 1329 +++++++++++++++++ crates/victory-shader/src/emit/rect.rs | 1 + crates/victory-shader/src/emit/shader.rs | 192 ++- crates/victory-shader/src/emit/valu_tests.rs | 117 ++ .../src/emit/waterfall_tests.rs | 2 + crates/victory-shader/src/resource.rs | 4 +- docs/architecture.md | 10 +- docs/compatibility.md | 99 ++ docs/debugging.md | 123 ++ docs/linux-proton.md | 118 ++ docs/linux-wine.md | 115 ++ shell.nix | 42 + 22 files changed, 5113 insertions(+), 413 deletions(-) create mode 100644 .github/workflows/linux-subset.yml create mode 100644 crates/victory-formats/examples/texture_layout_bench.rs create mode 100644 crates/victory-gpu/src/mesh_emu.rs create mode 100644 crates/victory-shader/src/emit/lower/code_table_tests.rs create mode 100644 crates/victory-shader/src/emit/lower/mesh_emulation.rs create mode 100644 crates/victory-shader/src/emit/mesh_emu.rs create mode 100644 docs/compatibility.md create mode 100644 docs/debugging.md create mode 100644 docs/linux-proton.md create mode 100644 docs/linux-wine.md create mode 100644 shell.nix diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 80e6a359..5400e007 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,25 +5,44 @@ on: push: branches: [main] -permissions: - contents: read +# No token permissions by default; the job grants only what it uses. +permissions: {} +# A newer push to a PR cancels its older run. Runs on main are never +# cancelled: only main saves the rust-cache, so a cancelled main run would +# leave PRs restoring a stale cache. concurrency: group: ci-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: CARGO_TERM_COLOR: always jobs: + # The name repeats the id, so the required check stays `check`. check: + name: check runs-on: windows-latest + # checkout only. + permissions: + contents: read timeout-minutes: 60 steps: - - uses: actions/checkout@v5 + # Actions are pinned to full commit SHAs (tag in the trailing comment): + # a tag can be moved to other code, a commit cannot. Bump both together. + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false # The version and components pinned in rust-toolchain.toml. - - run: rustup toolchain install - - uses: Swatinem/rust-cache@v2 + # --no-self-update: rustup would otherwise replace itself with whatever + # release is newest that day, unpinned and mid-job. + - run: rustup toolchain install --no-self-update + # Save the cache only from main: PR runs restore it but do not write + # their own entries, which would evict main's from the 10 GB quota. + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} - name: Clippy run: cargo clippy --workspace --all-targets --locked -- -D warnings - name: Clippy, diagnostics build diff --git a/.github/workflows/linux-subset.yml b/.github/workflows/linux-subset.yml new file mode 100644 index 00000000..a7b72339 --- /dev/null +++ b/.github/workflows/linux-subset.yml @@ -0,0 +1,1150 @@ +# Interim Linux CI for the crates that already build without Windows. +# Superseded once full-workspace Linux CI lands; fold or delete then. +# +# Every step here passes on plain Linux with no Windows SDK, no cross target +# and no game data. The PR that added this lists the same commands for local use. +name: linux-subset + +on: + push: + branches: [main] + pull_request: + +# No token permissions by default; each job grants only what it uses, so a +# job added later starts with none instead of inheriting these. +permissions: {} + +# The implicit default shell is plain `bash -e`, where a failing command on +# the left of a pipe (e.g. the `echo ... | sha256sum -c -` checksum checks) +# is ignored. Set it once so every `run:` script gets pipefail, plus nounset: +# a misspelt or missing variable (say a renamed *_CRATES list) is an error +# instead of expanding to nothing, which would e.g. run `cargo clippy` with +# no -p flags on whatever the default members are. inherit_errexit makes +# `set -e` apply inside command substitutions too, which Bash otherwise +# resets there: a failing command in `x="$(a; b)"` stops the step instead +# of letting `b` run on. +defaults: + run: + shell: bash --noprofile --norc -O inherit_errexit -euo pipefail {0} + +# Actions are pinned to full commit SHAs (tag in the trailing comment): a tag +# can be moved to other code, a commit cannot. Bump both together. + +# A newer push to a PR cancels its older run. Runs on main are never +# cancelled: only main saves the rust-cache, so a cancelled main run would +# leave PRs restoring a stale cache. +concurrency: + group: linux-subset-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + # A failing test or build script prints where it panicked. + RUST_BACKTRACE: 1 + # Folded package lists are read into Bash arrays of Cargo arguments. + # Crates (plus xtask) that build, test and are clippy-clean on Linux today. + LINUX_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p xtask + # Crates that are clippy-clean for the Windows target today: every + # workspace member but xtask, which is host-only. + WINDOWS_CLIPPY_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p victory-gpu + -p victory-hle -p victory + # Packages that are rustfmt-clean today. The rest (victory-formats, + # victory-loader, victory-gpu, victory-hle) are not yet; add each one + # once it is, and switch to `cargo fmt --all --check` when all are. + RUSTFMT_CRATES: >- + -p victory-core -p victory-pe -p victory-pipeline -p victory-game + -p xtask + # Crates whose rustdoc builds with no warnings on Linux (broken or private + # intra-doc links, bad code-block attributes, ...): LINUX_CRATES plus + # victory-gpu, whose docs build on Linux although its code does not. + RUSTDOC_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p victory-gpu + -p xtask + # Crates whose rustdoc builds with no warnings for the Windows target, where + # cfg(windows) items (all of victory-hle, apps/victory's host) exist and the + # Linux rustdoc step never sees them. Every workspace member but the + # host-only xtask, like WINDOWS_CLIPPY_CRATES. + WINDOWS_RUSTDOC_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p victory-gpu + -p victory-hle -p victory + +jobs: + # Each job's name repeats its id, so the check names that branch protection + # requires stay `linux` and `windows-target-check`; zizmor's auditor + # persona (below) flags unnamed jobs. + # Both jobs pin the runner image's Ubuntu release rather than + # `ubuntu-latest`, like the action and tool pins: the alias moves to a new + # release (new preinstalled rustup, curl, tar, coreutils, ...) under us, so + # a passing PR could fail on main with no change. Bump it deliberately. + linux: + name: linux + runs-on: ubuntu-24.04 + # checkout, plus zizmor's online audits (impostor commits, advisories). + permissions: + contents: read + timeout-minutes: 30 + steps: + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + # Every step here, and the rust-cache key, trusts rust-toolchain.toml to + # name one exact release. A channel of `stable` (or `beta`, `nightly`, + # a bare `1.98`) still installs and passes, but floats to whatever is + # newest that day: new lints fail a PR that changed nothing, and main + # and a PR build with different compilers. A `path` toolchain is a + # local directory the runner does not have, and a legacy + # `rust-toolchain` file next to it would take precedence over the + # .toml in rustup. The pin must also be no older than the workspace's + # rust-version, or the msrv job checks with a compiler newer than the + # one every other step uses. Read with the runner's Python 3 tomllib + # (-I: no site packages, no cwd on sys.path) before rustup reads it. + - name: Toolchain pin is one exact release + run: | + python3 -I - <<'EOF' + import os, re, sys, tomllib + + def load(path): + with open(path, "rb") as f: + return tomllib.load(f) + + failed = False + if os.path.lexists("rust-toolchain"): + print("::error file=rust-toolchain::legacy toolchain file overrides rust-toolchain.toml", file=sys.stderr) + failed = True + toolchain = load("rust-toolchain.toml").get("toolchain", {}) + channel = toolchain.get("channel") + pin = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", channel) if isinstance(channel, str) else None + if pin is None: + print(f"::error file=rust-toolchain.toml::channel {channel!r} is not an exact release (MAJOR.MINOR.PATCH)", file=sys.stderr) + failed = True + if "path" in toolchain: + print("::error file=rust-toolchain.toml::toolchain names a local path", file=sys.stderr) + failed = True + msrv = load("Cargo.toml").get("workspace", {}).get("package", {}).get("rust-version", "") + floor = re.fullmatch(r"(\d+)\.(\d+)(?:\.(\d+))?", msrv) if isinstance(msrv, str) else None + if floor is None: + print(f"::error file=Cargo.toml::unexpected workspace rust-version {msrv!r}", file=sys.stderr) + failed = True + elif pin is not None: + have = tuple(int(g) for g in pin.groups()) + need = tuple(int(g or 0) for g in floor.groups()) + if have < need: + print(f"::error file=rust-toolchain.toml::channel {channel} is older than the workspace rust-version {msrv}", file=sys.stderr) + failed = True + if failed: + sys.exit(1) + print(f"Pinned toolchain {channel}, rust-version {msrv}") + EOF + + # rustup is preinstalled; this installs the toolchain pinned in + # rust-toolchain.toml (with clippy and rustfmt). --no-self-update keeps + # the runner image's rustup as is: otherwise rustup replaces itself + # with whatever release is newest that day, unpinned and mid-job. + - name: Install pinned toolchain + run: rustup toolchain install --no-self-update + + # Save the cache only from main: PR runs restore it but do not write + # their own entries, which would evict main's from the 10 GB quota. + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} + + # Spelled out rather than the `cargo xtask` alias (`run --package xtask + # --`), which has no room for --locked: this is the job's first cargo + # command, and without it a Cargo.lock out of date with the manifests + # would be rewritten here, so every later `--locked` step would check + # against the rewritten file and pass. + - name: Asset policy + run: cargo run --locked --quiet --package xtask -- policy + + # The crate lists above are written out by hand, so a workspace member + # added later would silently get no clippy or rustdoc at all. Fail + # instead: every member but the host-only xtask must be in both Windows + # lists (which say they hold every member but xtask), and xtask, which + # nothing else lints, must be in LINUX_CRATES. Every LINUX_CRATES crate + # must also be in RUSTDOC_CRATES (which says it holds them all), so one + # moved onto Linux CI gets its rustdoc lints too. Lists may still name + # fewer crates on purpose (LINUX_CRATES, RUSTFMT_CRATES, ...). + - name: Crate lists cover the workspace + run: | + metadata="$(cargo metadata --locked --no-deps --format-version 1)" + names="$(jq -r '.packages[].name' <<< "${metadata}")" + mapfile -t members <<< "${names}" + if [[ "${#members[@]}" -lt 2 ]]; then + echo "::error::cargo metadata listed no workspace members" >&2 + exit 1 + fi + declare -A linux=() clippy=() rustdoc=() linux_rustdoc=() + read -r -a args <<< "${LINUX_CRATES}" + for a in "${args[@]}"; do linux["${a}"]=1; done + read -r -a args <<< "${RUSTDOC_CRATES}" + for a in "${args[@]}"; do linux_rustdoc["${a}"]=1; done + read -r -a args <<< "${WINDOWS_CLIPPY_CRATES}" + for a in "${args[@]}"; do clippy["${a}"]=1; done + read -r -a args <<< "${WINDOWS_RUSTDOC_CRATES}" + for a in "${args[@]}"; do rustdoc["${a}"]=1; done + missing=0 + read -r -a args <<< "${LINUX_CRATES}" + for c in "${args[@]}"; do + if [[ "${c}" != -p && ! -v linux_rustdoc["${c}"] ]]; then + echo "::error::LINUX_CRATES member ${c} is not in RUSTDOC_CRATES" >&2 + missing=1 + fi + done + for m in "${members[@]}"; do + if [[ "${m}" == xtask ]]; then + if [[ ! -v linux["${m}"] ]]; then + echo "::error::xtask is not in LINUX_CRATES" >&2 + missing=1 + fi + continue + fi + if [[ ! -v clippy["${m}"] ]]; then + echo "::error::workspace member ${m} is not in WINDOWS_CLIPPY_CRATES" >&2 + missing=1 + fi + if [[ ! -v rustdoc["${m}"] ]]; then + echo "::error::workspace member ${m} is not in WINDOWS_RUSTDOC_CRATES" >&2 + missing=1 + fi + done + if [[ "${missing}" -ne 0 ]]; then + exit 1 + fi + printf 'Covered: %s\n' "${members[@]}" + + # The clippy and rustdoc steps lint with whatever `[lints]` each crate + # declares, so a member added (or edited) without `[lints] workspace = + # true` silently drops `undocumented_unsafe_blocks`, + # `unsafe_op_in_unsafe_fn = deny`, ... and still passes. The hle-probe + # fixture is outside the workspace and repeats those lints by hand + # ("keep the two in step"); fail when the copies drift apart. cargo + # metadata does not report lints, so the manifests are read with the + # runner's Python 3 tomllib (-I: no site packages, no cwd on sys.path). + # The same goes for the [workspace.package] fields every member + # inherits today: a member that spells out its own `edition` (or + # `license`, `publish`) instead of `.workspace = true` drifts unseen + # when the root one is bumped, so each must be inherited, and the + # fixture's hand-written copies must match the root's. + - name: Workspace lints and package fields apply everywhere + run: | + metadata="$(cargo metadata --locked --no-deps --format-version 1)" + manifests="$(jq -r '.packages[].manifest_path' <<< "${metadata}")" + mapfile -t manifest_list <<< "${manifests}" + python3 -I - Cargo.toml tests/fixtures/hle-probe/Cargo.toml "${manifest_list[@]}" <<'EOF' + import sys, tomllib + + def load(path): + with open(path, "rb") as f: + return tomllib.load(f) + + root, fixture, *members = sys.argv[1:] + want = load(root).get("workspace", {}).get("lints") + inherited = ("edition", "license", "publish") + root_package = load(root).get("workspace", {}).get("package", {}) + failed = False + for key in inherited: + if key not in root_package: + print(f"::error::root Cargo.toml has no [workspace.package] {key}", file=sys.stderr) + failed = True + if not want: + print("::error::root Cargo.toml has no [workspace.lints]", file=sys.stderr) + failed = True + if len(members) < 2: + print("::error::cargo metadata listed no workspace members", file=sys.stderr) + failed = True + for m in members: + manifest = load(m) + if manifest.get("lints") != {"workspace": True}: + print(f"::error file={m}::[lints] must be exactly `workspace = true`", file=sys.stderr) + failed = True + package = manifest.get("package", {}) + for key in inherited: + if package.get(key) != {"workspace": True}: + print(f"::error file={m}::[package] {key} must be `{key}.workspace = true`", file=sys.stderr) + failed = True + fixture_manifest = load(fixture) + if fixture_manifest.get("lints") != want: + print(f"::error file={fixture}::[lints] differs from the root [workspace.lints]", file=sys.stderr) + failed = True + fixture_package = fixture_manifest.get("package", {}) + for key in inherited: + if fixture_package.get(key) != root_package.get(key): + print(f"::error file={fixture}::[package] {key} differs from the root [workspace.package] {key}", file=sys.stderr) + failed = True + if failed: + sys.exit(1) + print(f"Workspace lints and {', '.join(inherited)} on {len(members)} members and the hle-probe fixture") + EOF + + # Every dependency today is a checksummed crates.io release. A git + # dependency (or a `[patch]` pointing at one), a path dependency outside + # the repository, or a crate from another registry or a source + # replacement would build and pass every step here, while pulling code + # that is neither checksummed nor reviewable from Cargo.lock, so fail on + # one instead. Both lockfiles are read with tomllib, without the + # network: each package must either have no source and be a workspace + # member (the fixture's lock: the fixture itself), or come from the + # crates.io index with a checksum. The root manifest and the cargo + # config must not redirect sources with [patch], [replace], [source] + # or [registries]. + - name: Dependencies come only from crates.io + run: | + metadata="$(cargo metadata --locked --no-deps --format-version 1)" + names="$(jq -r '.packages[].name' <<< "${metadata}")" + mapfile -t members <<< "${names}" + python3 -I - "${members[@]}" <<'EOF' + import sys, tomllib + + def load(path): + with open(path, "rb") as f: + return tomllib.load(f) + + crates_io = { + "registry+https://github.com/rust-lang/crates.io-index", + "sparse+https://index.crates.io/", + } + members = set(sys.argv[1:]) + failed = False + if len(members) < 2: + print("::error::cargo metadata listed no workspace members", file=sys.stderr) + failed = True + fixture = "tests/fixtures/hle-probe" + fixture_name = load(f"{fixture}/Cargo.toml")["package"]["name"] + counted = 0 + for lock, local in (("Cargo.lock", members), (f"{fixture}/Cargo.lock", {fixture_name})): + packages = load(lock).get("package", []) + if not packages: + print(f"::error file={lock}::no [[package]] entries", file=sys.stderr) + failed = True + for p in packages: + counted += 1 + name, source = p["name"], p.get("source") + if source is None: + if name not in local: + print(f"::error file={lock}::{name} has no source but is not a workspace member (path dependency outside the workspace?)", file=sys.stderr) + failed = True + elif source not in crates_io: + print(f"::error file={lock}::{name} comes from {source}, not crates.io", file=sys.stderr) + failed = True + elif not p.get("checksum"): + print(f"::error file={lock}::{name} from crates.io has no checksum", file=sys.stderr) + failed = True + for path, keys in ( + ("Cargo.toml", ("patch", "replace")), + (f"{fixture}/Cargo.toml", ("patch", "replace")), + (".cargo/config.toml", ("patch", "source", "registries")), + ): + found = [k for k in keys if k in load(path)] + if found: + print(f"::error file={path}::redirects dependency sources with [{'], ['.join(found)}]", file=sys.stderr) + failed = True + if failed: + sys.exit(1) + print(f"{counted} locked packages: workspace members or checksummed crates.io releases") + EOF + + # .gitattributes stores every text file with LF (`text=auto eol=lf`; + # *.cmd and *.ps1 get CRLF only in the working tree). That applies only + # when git normalises the file at `git add`: a file committed with + # core.autocrlf=false from a Windows editor, or one added before the + # attribute, keeps its CRLFs in the index, and every Linux checkout + # then shows it modified. Fail on any tracked file whose stored copy + # has CRLF or mixed endings (`git ls-files --eol`, index column). + # Merge-conflict markers left in a resolved file do not always break + # the build (a comment, a doc, a workflow, a fixture), so fail on those + # too: `<<<<<<< `, `||||||| ` or `>>>>>>> ` opening a line in any + # tracked text file. A bare `=======` is left alone; it is also a + # Markdown heading underline. + # Trailing spaces or tabs, and a last line with no newline, are clean + # everywhere on main too, but only the rustfmt-clean packages are + # checked by rustfmt; the rest (workflows, TOML, docs, the crates + # rustfmt skips) pick up whitespace-only diff noise unseen. Both are + # read from the index (`git grep --cached`, the `--eol` list), so a + # CRLF working-tree copy (*.cmd, *.ps1) cannot trip or hide either. + # A UTF-8 byte-order mark (U+FEFF, which Notepad and some Visual Studio + # setups write) is invisible in an editor and in a diff, but it is not + # whitespace to the check above: at the top of a file it hides a + # script's `#!` line (the kernel, the file-mode step below and the + # ShellCheck list all look for `#!` at byte 0) and shows as a mystery + # first-line change in review. Mid-file it is a stray zero-width + # character. Fail on it anywhere in a tracked text file; Rust source + # that needs the character can spell it `\u{feff}`. + - name: LF line endings, no conflict markers, no stray whitespace or BOMs + run: | + list="${RUNNER_TEMP}/eol" + git ls-files -z --eol > "${list}" + bad=() + no_final_newline=() + while IFS= read -r -d '' entry; do + index_eol="${entry%% *}" + path="${entry#*$'\t'}" + if [[ "${index_eol}" == i/crlf || "${index_eol}" == i/mixed ]]; then + bad+=("${path}") + fi + # i/-text is binary; an empty file has nothing to end. + if [[ "${index_eol}" != i/-text ]]; then + last="$(git cat-file blob ":${path}" | tail -c 1)" + if [[ -n "${last}" ]]; then + no_final_newline+=("${path}") + fi + fi + done < "${list}" + if [[ "${#bad[@]}" -ne 0 ]]; then + echo "::error::tracked files stored with CRLF line endings (re-add them with git add --renormalize)" >&2 + printf '%s\n' "${bad[@]}" >&2 + exit 1 + fi + if [[ "${#no_final_newline[@]}" -ne 0 ]]; then + echo "::error::tracked text files whose last line has no newline" >&2 + printf '%s\n' "${no_final_newline[@]}" >&2 + exit 1 + fi + # git grep exits 1 when nothing matches; any other failure stops. + trailing="$(git grep --cached -nIE -e '[[:blank:]]+$')" || [[ $? -eq 1 ]] + if [[ -n "${trailing}" ]]; then + echo "::error::trailing spaces or tabs in tracked files" >&2 + printf '%s\n' "${trailing}" >&2 + exit 1 + fi + # git grep exits 1 when nothing matches; any other failure stops. + bom="$(git grep --cached -nIF -e $'\xEF\xBB\xBF')" || [[ $? -eq 1 ]] + if [[ -n "${bom}" ]]; then + echo "::error::UTF-8 byte-order marks (U+FEFF) in tracked text files" >&2 + printf '%s\n' "${bom}" >&2 + exit 1 + fi + # git grep exits 1 when nothing matches; any other failure stops. + markers="$(git grep -nIE -e '^(<{7}|[|]{7}|>{7})( |$)')" || [[ $? -eq 1 ]] + if [[ -n "${markers}" ]]; then + echo "::error::merge-conflict markers in tracked files" >&2 + printf '%s\n' "${markers}" >&2 + exit 1 + fi + + # Git records two file modes that a Linux checkout honours and a Windows + # one does not. A symlink (mode 120000) is checked out on Windows, where + # core.symlinks is off by default, as a plain text file holding the + # target path, so the two platforms build different trees; nothing here + # needs one, so fail on any. An executable bit (100755) on a file that + # is not a script is usually an accident from a Linux, WSL or mounted- + # NTFS editor and shows as mode noise in every diff; fail on executable + # files that do not start with `#!`. Read from the index (`git ls-files + # -s`), not the checkout, so the runner's umask cannot hide either. + - name: Portable file modes + run: | + list="${RUNNER_TEMP}/modes" + git ls-files -z -s > "${list}" + links=() + stray_exec=() + while IFS= read -r -d '' entry; do + mode="${entry%% *}" + path="${entry#*$'\t'}" + case "${mode}" in + 120000) links+=("${path}") ;; + 100755) + magic="$(head -c 2 -- "${path}")" + if [[ "${magic}" != '#!' ]]; then + stray_exec+=("${path}") + fi + ;; + *) ;; + esac + done < "${list}" + failed=0 + if [[ "${#links[@]}" -ne 0 ]]; then + echo "::error::tracked symlinks (Windows checkouts get a text file instead)" >&2 + printf '%s\n' "${links[@]}" >&2 + failed=1 + fi + if [[ "${#stray_exec[@]}" -ne 0 ]]; then + echo "::error::executable files without a #! line (git update-index --chmod=-x)" >&2 + printf '%s\n' "${stray_exec[@]}" >&2 + failed=1 + fi + if [[ "${failed}" -ne 0 ]]; then + exit 1 + fi + + # Path names that a Linux checkout accepts and a Windows one cannot + # hold. NTFS is case-insensitive, so two tracked paths that differ only + # in case (`Foo.rs`, `foo.rs`) collapse into one file there and the + # checkout shows a permanent spurious change. Windows also refuses a + # path component that holds `< > : " | ? *`, a backslash or a control + # character, that ends in a dot or a space, or whose name before the + # first dot is a reserved device (CON, PRN, AUX, NUL, COM0-9, LPT0-9, + # any case): `git checkout` there fails outright. Read from the index, + # NUL-delimited, so no name can split; the comparison runs under the + # C locale so it folds ASCII case only, as the check is meant to. + - name: Portable file names + env: + LC_ALL: C + run: | + list="${RUNNER_TEMP}/names" + git ls-files -z > "${list}" + bad=() + declare -A seen=() + collide=() + reserved='^(con|prn|aux|nul|com[0-9]|lpt[0-9])$' + while IFS= read -r -d '' path; do + # Walk every prefix (each directory, then the file), so `Src/a` + # and `src/b` collide too, not only whole paths. + prefix="" + rest="${path}" + flagged=0 + while [[ -n "${rest}" ]]; do + part="${rest%%/*}" + if [[ "${rest}" == */* ]]; then + rest="${rest#*/}" + else + rest="" + fi + prefix="${prefix:+${prefix}/}${part}" + lower="${prefix,,}" + if [[ -z "${seen[${lower}]+set}" ]]; then + seen["${lower}"]="${prefix}" + elif [[ "${seen[${lower}]}" != "${prefix}" ]]; then + collide+=("${seen[${lower}]} <-> ${prefix}") + fi + stem="${part%%.*}" + if [[ "${flagged}" -eq 0 ]] \ + && { [[ "${part}" =~ [\<\>:\"\|?*\\[:cntrl:]] ]] \ + || [[ "${part}" == *. || "${part}" == *' ' ]] \ + || [[ "${stem,,}" =~ ${reserved} ]]; }; then + bad+=("${path}") + flagged=1 + fi + done + done < "${list}" + failed=0 + if [[ "${#collide[@]}" -ne 0 ]]; then + echo "::error::tracked paths that differ only in case (one file on Windows)" >&2 + printf '%s\n' "${collide[@]}" | sort -u >&2 + failed=1 + fi + if [[ "${#bad[@]}" -ne 0 ]]; then + echo "::error::tracked paths Windows cannot check out (reserved name, character, or trailing dot or space)" >&2 + printf '%s\n' "${bad[@]}" >&2 + failed=1 + fi + if [[ "${failed}" -ne 0 ]]; then + exit 1 + fi + # Lints all workflows: expression and context typos, unknown keys, and + # (via ShellCheck) the `run:` scripts, which YAML parsing alone never + # checks. actionlint silently skips the shell checks when shellcheck is + # not on PATH, and the runner image's shellcheck changes version under + # us, so a pinned ShellCheck release is downloaded and passed explicitly + # instead: the same checks run on every runner image, and a missing + # binary fails the step rather than skipping the checks. Both releases + # are pinned and their checksums verified, like the actions above. + # Every download (here and in zizmor below) is HTTPS-only, redirects + # included (--proto =https), with TLS 1.2 or newer. Each attempt is + # capped (--connect-timeout, --max-time): a stalled release download + # fails and is retried within minutes instead of holding the job until + # its 30-minute timeout. + # pyflakes is off: no step runs Python. + # SHELLCHECK_OPTS turns on ShellCheck's optional checks (masked return + # codes, `set -e` suppressed in functions, unassigned uppercase vars, + # `[[ ]]` over `[ ]`, `${var}` over `$var`, useless `cat`, ...) for the + # `run:` scripts. Every optional check of the pinned release is listed + # and passes (`shellcheck --list-optional`); they are named rather than + # `--enable=all` so bumping ShellCheck cannot add one unseen. + # --norc: a `.shellcheckrc` (committed, or added by a PR) cannot + # quietly disable checks or drop these optional ones; disabling a check + # takes an inline `# shellcheck disable=` next to the code, in review. + # -config-file /dev/null does the same for actionlint's own config: a + # `.github/actionlint.yaml` (or .yml) can `ignore:` any error by regex, + # which actionlint otherwise picks up silently. + # actionlint only sees `run:` scripts, so the same ShellCheck (same + # SHELLCHECK_OPTS, which ShellCheck reads itself) then lints the + # standalone scripts too: the git hooks, any tracked *.sh / *.bash, and + # any tracked text file whose first line is a sh/bash/dash/ksh shebang + # (a script with no extension, e.g. under scripts/). The list comes + # from git, so a script added later is checked without editing this + # step; the step fails if the list is empty, rather than passing while + # checking nothing. File names are NUL-delimited end to end, so no name + # (spaces, newlines, a leading `-`) can split, glob or become a flag. + - name: actionlint + ShellCheck + env: + SHELLCHECK_OPTS: >- + --norc + --enable=add-default-case,avoid-negated-conditions,avoid-nullary-conditions,check-extra-masked-returns,check-set-e-suppressed,check-unassigned-uppercase,deprecate-which,quote-safe-variables,require-double-brackets,require-variable-braces,useless-use-of-cat + SHELLCHECK_VERSION: 0.11.0 + SHELLCHECK_SHA256: 8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198 + ACTIONLINT_VERSION: 1.7.12 + ACTIONLINT_SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 + run: | + cd "${RUNNER_TEMP}" + sc_tarball="shellcheck-v${SHELLCHECK_VERSION}.linux.x86_64.tar.xz" + curl -sSfL --proto =https --tlsv1.2 --retry 3 --connect-timeout 20 --max-time 300 -O "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/${sc_tarball}" + echo "${SHELLCHECK_SHA256} ${sc_tarball}" | sha256sum -c - + tar xJf "${sc_tarball}" --strip-components=1 "shellcheck-v${SHELLCHECK_VERSION}/shellcheck" + shellcheck_bin="${RUNNER_TEMP}/shellcheck" + "${shellcheck_bin}" --version + tarball="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + curl -sSfL --proto =https --tlsv1.2 --retry 3 --connect-timeout 20 --max-time 300 -O "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/${tarball}" + echo "${ACTIONLINT_SHA256} ${tarball}" | sha256sum -c - + tar xzf "${tarball}" actionlint + cd "${GITHUB_WORKSPACE}" + "${RUNNER_TEMP}/actionlint" -color -config-file /dev/null -shellcheck="${shellcheck_bin}" -pyflakes= + list="${RUNNER_TEMP}/shell-scripts" + git ls-files -z -- '.githooks/*' '*.sh' '*.bash' > "${list}" + # git grep exits 1 when nothing matches; any other failure stops. + git grep -lzI -e '^#!' > "${list}.candidates" || [[ $? -eq 1 ]] + shebang_re='^#![[:space:]]*(/usr)?/bin/(env[[:space:]]+)?(ba|da|k)?sh([[:space:]]|$)' + while IFS= read -r -d '' f; do + first_line="$(head -n 1 -- "${f}")" + if [[ "${first_line}" =~ ${shebang_re} ]]; then + printf '%s\0' "${f}" >> "${list}" + fi + done < "${list}.candidates" + sort -zu -o "${list}" -- "${list}" + mapfile -d '' -t script_list < "${list}" + if [[ "${#script_list[@]}" -eq 0 ]]; then + echo "::error::no shell scripts found to check" >&2 + exit 1 + fi + printf 'ShellCheck: %s\n' "${script_list[@]}" + "${shellcheck_bin}" -- "${script_list[@]}" + + # Security audit of the workflows, which actionlint does not do: + # template injection in `run:` scripts, credentials persisted by + # checkout, over-broad permissions, cache poisoning, unpinned actions. + # With the job's read-only token it also checks online that each pinned + # SHA really is a commit of the action's repository (impostor commits) + # and that no pinned version has a known advisory. Pinned and + # checksum-verified like actionlint; exits non-zero on any finding. + # The auditor persona runs every audit at every confidence: the + # code-quality ones the default persona hides (unnamed jobs, ...) and + # the low-confidence ones pedantic still drops. Every one passes today. + # --strict-collection fails on a workflow zizmor cannot parse, which it + # otherwise only warns about and skips, auditing nothing in it. + # --no-config: a `zizmor.yml` or `.github/zizmor.yml` (committed, or + # added by a PR) cannot disable audits or loosen the pin policy unseen; + # silencing a finding takes an inline `# zizmor: ignore[...]`, in review. + - name: zizmor + env: + ZIZMOR_VERSION: 1.32.0 + ZIZMOR_SHA256: bb110cc765eca9cd7efb2e284a956be5974c60027b0970f16397d86208a9957b + GH_TOKEN: ${{ github.token }} + run: | + tarball="zizmor-x86_64-unknown-linux-gnu.tar.gz" + cd "${RUNNER_TEMP}" + curl -sSfL --proto =https --tlsv1.2 --retry 3 --connect-timeout 20 --max-time 300 -O "https://github.com/zizmorcore/zizmor/releases/download/v${ZIZMOR_VERSION}/${tarball}" + echo "${ZIZMOR_SHA256} ${tarball}" | sha256sum -c - + tar xzf "${tarball}" zizmor + cd "${GITHUB_WORKSPACE}" + "${RUNNER_TEMP}/zizmor" --color=always --persona=auditor --strict-collection --no-config .github/workflows + + # Fast, needs no build: keep the clean packages clean. load_probe.rs is + # checked by itself, since the rest of victory-loader is not clean yet. + - name: rustfmt (clean packages) + run: | + read -r -a crates <<< "${RUSTFMT_CRATES}" + cargo fmt --check "${crates[@]}" + rustfmt --check --edition 2024 crates/victory-loader/tests/load_probe.rs + + - name: clippy (all targets) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + cargo clippy --all-targets --locked "${crates[@]}" -- -D warnings + + # The steps above build default features only, so code behind the + # `diagnostics` (and victory-shader's `host`) features is never compiled. + # Lint it too. Both builds stay: some code is cfg(not(feature = ...)). + - name: clippy (all features) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + cargo clippy --all-targets --all-features --locked "${crates[@]}" -- -D warnings + + # Every step builds its crates together, so Cargo unifies their + # features: a crate that uses a dependency's feature (one of serde's, + # object's, windows-sys's, ...) without enabling it in its own + # Cargo.toml still builds, because a sibling enables it, and breaks only + # when built alone (`cargo test -p` it, or a downstream user). Check + # each crate by itself, with default features and with all of its own. + # Lints stay with clippy above; this only fails on build errors. + - name: cargo check (each crate on its own) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + for ((i = 1; i < ${#crates[@]}; i += 2)); do + cargo check --locked --quiet --all-targets -p "${crates[i]}" + cargo check --locked --quiet --all-targets --all-features -p "${crates[i]}" + done + + # Doc tests run under `cargo test` below, but rustdoc's own lints (a + # renamed item leaving a dangling [`link`], a public doc linking to a + # private item) only fire when the docs are built. Private items are + # documented too, so their doc comments (most of the code's) are linted + # as well; a public doc linking to a private item still fails. The + # second run turns every feature on, so the doc comments on `diagnostics` + # (and victory-shader's `host`) code are linted too. + - name: rustdoc (clean crates) + env: + RUSTDOCFLAGS: -D warnings + run: | + read -r -a crates <<< "${RUSTDOC_CRATES}" + cargo doc --no-deps --locked --document-private-items "${crates[@]}" + cargo doc --no-deps --locked --document-private-items --all-features "${crates[@]}" + + # The skipped tests parse the test executable itself as a PE image, which + # is an ELF on Linux. They still run on Windows. Once the workspace's + # Linux gates land they are cfg(windows) and these --skip flags are no-ops. + # --no-fail-fast: report failures from every test binary, not the first. + # The second run turns every feature on, like the clippy and rustdoc + # steps: `diagnostics` changes what some code does (victory-core's log + # cap, victory-shader's loop limit read from the environment), so the + # tests must pass with it too, not only compile. + # Two more runs build the tests the way the game itself is built: the + # release profile (what ships), and the diag profile with every feature + # (the development build, `--profile diag --features diagnostics`). Both + # optimise and drop debug assertions and overflow checks, which the dev + # profile above keeps: an invariant held only by a debug_assert (the + # shader IR and bitcode writer have several), arithmetic that panics in + # debug but wraps in release, or unsafe code (the loader's, the PE + # parser's) whose undefined behaviour only shows once the optimiser + # relies on it would otherwise pass here and misbehave only in a real + # build. Each adds one optimised build of the crates, well under the + # job's timeout. + # The release run also uses --test-threads 1: the runner compiles with as + # many cores as cargo wants, but each test binary then runs one test at + # a time, so a test that races on a shared static, a temp file under + # TMPDIR, or an OS-global resource can still pass under the default + # parallel harness on a fast machine and fail under Wine or in a + # debugger, where timing differs. One ordered pass is enough; the other + # three runs keep the default threading so nothing only fails in release. + # All four runs get a fresh, empty TMPDIR (std::env::temp_dir() reads it), so + # a test that leaves scratch files behind fails here: the checkout check + # below never sees the temp dir, and on a contributor's machine the + # leftovers pile up in /tmp with every run. rustc and the linker clean + # up their own temp files there, so the directory must end up empty. + # HOME is a fresh, empty directory too, with the XDG base directories + # unset: victory-core's config falls back to $XDG_CACHE_HOME or + # ~/.cache for its cache and data, so a test that resolves the default + # config instead of passing its own paths would read a contributor's + # real cache (game data included) and write into it, passing there and + # nowhere else. Anything a test leaves in that HOME fails the step as + # well. rustup and cargo keep their own homes: both are pinned to where + # they were before HOME moves, so the toolchain and the registry cache + # are the ones the steps above used. + # Both directories sit under one whose name has a space and a non-ASCII + # letter, as a contributor's may ("/home/zoë/My Files"). The runner's + # own paths are plain ASCII with no spaces, so a test that splits a + # temp path on whitespace, passes it unquoted through a shell, or + # assumes it is ASCII would otherwise pass here and fail for them. + # All four also have no network: they run in a new network namespace + # (unshare, as the runner user, so permission checks still apply) that + # holds only a downed loopback, with CARGO_NET_OFFLINE set. A test or + # build script that downloads something (a fixture, a reference file) + # passes here only by luck of the network and fails for anyone offline + # or behind a proxy; this makes it fail every time instead. The steps + # above already fetched every dependency, all features included, into + # CARGO_HOME. Ubuntu 24.04 lets unprivileged users create user + # namespaces only after an AppArmor sysctl is lifted, so lift it first + # (on this throwaway runner) and fail loudly if unshare still cannot. + # All four also start from an empty environment (env -i) that keeps + # only what Cargo, rustup and the linker need, plus the settings above. + # The runner exports dozens of variables a contributor's shell never + # has (CI, GITHUB_*, RUNNER_*, ImageOS, a UTF-8 LANG), and a + # contributor's shell has ones the runner never does (VICTORY_LOG, + # RUST_LOG, VICTORY_CONFIG, LOCALAPPDATA, LC_ALL): a test that reads + # any of them, directly or through a default it resolves, passes in + # one place and fails in the other. With none of them set, a test sees + # the same environment here as under `env -i` locally. A kept variable + # that is unset becomes empty rather than going missing, which would + # change what Cargo and rustup do, so only set ones are passed on. + # LC_ALL=C is kept explicitly (the runner has a UTF-8 LANG, a contributor + # may have another): libc collation, character classes and strerror + # strings then match a POSIX locale everywhere. + # All four also run under umask 077, not the runner's 022, so every + # file and directory a test or build script makes is private to its + # owner, as on a contributor's machine set up that way (a hardened + # distro default, or a shared box). A test that has another process + # read back what it wrote as a different mode, compares the mode of a + # file it made against 0644 or 0755, or copies a file's permissions + # and expects group or world bits would otherwise pass here and fail + # there. The umask is inherited through unshare and env -i, and + # checked inside them, so the tests see exactly it. + # #[ignore] tests never run in the four runs above, nor anywhere else + # unless someone asks for them by name, so they rot unseen: a benchmark + # that unwraps an API it no longer matches still compiles and still + # "passes" by being skipped. The ones that need nothing from outside + # the repository (the synthetic benchmarks in IGNORED_HERMETIC) run + # here too, once, in the release profile they are written for; their + # timings are only printed, so a slow runner cannot fail them. The + # rest (IGNORED_EXTERNAL) read game data or reference files named by + # environment variables and cannot run here. Every ignored test in the + # Linux crates must be on exactly one of the two lists in all four + # build passes above (default, all-features, release, diag), so a + # cfg(feature) or profile-only benchmark cannot hide from the lists, a + # new one is either run or says why it cannot be, and a renamed or + # deleted one cannot leave a stale entry behind. + - name: cargo test + env: + IGNORED_HERMETIC: >- + bcpack::tests::bcpack_throughput + emit::bitcode::tests::bench_write + IGNORED_EXTERNAL: >- + bcpack::tests::reference_chunks + emit::lower::tests::a_missing_value_stays_missing_through_two_live_joins + xma::tests::matches_a_reference_decoder + xma::tests::walks_saved_streams + run: | + userns=/proc/sys/kernel/apparmor_restrict_unprivileged_userns + if [[ -e "${userns}" && "$(< "${userns}")" != 0 ]]; then + sudo sysctl -q -w kernel.apparmor_restrict_unprivileged_userns=0 + fi + umask 077 + export CARGO_NET_OFFLINE=true + export CARGO_HOME="${CARGO_HOME:-${HOME}/.cargo}" + export RUSTUP_HOME="${RUSTUP_HOME:-${HOME}/.rustup}" + scratch="${RUNNER_TEMP}/cargo test ä" + export HOME="${scratch}/home" + mkdir -p "${HOME}" + unset XDG_CACHE_HOME XDG_CONFIG_HOME XDG_DATA_HOME XDG_STATE_HOME + export TMPDIR="${scratch}/tmp" + mkdir "${TMPDIR}" + export LC_ALL=C + keep=() + for name in PATH HOME TMPDIR CARGO_HOME RUSTUP_HOME CARGO_NET_OFFLINE \ + CARGO_TERM_COLOR CARGO_INCREMENTAL RUST_BACKTRACE LC_ALL; do + if [[ -v "${name}" ]]; then + keep+=("${name}=${!name}") + fi + done + offline=(unshare --user --map-current-user --net -- env -i "${keep[@]}") + inner_uid="$("${offline[@]}" id -u)" + if [[ "${inner_uid}" != "${UID}" ]]; then + echo "::error::unshare did not keep the runner's user id" >&2 + exit 1 + fi + inner_umask="$("${offline[@]}" sh -c umask)" + if [[ "${inner_umask}" != 0077 ]]; then + echo "::error::the tests would run under umask ${inner_umask}, not 0077" >&2 + exit 1 + fi + # Fail if anything beyond the kept variables reaches the tests. + extra="$("${offline[@]}" env | cut -d= -f1 | grep -vxF -f <(printf '%s\n' "${keep[@]%%=*}") || true)" + if [[ -n "${extra}" ]]; then + echo "::error::the test environment is not empty beyond the kept variables" >&2 + printf '%s\n' "${extra}" >&2 + exit 1 + fi + read -r -a crates <<< "${LINUX_CRATES}" + skips=( + --skip image::tests::parses_own_test_binary + --skip image::tests::rva_to_file_offset_maps_entry_point + --skip image::tests::rva_to_file_offset_rejects_offsets_past_4_gib + --skip image::tests::rejects_iat_outside_image + --skip prepare::tests::patches_own_test_binary + --skip prepare::tests::keeps_iat_slots_when_import_size_excludes_the_terminator + --skip prepare::tests::file_name_is_stable_per_build + ) + "${offline[@]}" cargo test --locked --no-fail-fast "${crates[@]}" -- --exact "${skips[@]}" + "${offline[@]}" cargo test --locked --no-fail-fast --all-features "${crates[@]}" -- --exact "${skips[@]}" + "${offline[@]}" cargo test --locked --no-fail-fast --release "${crates[@]}" -- --exact --test-threads 1 "${skips[@]}" + "${offline[@]}" cargo test --locked --no-fail-fast --profile diag --all-features "${crates[@]}" -- --exact "${skips[@]}" + read -r -a hermetic <<< "${IGNORED_HERMETIC}" + read -r -a external <<< "${IGNORED_EXTERNAL}" + expected="${RUNNER_TEMP}/ignored-expected" + listed="${RUNNER_TEMP}/ignored-listed" + printf '%s\n' "${hermetic[@]}" "${external[@]}" | sort > "${expected}" + dups="$(uniq -d "${expected}")" + if [[ -n "${dups}" ]]; then + echo "::error::a test is listed twice in IGNORED_HERMETIC/IGNORED_EXTERNAL" >&2 + printf '%s\n' "${dups}" >&2 + exit 1 + fi + for build in default --all-features --release "--profile diag --all-features"; do + case "${build}" in + default) flags=() ;; + --all-features) read -r -a flags <<< "--all-features" ;; + --release) read -r -a flags <<< "--release" ;; + *) read -r -a flags <<< "${build}" ;; + esac + "${offline[@]}" cargo test --locked -q "${flags[@]}" "${crates[@]}" -- --list --ignored --format terse > "${listed}.raw" + sed -n 's/: test$//p' "${listed}.raw" | sort -u > "${listed}" + if ! diff "${listed}" "${expected}" > "${listed}.diff"; then + echo "::error::ignored tests (cargo test ${build}) differ from IGNORED_HERMETIC + IGNORED_EXTERNAL (< listed, > expected)" >&2 + cat "${listed}.diff" >&2 + exit 1 + fi + done + "${offline[@]}" cargo test --locked --no-fail-fast --release "${crates[@]}" -- --exact --ignored "${hermetic[@]}" + leftovers="$(find "${TMPDIR}" -mindepth 1 -maxdepth 2)" + if [[ -n "${leftovers}" ]]; then + echo "::error::cargo test left files in TMPDIR" >&2 + printf '%s\n' "${leftovers}" >&2 + exit 1 + fi + leftovers="$(find "${HOME}" -mindepth 1 -maxdepth 3)" + if [[ -n "${leftovers}" ]]; then + echo "::error::cargo test wrote into HOME" >&2 + printf '%s\n' "${leftovers}" >&2 + exit 1 + fi + + # Builds, build scripts and tests must leave the checkout as they found + # it: a test writing scratch files into the source tree (instead of a + # temp dir), a build script regenerating a tracked file, or rustfmt or + # xtask rewriting something would otherwise pass here and dirty every + # contributor's tree. Untracked files count too, and so do ignored ones + # (a test's scratch.bin), except the build output in target/ and a + # fixture's target/. --locked already covers Cargo.lock. + - name: Checkout unchanged by the steps above + run: | + changes="$(git status --porcelain=v1 --untracked-files=all)" + if [[ -n "${changes}" ]]; then + echo "::error::the steps above modified or created files in the checkout" >&2 + printf '%s\n' "${changes}" >&2 + git diff --stat >&2 + exit 1 + fi + # .gitignore hides *.bin, *.dll, *.dat, ... from `git status`, so a + # scratch file of those kinds would pass the check above. List the + # ignored files too (whole ignored directories collapse to one + # entry) and allow only the build output directories. + list="${RUNNER_TEMP}/ignored-files" + git ls-files -z --others --ignored --exclude-standard --directory > "${list}" + mapfile -d '' -t ignored < "${list}" + stray=() + for f in "${ignored[@]}"; do + if [[ "${f}" != target/ && ! "${f}" =~ ^tests/fixtures/[^/]+/target/$ ]]; then + stray+=("${f}") + fi + done + if [[ "${#stray[@]}" -ne 0 ]]; then + echo "::error::the steps above created ignored files outside target/" >&2 + printf '%s\n' "${stray[@]}" >&2 + exit 1 + fi + + # Type-checks the Windows build from Linux: no MSVC, no linking, nothing runs. + # Catches compile errors in cfg(windows) code (most of victory-gpu, + # victory-hle and apps/victory, and the Windows-only tests) that the job + # above never compiles. + windows-target-check: + name: windows-target-check + runs-on: ubuntu-24.04 + # checkout only. + permissions: + contents: read + timeout-minutes: 30 + env: + # blake3's build script compiles C/assembly with MSVC tools for this + # target. Its build script reads this variable to select the pure-Rust + # implementation; nothing is linked here, so the choice has no effect. + CARGO_FEATURE_PURE: "1" + # rustc warnings (unused imports, dead code, ...) fail every step, + # including the workspace-wide `cargo check` ones. Set for the whole job + # so all steps share one build. + # Dependencies are unaffected: cargo caps their lints. + RUSTFLAGS: -D warnings + steps: + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + # rust-toolchain.toml already lists the x86_64-pc-windows-msvc target. + # --no-self-update: as in the linux job. + - name: Install pinned toolchain + run: rustup toolchain install --no-self-update + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: windows-target + save-if: ${{ github.ref == 'refs/heads/main' }} + + - name: cargo check (workspace, all targets) + run: cargo check --locked --workspace --all-targets --target x86_64-pc-windows-msvc + + - name: clippy (Windows target, clean crates) + run: | + read -r -a crates <<< "${WINDOWS_CLIPPY_CRATES}" + cargo clippy --locked --all-targets --target x86_64-pc-windows-msvc "${crates[@]}" -- -D warnings + + # Same as the step above with every feature on, so the + # `diagnostics` code (frame capture, the host debug layer, scripted keys, + # mostly cfg(windows)) is compiled and linted too. Both builds stay: some + # code is cfg(not(feature = "diagnostics")). + - name: cargo check + clippy (Windows target, all features) + run: | + read -r -a crates <<< "${WINDOWS_CLIPPY_CRATES}" + cargo check --locked --workspace --all-targets --all-features --target x86_64-pc-windows-msvc + cargo clippy --locked --all-targets --all-features --target x86_64-pc-windows-msvc "${crates[@]}" -- -D warnings + + # As the Linux job's per-crate step: the steps above unify features + # across the workspace, so a crate missing a feature it uses on a + # dependency (windows-sys's Win32_* features most of all) still builds. + # Check each one by itself. RUSTFLAGS above makes warnings fail too. + - name: cargo check (Windows target, each crate on its own) + run: | + read -r -a crates <<< "${WINDOWS_CLIPPY_CRATES}" + for ((i = 1; i < ${#crates[@]}; i += 2)); do + cargo check --locked --quiet --all-targets --target x86_64-pc-windows-msvc -p "${crates[i]}" + cargo check --locked --quiet --all-targets --all-features --target x86_64-pc-windows-msvc -p "${crates[i]}" + done + + # The hle-probe fixture is outside the workspace (load_probe builds it on + # demand on Windows), so the steps above never compile it. It is + # Windows-only and needs no linker to check. It cannot inherit the + # workspace lints, so its Cargo.toml repeats them (SAFETY comments etc.). + - name: clippy (hle-probe fixture, Windows target) + run: > + cargo clippy --locked --all-targets --target x86_64-pc-windows-msvc + --manifest-path tests/fixtures/hle-probe/Cargo.toml -- -D warnings + + # Same rustdoc lints as the Linux job (private items included), but for + # the Windows-only code it never compiles, plus the hle-probe fixture. + # Nothing is linked; RUSTFLAGS above is unchanged, so the dependency + # builds are shared with the steps above. The all-features run covers + # the docs on the `diagnostics` code, which is mostly cfg(windows). + - name: rustdoc (Windows target, clean crates) + env: + RUSTDOCFLAGS: -D warnings + run: | + read -r -a crates <<< "${WINDOWS_RUSTDOC_CRATES}" + cargo doc --no-deps --locked --document-private-items --target x86_64-pc-windows-msvc "${crates[@]}" + cargo doc --no-deps --locked --document-private-items --all-features --target x86_64-pc-windows-msvc "${crates[@]}" + cargo doc --no-deps --locked --document-private-items --target x86_64-pc-windows-msvc --manifest-path tests/fixtures/hle-probe/Cargo.toml + + # The fixture is outside the workspace, so `cargo fmt --all` never reaches + # it. It is rustfmt-clean today; keep it that way. (The workspace itself + # is not rustfmt-clean on main yet, so it is not checked here.) + - name: rustfmt (hle-probe fixture) + run: cargo fmt --check --manifest-path tests/fixtures/hle-probe/Cargo.toml + + # As in the linux job: the Windows-target builds (the workspace's and the + # hle-probe fixture's, build scripts included) must leave the checkout as + # they found it. Build output (target/, the fixture's target/) does not + # count; anything else, tracked, untracked or ignored, fails. The + # fixture's --locked steps already cover its own Cargo.lock. + - name: Checkout unchanged by the steps above + run: | + changes="$(git status --porcelain=v1 --untracked-files=all)" + if [[ -n "${changes}" ]]; then + echo "::error::the steps above modified or created files in the checkout" >&2 + printf '%s\n' "${changes}" >&2 + git diff --stat >&2 + exit 1 + fi + # .gitignore hides *.bin, *.dll, *.dat, ... from `git status`, so a + # scratch file of those kinds would pass the check above. List the + # ignored files too (whole ignored directories collapse to one + # entry) and allow only the build output directories. + list="${RUNNER_TEMP}/ignored-files" + git ls-files -z --others --ignored --exclude-standard --directory > "${list}" + mapfile -d '' -t ignored < "${list}" + stray=() + for f in "${ignored[@]}"; do + if [[ "${f}" != target/ && ! "${f}" =~ ^tests/fixtures/[^/]+/target/$ ]]; then + stray+=("${f}") + fi + done + if [[ "${#stray[@]}" -ne 0 ]]; then + echo "::error::the steps above created ignored files outside target/" >&2 + printf '%s\n' "${stray[@]}" >&2 + exit 1 + fi + + # Cargo.toml declares `rust-version` (the MSRV) for every member, but the + # jobs above build with the newer toolchain pinned in rust-toolchain.toml, + # so code using a newer language feature or std API, or a Cargo.lock bump + # to a dependency that needs a newer rustc, passed CI and broke anyone + # building with the declared version. Type-check with exactly that version + # (read from Cargo.toml, so the two cannot drift): the Linux crates and the + # whole workspace for the Windows target, default and all features, plus + # the hle-probe fixture, which load_probe builds with the same cargo that + # ran the test. Only `cargo check`: older rustc and clippy warn + # differently, so warnings are left to the pinned-toolchain jobs. Its own + # target dir in RUNNER_TEMP keeps a second compiler's output out of the + # rust-cache entries the other jobs share. + msrv: + name: msrv + runs-on: ubuntu-24.04 + # checkout only. + permissions: + contents: read + timeout-minutes: 30 + env: + # As in windows-target-check: blake3's build script picks its + # pure-Rust code instead of calling MSVC's tools. Nothing is linked. + CARGO_FEATURE_PURE: "1" + steps: + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + # The root [workspace.package] rust-version is read with the runner's + # Python 3 tomllib (-I: no site packages, no cwd on sys.path), since + # cargo would first install the pinned toolchain. Every member must + # inherit it; one that declares its own would not be checked against + # the version it claims. --no-self-update: as in the linux job. + - name: Install the rust-version toolchain + run: | + msrv="$(python3 -I -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["rust-version"])')" + if [[ ! "${msrv}" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then + echo "::error file=Cargo.toml::unexpected workspace rust-version '${msrv}'" >&2 + exit 1 + fi + rustup toolchain install "${msrv}" --profile minimal --target x86_64-pc-windows-msvc --no-self-update + metadata="$(cargo +"${msrv}" metadata --locked --no-deps --format-version 1)" + others="$(jq -r --arg v "${msrv}" '.packages[] | select(.rust_version != $v) | "\(.name) (\(.rust_version))"' <<< "${metadata}")" + if [[ -n "${others}" ]]; then + echo "::error::workspace members whose rust-version is not the workspace's ${msrv}:" >&2 + printf '%s\n' "${others}" >&2 + exit 1 + fi + echo "MSRV=${msrv}" >> "${GITHUB_ENV}" + echo "CARGO_TARGET_DIR=${RUNNER_TEMP}/msrv-target" >> "${GITHUB_ENV}" + + - name: cargo check (Linux crates) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + cargo +"${MSRV}" check --locked --all-targets "${crates[@]}" + cargo +"${MSRV}" check --locked --all-targets --all-features "${crates[@]}" + + - name: cargo check (Windows target, workspace and hle-probe fixture) + run: | + cargo +"${MSRV}" check --locked --workspace --all-targets --target x86_64-pc-windows-msvc + cargo +"${MSRV}" check --locked --workspace --all-targets --all-features --target x86_64-pc-windows-msvc + cargo +"${MSRV}" check --locked --all-targets --target x86_64-pc-windows-msvc --manifest-path tests/fixtures/hle-probe/Cargo.toml + + # As in the linux and windows-target-check jobs: build scripts and the + # msrv checks must leave the checkout as they found it (output under + # CARGO_TARGET_DIR in RUNNER_TEMP, or target/, does not count). + - name: Checkout unchanged by the steps above + run: | + changes="$(git status --porcelain=v1 --untracked-files=all)" + if [[ -n "${changes}" ]]; then + echo "::error::the steps above modified or created files in the checkout" >&2 + printf '%s\n' "${changes}" >&2 + git diff --stat >&2 + exit 1 + fi + list="${RUNNER_TEMP}/ignored-files" + git ls-files -z --others --ignored --exclude-standard --directory > "${list}" + mapfile -d '' -t ignored < "${list}" + stray=() + for f in "${ignored[@]}"; do + if [[ "${f}" != target/ && ! "${f}" =~ ^tests/fixtures/[^/]+/target/$ ]]; then + stray+=("${f}") + fi + done + if [[ "${#stray[@]}" -ne 0 ]]; then + echo "::error::the steps above created ignored files outside target/" >&2 + printf '%s\n' "${stray[@]}" >&2 + exit 1 + fi diff --git a/crates/victory-formats/examples/texture_layout_bench.rs b/crates/victory-formats/examples/texture_layout_bench.rs new file mode 100644 index 00000000..53c3936d --- /dev/null +++ b/crates/victory-formats/examples/texture_layout_bench.rs @@ -0,0 +1,89 @@ +//! Run with `cargo run --release -p victory-formats --example texture_layout_bench`. + +use std::hint::black_box; +use std::time::Instant; + +use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; + +fn main() { + const CALLS: u64 = 50_000; + let base = TextureDesc { + dimension: Dimension::Tex2d, + width: 512, + height: 512, + depth_or_array: 1, + mips: 0, + format: 98, // BC7 + samples: 1, + swizzle: Swizzle::SW_64KB_D, + }; + let cases = [ + ("BC7 64KB_D", base), + ( + "BC1 64KB_S", + TextureDesc { + format: 71, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 4KB_D", + TextureDesc { + format: 28, + swizzle: Swizzle::SW_4KB_D, + ..base + }, + ), + ( + "R8 64KB_S", + TextureDesc { + format: 61, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 volume 64KB_S", + TextureDesc { + dimension: Dimension::Tex3d, + width: 128, + height: 128, + depth_or_array: 64, + format: 28, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 linear", + TextureDesc { + format: 28, + swizzle: Swizzle::LINEAR, + ..base + }, + ), + ]; + + for (name, desc) in cases { + let mut samples = [0.0; 7]; + black_box(Texture::new(black_box(&desc)).unwrap()); + let mut checksum = 0u64; + for sample in &mut samples { + let start = Instant::now(); + for i in 0..CALLS { + let desc = TextureDesc { + width: desc.width + (i % 32) as u32, + ..desc + }; + let texture = black_box(Texture::new(black_box(&desc)).unwrap()); + let layout = &texture.planes[0].layout; + checksum = + checksum.wrapping_add(texture.size + layout.offset(0, 7, 11, 0).unwrap()); + } + *sample = start.elapsed().as_secs_f64() * 1e9 / CALLS as f64; + } + samples.sort_by(f64::total_cmp); + println!("{name:22} {:8.1} ns/layout {checksum}", samples[3]); + } +} diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index c8d35378..0218fc76 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -12,6 +12,7 @@ //! the BC7 control codes and the dictionaries are constants of the format, //! kept in `bcpack-tables.bin` beside this file ([`Tables::builtin`]). +use std::cell::RefCell; use std::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -252,47 +253,203 @@ impl Tables { } } +/// Reusable scratch space for [`Workspace::decode`]. Holding one per worker +/// thread avoids allocating history ring buffers on repeated streaming calls. +#[derive(Default)] +pub struct Workspace { + plain: Vec, + bc6: Vec<(Bc6Ep, Bc6Ix)>, + bc7: Vec<(Bc7Ep, Bc7Ix)>, +} + +impl Workspace { + /// Creates an empty workspace; format history buffers are allocated lazily + /// on first use and reused across calls. + pub fn new() -> Self { + Self::default() + } + + #[allow(clippy::too_many_arguments)] + fn decode_plain< + const N: usize, + const PER: usize, + const STRIDE: usize, + const EP: usize, + const IX: usize, + const PAIRED: bool, + const OUT: usize, + >( + &mut self, + tables: &Tables, + widths: &[u8; N], + src: &[u8], + dst: &mut [u8], + dictionary: &[Plain], + masks: &Masks, + residual: impl Fn(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8; OUT]), + ) -> Result<(), Error> { + if self.plain.len() != HISTORY { + self.plain.resize(HISTORY, Plain::default()); + } + let history = &mut self.plain[..HISTORY]; + let zero = Plain::default(); + let (out, _) = dst.as_chunks_mut::(); + let mut cursor = 0usize; + let mut feed = |_: usize| -> Option { + let b = *src.get(cursor)?; + cursor += 1; + Some(b) + }; + lanes_stream::(tables, widths, out.len(), &mut feed, |i, s| { + plain_block::( + i, + s, + &mut out[i], + history, + dictionary, + &zero, + masks, + &residual, + pack, + ); + Ok(()) + }) + } + + /// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, reusing this + /// workspace's scratch history buffers without per-call heap allocations. + /// On `Err`, the contents of `dst` are unspecified. + pub fn decode( + &mut self, + bc: u8, + src: &[u8], + dst: &mut [u8], + tables: &Tables, + ) -> Result<(), Error> { + let block = match bc { + 1 | 4 => 8, + 3 | 5 | 6 | 7 => 16, + _ => return Err(Error("unsupported BC format")), + }; + if dst.is_empty() || !dst.len().is_multiple_of(block) { + return Err(Error("destination is not a whole number of blocks")); + } + match bc { + 1 => self.decode_plain::<12, 1, 12, 6, 16, false, 8>( + tables, + &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], + src, + dst, + &tables.bc1, + &BC1_MASK, + |s| bc1_residual(tables, s), + bc1_pack, + ), + 3 => self.decode_plain::<12, 2, 24, 8, 32, true, 16>( + tables, + &[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], + src, + dst, + &tables.bc3, + &BC3_MASK, + |s| bc3_residual(tables, s), + bc3_pack, + ), + 4 => self.decode_plain::<12, 1, 12, 2, 16, false, 8>( + tables, + &[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], + src, + dst, + &tables.bc4, + &BC4_MASK, + |s| bc4_residual(tables, s), + bc4_pack, + ), + 5 => self.decode_plain::<12, 2, 24, 4, 32, true, 16>( + tables, + &[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], + src, + dst, + &tables.bc5, + &BC5_MASK, + |s| bc5_residual(tables, s), + bc5_pack, + ), + 6 => { + if self.bc6.len() != HISTORY { + self.bc6 + .resize(HISTORY, (Bc6Ep::default(), Bc6Ix::default())); + } + let history = &mut self.bc6[..HISTORY]; + let zero = ( + Bc6Ep::default(), + Bc6Ix { + mode: 11, + ..Default::default() + }, + ); + let (out, _) = dst.as_chunks_mut::<16>(); + let mut cursor = 0usize; + let mut feed = |_: usize| -> Option { + let b = *src.get(cursor)?; + cursor += 1; + Some(b) + }; + lanes_stream::<16, 2, 32>( + tables, + &[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], + out.len(), + &mut feed, + |i, s| bc6_block(i, s, &mut out[i], history, &tables.bc6, &zero), + ) + } + _ => { + if self.bc7.len() != HISTORY { + self.bc7 + .resize(HISTORY, (Bc7Ep::default(), Bc7Ix::default())); + } + let history = &mut self.bc7[..HISTORY]; + let zero = (Bc7Ep::default(), Bc7Ix::default()); + let (out, _) = dst.as_chunks_mut::<16>(); + let mut cursor = 0usize; + let mut feed = |_: usize| -> Option { + let b = *src.get(cursor)?; + cursor += 1; + Some(b) + }; + lanes_stream::<16, 2, 32>( + tables, + &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], + out.len(), + &mut feed, + |i, s| bc7_block(i, s, &mut out[i], history, tables, &zero), + ) + } + } + } +} + +thread_local! { + static WORKSPACE: RefCell = RefCell::new(Workspace::new()); +} + /// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, whose length gives /// the block count. The stream carries no size: bytes after the last one the -/// lanes need are ignored, a stream that runs out is an error. +/// lanes need are ignored, a stream that runs out is an error. On `Err`, the +/// contents of `dst` are unspecified. pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> { - let block = match bc { - 1 | 4 => 8, - 3 | 5 | 6 | 7 => 16, - _ => return Err(Error("unsupported BC format")), - }; - if dst.is_empty() || !dst.len().is_multiple_of(block) { - return Err(Error("destination is not a whole number of blocks")); - } - let blocks = dst.len() / block; - let (widths, per): (&[u8], usize) = match bc { - 1 => (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), - 3 => (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), - 4 => (&[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1), - 5 => (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), - 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), - _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), - }; - let stride = widths.len() * per; - let mut records = vec![0u8; blocks * stride]; - let mut next = src.iter().copied(); - lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; - let records = records.chunks_exact(stride); - let out = dst.chunks_exact_mut(block); - let t = tables; - match bc { - 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), - 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), - 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), - 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), - 6 => bc6(records, out, &t.bc6), - _ => bc7(records, out, t), - } + WORKSPACE.with(|ws| match ws.try_borrow_mut() { + Ok(mut ws) => ws.decode(bc, src, dst, tables), + Err(_) => Workspace::new().decode(bc, src, dst, tables), + }) } // Lanes. -#[derive(Clone, Copy, Default)] +const NONE: u16 = u16::MAX; + +#[derive(Clone, Copy)] struct Lane { /// Symbol bits - 1 at the full alphabet. width: u8, @@ -302,74 +459,106 @@ struct Lane { reset: bool, model: u8, need: bool, - latch: Option, - out: Option, stalled: bool, + latch: u16, + out: u16, x: u32, left: u32, } +impl Default for Lane { + fn default() -> Self { + Self { + width: 0, + phase: 0, + long: false, + reset: false, + model: 0, + need: false, + stalled: false, + latch: NONE, + out: NONE, + x: 0, + left: 0, + } + } +} + impl Lane { + #[cold] + #[inline(never)] + fn step_control(&mut self) { + if self.latch == NONE { + return; + } + let b = self.latch as u8; + self.latch = NONE; + self.need = true; + match self.phase { + 0 => { + // The top two bits shrink the alphabet; width >= 3. + let group = self.width - (b >> 6); + self.model = group * 16 + (b & 15); + self.reset = b & 0x10 != 0; + self.long = b & 0x20 != 0; + self.left = 0; + self.phase = 1; + } + 1 if self.long => { + self.left = b.into(); + self.phase = 2; + } + 1 => { + self.left = u32::from(b) + 1; + self.phase = 3; + } + _ => { + self.left = (u32::from(b) << 8 | self.left) + 257; + self.phase = 3; + } + } + } + /// One step: take the latched byte (header, length or payload) and /// decode at most one symbol. - fn step(&mut self, t: &Tables) -> Result<(), Error> { + #[inline(always)] + fn step(&mut self, t: &Tables) { if self.phase != 3 { - let Some(b) = self.latch.take() else { - return Ok(()); - }; - self.need = true; - match self.phase { - 0 => { - // The top two bits shrink the alphabet; width >= 3. - let group = self.width - (b >> 6); - self.model = group * 16 + (b & 15); - self.reset = b & 0x10 != 0; - self.long = b & 0x20 != 0; - self.left = 0; - self.phase = 1; - } - 1 if self.long => { - self.left = b.into(); - self.phase = 2; - } - 1 => { - self.left = u32::from(b) + 1; - self.phase = 3; - } - _ => { - self.left = (u32::from(b) << 8 | self.left) + 257; - self.phase = 3; - } - } - return Ok(()); + self.step_control(); + return; } let mut x = self.x; - if x < LOW - && let Some(b) = self.latch.take() - { + if x < LOW && self.latch != NONE { + let b = u32::from(self.latch as u8); + self.latch = NONE; self.left = self.left.wrapping_sub(1); - x = x << 8 | u32::from(b); + x = (x << 8) | b; } - self.need = self.left != 0 && self.latch.is_none(); + self.need = self.left != 0 && self.latch == NONE; if x > LOW { - let freq = &t.freq[usize::from(self.model)]; - let start = &t.start[usize::from(self.model)]; + let m = usize::from(self.model); + let freq = &t.freq[m]; + let start = &t.start[m]; let slot = x & 0xffff; // The bucket: starts are ascending, and 65536 past the model's last. let b = bucket_of(t, self.model, slot); // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0 - // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency - // f[b] from start[b] on; offset and frequency are below 2^16, where - // the reciprocal divides exactly. + // is never used). Bucket 1 holds symbol 1. Elsewhere offset and + // frequency are below 2^16, where the reciprocal divides exactly + // and `offset - q * f == slot - c`. let (sym, f, rem) = if b == 0 { - (0, freq[0] - 1, slot.wrapping_sub(1)) + (0u8, freq[0] - 1, slot.wrapping_sub(1)) + } else if b == 1 { + (1u8, freq[1], slot - start[1]) } else { let offset = slot - start[b]; - let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; - ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) + let rec = t.recip[m][b]; + let q = ((u64::from(offset) * rec) >> 32) as u32; + let f = freq[b]; + ((1u8 << (b - 1)).wrapping_add(q as u8), f, offset - q * f) }; self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); - self.out = Some(sym as u8); + self.out = u16::from(sym); } else if self.left != 0 { // At exactly 2^24 the lane neither reads nor decodes again; only a // lane that has delivered its symbols may end up there. @@ -377,12 +566,11 @@ impl Lane { } else { // The fragment ends; a byte read in this step does not reach the carried state. self.phase = 0; - self.need = self.latch.is_none(); + self.need = self.latch == NONE; if self.reset { self.x = 0; } } - Ok(()) } } @@ -399,66 +587,59 @@ fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { b } -/// Decodes `per` symbols per block on every lane into `records` (one record -/// of `widths.len() * per` symbols per block), taking input from `fetch` -/// (given the lane that takes the byte) in the order of the schedule: each -/// round the lanes step in order and take at most 8 bytes between them. -// shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s -// on one core); if texture streaming needs more, run the schedule only to -// split the input per lane and decode the lanes apart. -fn lanes( +/// Decodes `PER` symbols per block across `N` interleaved lanes and invokes +/// `on_block` with each completed `STRIDE = N * PER`-byte record in place, +/// avoiding a multi-megabyte intermediate `records` buffer. +fn lanes_stream( t: &Tables, - widths: &[u8], - per: usize, + widths: &[u8; N], blocks: usize, - mut fetch: impl FnMut(usize) -> Option, - records: &mut [u8], + fetch: &mut impl FnMut(usize) -> Option, + mut on_block: impl FnMut(usize, &[u8; STRIDE]) -> Result<(), Error>, ) -> Result<(), Error> { - let mut lanes = [Lane::default(); 16]; - let lanes = &mut lanes[..widths.len()]; - for (lane, &width) in lanes.iter_mut().zip(widths) { - lane.width = width; - lane.need = true; + debug_assert_eq!(N * PER, STRIDE); + let mut lanes = [Lane::default(); N]; + for j in 0..N { + lanes[j].width = widths[j]; + lanes[j].need = true; } - let stride = widths.len() * per; - let full = (1u32 << widths.len()) - 1; - let (mut pos, mut done, mut idle) = (0, 0u32, 0); - // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. - let mut at = 0; - while pos < blocks * per { - let (mut taken, mut moved) = (0, false); + let full = (1u32 << N) - 1; + let mut rec = [0u8; STRIDE]; + let (mut block_idx, mut sub, mut done, mut idle) = (0usize, 0usize, 0u32, 0u32); + while block_idx < blocks { + let (mut taken, mut moved) = (0usize, false); for (j, lane) in lanes.iter_mut().enumerate() { - let bit = 1 << j; + let bit = 1u32 << j; let before = taken; if !lane.stalled { - lane.step(t)?; + lane.step(t); } - let waiting = lane.out.is_some() && done & bit != 0; + let waiting = lane.out != NONE && (done & bit) != 0; if lane.need && !waiting && taken < ROUND_BYTES { // Past the end nothing arrives; in a valid stream only finished lanes ask there. if let Some(b) = fetch(j) { - lane.latch = Some(b); + lane.latch = u16::from(b); taken += 1; } } lane.stalled = (lane.need && before >= ROUND_BYTES) || waiting; - if !lane.stalled - && let Some(sym) = lane.out.take() - { - records[at + j * per] = sym; + if !lane.stalled && lane.out != NONE { + rec[j * PER + sub] = lane.out as u8; + lane.out = NONE; done |= bit; moved = true; } } if done == full { - pos += 1; - at += if pos.is_multiple_of(per) { - stride - per + 1 - } else { - 1 - }; done = 0; moved = true; + if PER == 1 || sub == PER - 1 { + on_block(block_idx, &rec)?; + block_idx += 1; + sub = 0; + } else { + sub += 1; + } } // Nothing read and nothing delivered for a few rounds: no lane can go on. idle = if taken > 0 || moved { 0 } else { idle + 1 }; @@ -469,9 +650,114 @@ fn lanes( Ok(()) } +/// Decodes `per` symbols per block on every lane into `records` (one record +/// of `widths.len() * per` symbols per block), taking input from `fetch` +/// (given the lane that takes the byte) in the order of the schedule. +#[cfg(test)] +fn lanes( + t: &Tables, + widths: &[u8], + per: usize, + blocks: usize, + mut fetch: impl FnMut(usize) -> Option, + records: &mut [u8], +) -> Result<(), Error> { + let stride = widths.len() * per; + let mut dst = records.chunks_exact_mut(stride); + match (widths.len(), per) { + (12, 1) => lanes_stream::<12, 1, 12>( + t, + widths.try_into().unwrap(), + blocks, + &mut fetch, + |_, rec| { + dst.next().unwrap().copy_from_slice(rec); + Ok(()) + }, + ), + (12, 2) => lanes_stream::<12, 2, 24>( + t, + widths.try_into().unwrap(), + blocks, + &mut fetch, + |_, rec| { + dst.next().unwrap().copy_from_slice(rec); + Ok(()) + }, + ), + (16, 2) => lanes_stream::<16, 2, 32>( + t, + widths.try_into().unwrap(), + blocks, + &mut fetch, + |_, rec| { + dst.next().unwrap().copy_from_slice(rec); + Ok(()) + }, + ), + _ => Err(Error("unsupported lane layout")), + } +} + // Blocks. +/// Spreads 4 bits into even bit positions (0, 2, 4, 6). +const SPREAD4: [u8; 16] = { + let mut table = [0u8; 16]; + let mut v = 0usize; + while v < 16 { + let mut out = 0u8; + let mut k = 0; + while k < 4 { + out |= (((v >> k) & 1) as u8) << (2 * k); + k += 1; + } + table[v] = out; + v += 1; + } + table +}; + +/// Spreads 8 bits into even bit positions of a `u16`. +const SPREAD8: [u16; 256] = { + let mut table = [0u16; 256]; + let mut v = 0usize; + while v < 256 { + let mut out = 0u16; + let mut k = 0; + while k < 8 { + out |= (((v >> k) & 1) as u16) << (2 * k); + k += 1; + } + table[v] = out; + v += 1; + } + table +}; + +/// Precomputed `[even, odd]` zigzag-coded 4-bit residuals for every byte. +const NIBBLES_EVEN_FIRST: [[i16; 2]; 256] = { + let mut table = [[0i16; 2]; 256]; + let mut b = 0usize; + while b < 256 { + let mut even = 0u8; + let mut odd = 0u8; + let mut k = 0; + while k < 4 { + even |= (((b >> (2 * k)) & 1) as u8) << k; + odd |= (((b >> (2 * k + 1)) & 1) as u8) << k; + k += 1; + } + let ze = ((even >> 1) as i16) ^ -((even & 1) as i16); + let zo = ((odd >> 1) as i16) ^ -((odd & 1) as i16); + table[b] = [ze, zo]; + b += 1; + } + table +}; + /// The record's endpoint and index references. +#[inline(always)] fn references(s: &[u8], paired: bool) -> (usize, usize) { let (d, ix) = if paired { (interleave(s[0], s[1]), interleave(s[2], s[3])) @@ -483,105 +769,125 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { } /// Two 4-bit symbols, the first on the even bits. +#[inline(always)] fn interleave(a: u8, b: u8) -> u8 { - let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); - spread(a) | spread(b) << 1 + SPREAD4[usize::from(a & 15)] | (SPREAD4[usize::from(b & 15)] << 1) } /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first /// block into the dictionary. +#[inline(always)] fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T { match r { 0 => zero, - r if r <= i => &history[(i - r) % HISTORY], + r if r <= i => &history[(i - r) & (HISTORY - 1)], r => &dictionary[r - i - 1], } } /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +#[inline(always)] fn zz(v: u8, bits: u32) -> u8 { let mask = ((1u32 << bits) - 1) as u8; - ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask + ((v >> 1) ^ (v & 1).wrapping_neg()) & mask } -/// Element widths of the plain formats' endpoints and indices. -struct Widths { +/// Precomputed bitmasks for the plain formats' endpoints and indices. +struct Masks { ep: [u8; 8], ix: [u8; 32], - paired: bool, } -const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { - let mut ix = [0; 32]; +const fn masks(ep_bits: [u8; 8], ix3: usize, ix2: usize) -> Masks { + let mut ep = [0u8; 8]; + let mut k = 0; + while k < 8 { + ep[k] = ((1u16 << ep_bits[k]) - 1) as u8; + k += 1; + } + let mut ix = [0u8; 32]; let mut k = 0; while k < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + ix[k] = if k < ix3 { 7 } else { 3 }; k += 1; } - Widths { ep, ix, paired } + Masks { ep, ix } } -const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); -const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true); -const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false); -const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true); - -fn plain<'a>( - records: impl Iterator, - out: impl Iterator, +const BC1_MASK: Masks = masks([5, 6, 5, 5, 6, 5, 0, 0], 0, 16); +const BC3_MASK: Masks = masks([5, 6, 5, 5, 6, 5, 8, 8], 16, 16); +const BC4_MASK: Masks = masks([8, 8, 0, 0, 0, 0, 0, 0], 16, 0); +const BC5_MASK: Masks = masks([8, 8, 8, 8, 0, 0, 0, 0], 32, 0); + +#[allow(clippy::too_many_arguments)] +#[inline(always)] +fn plain_block( + i: usize, + s: &[u8], + block: &mut [u8; OUT], + history: &mut [Plain], dictionary: &[Plain], - w: &Widths, - residual: impl Fn(&[u8]) -> Plain, - pack: fn(&Plain, &mut [u8]), -) -> Result<(), Error> { - let mut history = vec![Plain::default(); HISTORY]; - let zero = Plain::default(); - for (i, (s, block)) in records.zip(out).enumerate() { - let (ep_ref, ix_ref) = references(s, w.paired); - let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; - let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; - let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; - } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); - } - history[i % HISTORY] = v; - pack(&v, block); + zero: &Plain, + m: &Masks, + residual: impl FnOnce(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8; OUT]), +) { + let (ep_ref, ix_ref) = references(s, PAIRED); + let ep_ref = &pick(i, ep_ref, history, dictionary, zero).ep; + let ix_ref = &pick(i, ix_ref, history, dictionary, zero).ix; + let mut v = residual(s); + for ((v, &r), &mask) in v.ep[..EP].iter_mut().zip(&ep_ref[..EP]).zip(&m.ep[..EP]) { + *v = v.wrapping_add(r) & mask; } - Ok(()) + for ((v, &r), &mask) in v.ix[..IX].iter_mut().zip(&ix_ref[..IX]).zip(&m.ix[..IX]) { + *v = v.wrapping_add(r) & mask; + } + history[i & (HISTORY - 1)] = v; + pack(&v, block); } /// 2-bit index residuals: one symbol per 2x2 quad. +#[inline(always)] fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { - for (q, &sym) in s.iter().enumerate() { - let v = rank[usize::from(sym)]; - let base = (q >> 1) * 8 + (q & 1) * 2; - for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { - ix[base + p] = v >> (2 * k) & 3; - } + for (q, base) in [0usize, 2, 8, 10].into_iter().enumerate() { + let v = rank[usize::from(s[q])]; + ix[base] = v & 3; + ix[base + 1] = (v >> 2) & 3; + ix[base + 4] = (v >> 4) & 3; + ix[base + 5] = (v >> 6) & 3; } } /// 3-bit index residuals: one symbol per two pixels in raster order. -fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for (k, &sym) in s.iter().enumerate() { - let v = rank[usize::from(sym & 63)]; +#[inline(always)] +fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { + for k in 0..N { + let v = rank[usize::from(s[k] & 63)]; ix[2 * k] = v & 7; - ix[2 * k + 1] = v >> 4 & 7; + ix[2 * k + 1] = (v >> 4) & 7; } } +#[inline(always)] fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { - let mut v = Plain::default(); - for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { - v.ep[k] = zz(s[2 + k], bits); - } + let mut v = Plain { + ep: [ + zz(s[2], 5), + zz(s[3], 6), + zz(s[4], 5), + zz(s[5], 5), + zz(s[6], 6), + zz(s[7], 5), + 0, + 0, + ], + ix: [0; 32], + }; quads(&t.rank1, &s[8..12], &mut v.ix); v } +#[inline(always)] fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { // Colour lanes carry each channel's two endpoints together. let mut v = Plain { @@ -595,26 +901,29 @@ fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { zz(s[4], 8), zz(s[5], 8), ], - ..Default::default() + ix: [0; 32], }; - pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); + pairs::<8>(&t.rank3a, &s[6..14], &mut v.ix[..16]); quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); v } +#[inline(always)] fn bc4_residual(t: &Tables, s: &[u8]) -> Plain { let mut v = Plain::default(); - v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]); - pairs(&t.rank4, &s[4..12], &mut v.ix[..16]); + v.ep[0] = zz(s[2], 8); + v.ep[1] = zz(s[3], 8); + pairs::<8>(&t.rank4, &s[4..12], &mut v.ix[..16]); v } +#[inline(always)] fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { let mut v = Plain::default(); for k in 0..4 { v.ep[k] = zz(s[4 + k], 8); } - pairs(&t.rank5, &s[8..24], &mut v.ix); + pairs::<16>(&t.rank5, &s[8..24], &mut v.ix); v } @@ -622,54 +931,57 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; -fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { - let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); - let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); - let bits = (0..16).fold(0, |acc, p| { - acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) - }); - out[..2].copy_from_slice(&c0.to_le_bytes()); - out[2..4].copy_from_slice(&c1.to_le_bytes()); - out[4..8].copy_from_slice(&bits.to_le_bytes()); +#[inline(always)] +fn bc1_color(ep: &[u8; 8], ix: &[u8], out: &mut [u8]) { + let c0 = u32::from(ep[0]) << 11 | u32::from(ep[1]) << 5 | u32::from(ep[2]); + let c1 = u32::from(ep[3]) << 11 | u32::from(ep[4]) << 5 | u32::from(ep[5]); + let mut bits = 0u32; + for p in 0..16 { + bits |= BC1_CODE[usize::from(ix[p] & 3)] << (2 * p); + } + let word = u64::from(c0) | (u64::from(c1) << 16) | (u64::from(bits) << 32); + out[..8].copy_from_slice(&word.to_le_bytes()); } /// BC4 half: endpoints are kept 128 below their stored value. +#[inline(always)] fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let bits = (0..16).fold(0u64, |acc, p| { - acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) - }); + let mut bits = 0u64; + for p in 0..16 { + bits |= BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p); + } let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; out[..8].copy_from_slice(&v.to_le_bytes()); } -fn bc1_pack(v: &Plain, out: &mut [u8]) { - bc1_color(&v.ep, &v.ix, out); +fn bc1_pack(v: &Plain, out: &mut [u8; 8]) { + bc1_color(&v.ep, &v.ix[..16], out); } -fn bc3_pack(v: &Plain, out: &mut [u8]) { +fn bc3_pack(v: &Plain, out: &mut [u8; 16]) { bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); - bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); + bc1_color(&v.ep, &v.ix[16..32], &mut out[8..16]); } -fn bc4_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); +fn bc4_pack(v: &Plain, out: &mut [u8; 8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], out); } -fn bc5_pack(v: &Plain, out: &mut [u8]) { +fn bc5_pack(v: &Plain, out: &mut [u8; 16]) { bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); - bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); + bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..32], &mut out[8..16]); } /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +#[inline(always)] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES_EVEN_FIRST[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). +#[inline(always)] fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { let up = |v: i16, b: u8| { if b == 0 || b > 16 { @@ -690,6 +1002,7 @@ struct Bits { } impl Bits { + #[inline(always)] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; @@ -757,97 +1070,104 @@ fn bc7_precision(ctrl: u16) -> [u8; 4] { p } -fn bc7<'a>( - records: impl Iterator, - out: impl Iterator, +#[inline(always)] +fn bc7_block( + i: usize, + s: &[u8; 32], + block: &mut [u8; 16], + history: &mut [(Bc7Ep, Bc7Ix)], t: &Tables, + zero: &(Bc7Ep, Bc7Ix), ) -> Result<(), Error> { - let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; - let zero = (Bc7Ep::default(), Bc7Ix::default()); - for (i, (s, block)) in records.zip(out).enumerate() { - let (ep_ref, ix_ref) = references(s, true); - let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; - if ctrl == 0 { - return Err(Error("unused BC7 control code")); + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); + } + let mode = usize::from(ctrl & 7); + let subsets = usize::from((ctrl & 0xff) >> 6); + let prec = bc7_precision(ctrl); + let three = subsets == 3; + let or0 = |v: u8| if three { 0 } else { v }; + let if3 = |v: u8| if three { v } else { 0 }; + let stored = [ + [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], + [ + s[12], + s[13], + s[14], + s[15], + s[16], + s[17], + or0(s[18]), + or0(s[19]), + ], + [ + s[20], + s[21], + if3(s[10]), + if3(s[11]), + if3(s[18]), + if3(s[19]), + 0, + 0, + ], + ]; + let r = &pick(i, ep_ref, history, &t.bc7, zero).0; + let mut ep = Bc7Ep { + ctrl, + ..Default::default() + }; + // Rows the reference lacks build on its first row. + let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); + let columns = if prec[3] > 0 { 8 } else { 6 }; + for c in 0..columns { + let p = prec[c / 2]; + if p == 0 { + continue; } - let mode = usize::from(ctrl & 7); - let subsets = usize::from((ctrl & 0xff) >> 6); - let prec = bc7_precision(ctrl); - let three = subsets == 3; - let or0 = |v: u8| if three { 0 } else { v }; - let if3 = |v: u8| if three { v } else { 0 }; - let stored = [ - [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], - [ - s[12], - s[13], - s[14], - s[15], - s[16], - s[17], - or0(s[18]), - or0(s[19]), - ], - [ - s[20], - s[21], - if3(s[10]), - if3(s[11]), - if3(s[18]), - if3(s[19]), - 0, - 0, - ], - ]; - let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0; - let mut ep = Bc7Ep { - ctrl, - ..Default::default() - }; - // Rows the reference lacks build on its first row. - let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); - let columns = if prec[3] > 0 { 8 } else { 6 }; - for c in 0..columns { - let p = prec[c / 2]; - if p == 0 { - continue; - } - let mask = 0xffffu16 << (16 - p); - for (row, st) in stored.iter().enumerate().take(subsets) { - let v = st[c]; - let residual = - (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); - let base = r.rows[if row < common { row } else { 0 }][c] & mask; - ep.rows[row][c] = base.wrapping_add(residual); - } + let sh = 16 - p; + let mask = 0xffffu16 << sh; + for (row, st) in stored.iter().enumerate().take(subsets) { + let v = st[c]; + let residual = (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << sh; + let base = r.rows[if row < common { row } else { 0 }][c] & mask; + ep.rows[row][c] = base.wrapping_add(residual); } - let bits = BC7_INDEX[mode]; - let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1; - let mut ix = Bc7Ix { - bits, - ..Default::default() - }; - for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { - if bits[set] == 0 { - continue; - } - for (k, o) in offsets.into_iter().enumerate() { - for (b, &byte) in s[o..o + 2].iter().enumerate() { - let pair = nibbles(byte, k < 3); - for (h, &v) in pair.iter().enumerate() { - let p = 4 * k + 2 * b + h; - ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); - } - } - } + } + let bits = BC7_INDEX[mode]; + let rx = &pick(i, ix_ref, history, &t.bc7, zero).1; + let mut ix = Bc7Ix { + bits, + ..Default::default() + }; + for (set, offsets) in [[22usize, 24, 26, 28], [12, 14, 16, 20]] + .into_iter() + .enumerate() + { + let b_set = bits[set]; + if b_set == 0 { + continue; + } + let rb_set = rx.bits[set]; + for (k, o) in offsets.into_iter().enumerate() { + let odd_first = k < 3; + let [v0, v1] = nibbles(s[o], odd_first); + let [v2, v3] = nibbles(s[o + 1], odd_first); + let p0 = 4 * k; + ix.ix[set][p0] = add_index(v0, b_set, rx.ix[set][p0], rb_set); + ix.ix[set][p0 + 1] = add_index(v1, b_set, rx.ix[set][p0 + 1], rb_set); + ix.ix[set][p0 + 2] = add_index(v2, b_set, rx.ix[set][p0 + 2], rb_set); + ix.ix[set][p0 + 3] = add_index(v3, b_set, rx.ix[set][p0 + 3], rb_set); } - history[i % HISTORY] = (ep, ix); - bc7_pack(&ep, &ix, prec, block); } + history[i & (HISTORY - 1)] = (ep, ix); + bc7_pack(&ep, &ix, prec, block); Ok(()) } -fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { +#[inline(always)] +fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8; 16]) { let ctrl = ep.ctrl; let mode = ctrl & 7; let subsets = usize::from((ctrl & 0xff) >> 6); @@ -886,15 +1206,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + let anchor_mask: u16 = match subsets { + 2 => 1 | (1u16 << ANCHOR2[part]), + 3 => 1 | (1u16 << ANCHOR3A[part]) | (1u16 << ANCHOR3B[part]), + _ => 1, }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + let n = bits - u32::from((anchor_mask >> p) & 1); w.put(u64::from(v as u16), n); } }; @@ -909,7 +1229,7 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { } _ => indices(0), } - out.copy_from_slice(&w.v.to_le_bytes()); + *out = w.v.to_le_bytes(); } // BC6H. @@ -1057,107 +1377,99 @@ fn bc6_index_bits(mode: u8) -> u8 { } } -fn bc6<'a>( - records: impl Iterator, - out: impl Iterator, +#[inline(always)] +fn bc6_block( + i: usize, + s: &[u8; 32], + block: &mut [u8; 16], + history: &mut [(Bc6Ep, Bc6Ix)], dictionary: &[(Bc6Ep, Bc6Ix)], + zero: &(Bc6Ep, Bc6Ix), ) -> Result<(), Error> { - let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY]; - let zero = ( - Bc6Ep::default(), - Bc6Ix { - mode: 11, - ..Default::default() - }, - ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); - let wide = |a: u8, b: u8| { - (0..8).fold(0u16, |acc, k| { - acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) - }) + let wide = |a: u8, b: u8| SPREAD8[usize::from(a)] | (SPREAD8[usize::from(b)] << 1); + let (ep_ref, ix_ref) = references(s, true); + let mode = s[30].wrapping_add(1); + if !(1..=14).contains(&mode) { + return Err(Error("BC6H mode out of range")); + } + let two = mode < 11; + let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); + let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); + let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); + let (e2, e3) = if two { + ( + [s[16], s[18], s[20]].map(|v| z(v.into())), + [s[17], s[19], s[21]].map(|v| z(v.into())), + ) + } else { + (e0, e1) }; - for (i, (s, block)) in records.zip(out).enumerate() { - let (ep_ref, ix_ref) = references(s, true); - let mode = s[30].wrapping_add(1); - if !(1..=14).contains(&mode) { - return Err(Error("BC6H mode out of range")); - } - let two = mode < 11; - let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); - let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); - let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); - let (e2, e3) = if two { - ( - [s[16], s[18], s[20]].map(|v| z(v.into())), - [s[17], s[19], s[21]].map(|v| z(v.into())), - ) - } else { - (e0, e1) - }; - let r = &pick(i, ep_ref, &history, dictionary, &zero).0; - let mut ep = Bc6Ep::default(); - // Endpoint 0 at the base precision, the others per channel; the - // reference is cut by the mask after the sum. - let mask = |sh: u32| 0xffffu16 << sh; - for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { - *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); - } - for (k, res) in [e1, e2, e3] - .iter() - .enumerate() - .take(if two { 3 } else { 1 }) - { - for c in 0..3 { - ep.e[k + 1][c] = - r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); - } - } - if !two { - for c in 0..3 { - ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; - } - ep.e[3] = ep.e[1]; - } - let rx = &pick(i, ix_ref, &history, dictionary, &zero).1; - let bits = bc6_index_bits(mode); - let mut ix = Bc6Ix { - mode, - ..Default::default() - }; - for k in 0..8 { - for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { - let p = 2 * k + h; - ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); - } + let r = &pick(i, ep_ref, history, dictionary, zero).0; + let mut ep = Bc6Ep::default(); + // Endpoint 0 at the base precision, the others per channel; the + // reference is cut by the mask after the sum. + let mask = |sh: u32| 0xffffu16 << sh; + for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { + *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); + } + for (k, res) in [e1, e2, e3] + .iter() + .enumerate() + .take(if two { 3 } else { 1 }) + { + for c in 0..3 { + ep.e[k + 1][c] = + r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); } - history[i % HISTORY] = (ep, ix); - // Fields: the working value has its top bit flipped. - let field = |k: usize, c: usize| { - let sh = if k == 0 { shift[0] } else { shift[1 + c] }; - u64::from((ep.e[k][c] ^ 0x8000) >> sh) - }; - let mut w = Bits::default(); - let (code, n) = BC6_CODE[usize::from(mode)]; - w.put(code, n); - let part = s[31] & 31; - for run in BC6_LAYOUT[usize::from(mode)] { - if run.ch == 3 { - w.put(part.into(), 5); - } else { - w.put( - field(run.ep.into(), run.ch.into()) >> run.first, - run.len.into(), - ); - } + } + if !two { + for c in 0..3 { + ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; - for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(1 << (bits - 1)); - w.put(v.into(), u32::from(bits) - u32::from(short)); + ep.e[3] = ep.e[1]; + } + let rx = &pick(i, ix_ref, history, dictionary, zero).1; + let bits = bc6_index_bits(mode); + let ref_bits = bc6_index_bits(rx.mode); + let mut ix = Bc6Ix { + mode, + ..Default::default() + }; + for k in 0..8 { + let [v0, v1] = nibbles(s[22 + k], k < 6); + let p0 = 2 * k; + ix.ix[p0] = add_index(v0, bits, rx.ix[p0], ref_bits); + ix.ix[p0 + 1] = add_index(v1, bits, rx.ix[p0 + 1], ref_bits); + } + history[i & (HISTORY - 1)] = (ep, ix); + // Fields: the working value has its top bit flipped. + let field = |k: usize, c: usize| { + let sh = if k == 0 { shift[0] } else { shift[1 + c] }; + u64::from((ep.e[k][c] ^ 0x8000) >> sh) + }; + let mut w = Bits::default(); + let (code, n) = BC6_CODE[usize::from(mode)]; + w.put(code, n); + let part = s[31] & 31; + for run in BC6_LAYOUT[usize::from(mode)] { + if run.ch == 3 { + w.put(part.into(), 5); + } else { + w.put( + field(run.ep.into(), run.ch.into()) >> run.first, + run.len.into(), + ); } - block.copy_from_slice(&w.v.to_le_bytes()); } + let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + let bias = 1u16 << (bits - 1); + for (p, &v) in ix.ix.iter().enumerate() { + let short = p == 0 || p == usize::from(anchor); + let v = (v as u16).wrapping_add(bias); + w.put(v.into(), u32::from(bits) - u32::from(short)); + } + *block = w.v.to_le_bytes(); Ok(()) } @@ -1473,11 +1785,11 @@ mod tests { left: 1, ..Default::default() }; - lane.step(&t).unwrap(); + lane.step(&t); let (sym, next) = reference_decode(&t, model, x); assert_eq!( (lane.out, lane.x), - (Some(sym), next), + (u16::from(sym), next), "model {model} x {x:#x}" ); } @@ -1594,6 +1906,74 @@ mod tests { assert!(n > 0); } + #[test] + fn workspace_reuse_matches_fresh_decode_across_all_formats() { + let t = Tables::parse(&tables()).unwrap(); + let layouts: [(u8, &[u8], usize, usize); 6] = [ + (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8), + (3, &[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2, 16), + (4, &[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1, 8), + (5, &[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2, 16), + (6, &[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2, 16), + (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16), + ]; + let mut ws = Workspace::new(); + // Run twice across all 6 formats with different block counts (including > HISTORY = 256) + // so history buffers are reused across formats and calls without leaking prior state. + for &(bc, widths, per, blk_size) in layouts.iter().chain(layouts.iter()) { + let stride = widths.len() * per; + let blocks = if bc == 1 || bc == 7 { 300 } else { 40 }; + let records: Vec> = (0..blocks) + .map(|i| { + let mut r = vec![0u8; stride]; + for (j, &w) in widths.iter().enumerate() { + let mask = (1u16 << (w + 1)) - 1; + for sub in 0..per { + r[j * per + sub] = (((i * 17 + j * 11 + sub * 5) as u16) & mask) as u8; + } + } + if bc == 6 { + r[30] = (i % 14) as u8; // valid BC6H modes 1..=14 + } else if bc == 7 { + r[30] = 0; // control code 0 -> mode 6 in synthetic tables + r[31] = 0; + } + r + }) + .collect(); + let src = stream(&t, widths, per, &records); + let mut via_ws = vec![0xaa; blocks * blk_size]; + let mut fresh = vec![0x55; blocks * blk_size]; + ws.decode(bc, &src, &mut via_ws, &t).unwrap(); + Workspace::new().decode(bc, &src, &mut fresh, &t).unwrap(); + assert_eq!(via_ws, fresh, "BC{bc} mismatch on workspace reuse"); + // Corrupt input after valid decode must error without poisoning the workspace. + assert!( + ws.decode(bc, &src[..src.len() / 2], &mut via_ws, &t) + .is_err() + ); + } + } + + #[test] + fn bit_lookup_tables_match_reference_bit_ops() { + for a in 0..=15u8 { + for b in 0..=15u8 { + let spread = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> k) & 1) << (2 * k)); + assert_eq!(interleave(a, b), spread(a) | (spread(b) << 1)); + } + } + for b in 0..=255u8 { + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> (2 * k)) & 1) << k); + let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + let (even, odd) = (z(half(b)), z(half(b >> 1))); + assert_eq!(nibbles(b, false), [even, odd]); + assert_eq!(nibbles(b, true), [odd, even]); + let spread8 = (0..8).fold(0u16, |acc, k| acc | (u16::from((b >> k) & 1) << (2 * k))); + assert_eq!(SPREAD8[usize::from(b)], spread8); + } + } + /// A dictionary entry stands in for a block the decoder made: a set with /// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear). #[test] diff --git a/crates/victory-gpu/src/mesh_emu.rs b/crates/victory-gpu/src/mesh_emu.rs new file mode 100644 index 00000000..4f11af27 --- /dev/null +++ b/crates/victory-gpu/src/mesh_emu.rs @@ -0,0 +1,335 @@ +//! Shared GPU memory and preparation shaders for mesh emulation. +//! +//! An emulated mesh pipeline first runs the translated mesh shader as +//! compute, writing packed primitive indices and attributes into `output`. +//! Its generated vertex shader then reads that memory by `SV_VertexID` and +//! feeds the title's pixel shader. Indirect mesh dispatches first run a +//! tiny preparation pass that sums the bounded group counts, builds a slot +//! map across indirect records, and writes host dispatch/draw arguments. + +use std::sync::OnceLock; + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; + +use crate::host::{Host, HostList, host, name, transition}; +use crate::indirect::uav_barrier; + +const SLOT_MAP_BYTES: u64 = 65_536 * 4; +const INDIRECT_ARGS_BYTES: u64 = 256; +pub(crate) const MAX_INDIRECT_RECORDS: u32 = 65_535; +const OUTPUT_FALLBACK_SIZES: &[u64] = &[128 << 20, 64 << 20, 32 << 20, 16 << 20]; + +pub(crate) const PREP_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), UAV(u0), UAV(u1), UAV(u2), UAV(u3), UAV(u4)" +cbuffer Info : register(b0) { + uint stride; + uint max_records; + uint max_primitives; + uint group_cap; + uint has_count; + uint build_map; +}; +// The source arguments and count use the UAV state also used by title +// compute producers; this pass does not store to them. +RWByteAddressBuffer args : register(u0); +RWByteAddressBuffer count_buf : register(u1); +RWByteAddressBuffer out_args : register(u2); +RWByteAddressBuffer slot_map : register(u3); +RWByteAddressBuffer budget : register(u4); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint n = has_count != 0 ? min(count_buf.Load(0), max_records) : max_records; + uint cap = min(group_cap, 65535u); + uint total = 0; + for (uint r = 0; r < n; ++r) { + if (total >= cap) { + break; + } + uint3 g = args.Load3(r * stride); + uint gx = (g.y != 0 && g.z != 0) ? g.x : 0; + uint left = cap - total; + uint take = min(gx, left); + if (build_map != 0) { + for (uint k = 0; k < take; ++k) { + slot_map.Store((total + k) * 4, k); + } + } + total += take; + } + bool over = false; + uint cost = total * 128u; + if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < (1u << 27)) { + uint next = ((1u << 27) - before <= cost) ? (1u << 27) : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= (1u << 27) || (1u << 27) - before < cost; + } + if (over) total = 0; + out_args.Store4(0, uint4(total, 1, 1, 0)); + out_args.Store4(16, uint4(total * max_primitives * 3, 1, 0, 0)); +} +"#; + +pub(crate) struct Buffers { + pub(crate) output: ID3D12Resource, + pub(crate) output_gpu: u64, + pub(crate) output_bytes: u64, + pub(crate) slot_map: ID3D12Resource, + pub(crate) slot_map_gpu: u64, + pub(crate) indirect_args: ID3D12Resource, + pub(crate) indirect_args_gpu: u64, + pub(crate) dummy_srv: ID3D12Resource, + pub(crate) dummy_srv_gpu: u64, + prep_root: Option, + prep_pso: Option, +} + +// SAFETY: D3D12 resources, root signatures, and pipeline states are free-threaded. +unsafe impl Send for Buffers {} +// SAFETY: as above. +unsafe impl Sync for Buffers {} + +pub(crate) fn buffers() -> Option<&'static Buffers> { + static BUFFERS: OnceLock> = OnceLock::new(); + BUFFERS + .get_or_init(|| match make() { + Some(b) => Some(b), + None => { + tracing::warn!("no mesh emulation buffers; emulated mesh dispatches dropped"); + None + } + }) + .as_ref() +} + +fn configured_output_bytes() -> Option { + let raw = std::env::var("VICTORY_MESH_BUFFER_MB").ok()?; + let mb = raw.trim().parse::().ok()?; + if (1..=1024).contains(&mb) { + Some(mb << 20) + } else { + tracing::warn!( + value = %raw, + "VICTORY_MESH_BUFFER_MB out of range (1..=1024); using default" + ); + None + } +} + +fn allocate_output(host: &Host) -> Option<(ID3D12Resource, u64)> { + if let Some(bytes) = configured_output_bytes() + && let Some(buf) = host.default_buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) + { + return Some((buf, bytes)); + } + for &bytes in OUTPUT_FALLBACK_SIZES { + if let Some(buf) = host.default_buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { + return Some((buf, bytes)); + } + } + None +} + +fn compile_prep( + device: &ID3D12Device, +) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> { + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: static HLSL source and entry strings live through the call; + // output pointers are ours. + let compiled = unsafe { + D3DCompile( + PREP_SOURCE.as_ptr().cast(), + PREP_SOURCE.len(), + s!("mesh_indirect_prep"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + let fallback; + let bytes: &[u8] = if compiled.is_ok() { + let code = code.as_ref().ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob owns its bytes. + unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + } + } else { + if let Some(errors) = errors { + // SAFETY: the blob owns its bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::info!( + "mesh_indirect_prep: system compiler refused it ({}); trying DXC", + String::from_utf8_lossy(text).trim() + ); + } + fallback = crate::indirect::dxc_compile(PREP_SOURCE).inspect_err(|e| { + tracing::warn!(error = %e, "mesh_indirect_prep: DXC failed too"); + })?; + &fallback + }; + // SAFETY: `bytes` is valid compiled shader bytecode with an embedded + // root signature, alive through pipeline creation. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = 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((root, pso)) + } +} + +fn make() -> Option { + let host = host()?; + let (output, output_bytes) = allocate_output(host)?; + let slot_map = + host.default_buffer(SLOT_MAP_BYTES, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)?; + let indirect_args = host.default_buffer( + INDIRECT_ARGS_BYTES, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + )?; + let (dummy_srv, dummy_ptr) = host.upload_buffer(256)?; + // SAFETY: `dummy_ptr` points to 256 writable bytes of the live upload buffer. + unsafe { std::ptr::write_bytes(dummy_ptr, 0, 256) }; + let prep = compile_prep(&host.device) + .inspect_err(|e| tracing::warn!(error = %e, "mesh_indirect_prep pipeline failed")) + .ok(); + let (prep_root, prep_pso) = (prep.as_ref().map(|p| p.0.clone()), prep.as_ref().map(|p| p.1.clone())); + name(&output, || format!("mesh emu output {output_bytes:#x}")); + name(&slot_map, || "mesh emu slot_map".into()); + name(&indirect_args, || "mesh emu indirect_args".into()); + name(&dummy_srv, || "mesh emu dummy_srv".into()); + // SAFETY: all are live buffer resources. + let (output_gpu, slot_map_gpu, indirect_args_gpu, dummy_srv_gpu) = unsafe { + ( + output.GetGPUVirtualAddress(), + slot_map.GetGPUVirtualAddress(), + indirect_args.GetGPUVirtualAddress(), + dummy_srv.GetGPUVirtualAddress(), + ) + }; + tracing::info!( + output_mb = output_bytes >> 20, + "mesh shader emulation buffers ready" + ); + Some(Buffers { + output, + output_gpu, + output_bytes, + slot_map, + slot_map_gpu, + indirect_args, + indirect_args_gpu, + dummy_srv, + dummy_srv_gpu, + prep_root, + prep_pso, + }) +} + +impl Buffers { + /// Maximum number of mesh thread groups that fit in `output` in one chunk. + pub(crate) fn group_cap(&self, group_bytes: u32) -> u32 { + (self.output_bytes / u64::from(group_bytes.max(4))).min(65_535) as u32 + } + + /// Compacts indirect mesh groups into host dispatch and draw arguments, + /// charges only the groups that fit in the output-buffer chunk, and writes + /// each compacted group's record-local id to `slot_map`. + /// Leaves `indirect_args` in `INDIRECT_ARGUMENT` and `slot_map` readable. + #[allow(clippy::too_many_arguments)] + pub(crate) fn prepare_indirect( + &self, + list: &HostList, + args_gpu: u64, + count_gpu: Option, + budget_gpu: u64, + stride: u32, + max_records: u32, + max_primitives: u32, + group_cap: u32, + ) -> bool { + let (Some(prep_root), Some(prep_pso)) = (&self.prep_root, &self.prep_pso) else { + return false; + }; + if max_records > MAX_INDIRECT_RECORDS + || group_cap == 0 + || stride < 12 + || !stride.is_multiple_of(4) + || u64::from(stride) * u64::from(max_records) > u64::from(u32::MAX) + || !args_gpu.is_multiple_of(4) + || count_gpu.is_some_and(|gpu| !gpu.is_multiple_of(4)) + || !budget_gpu.is_multiple_of(4) + { + return false; + } + let l = &list.list; + let build_map = max_records > 1; + let constants = [ + stride, + max_records, + max_primitives, + group_cap, + u32::from(count_gpu.is_some()), + u32::from(build_map), + ]; + // SAFETY: an open list; all GPU addresses name live buffers kept for + // the submission. + unsafe { + // No SRV clamp precedes this pass: source buffers stay in UAV + // state, and this barrier orders any title compute producer. + l.ResourceBarrier(&[uav_barrier()]); + l.SetComputeRootSignature(prep_root); + l.SetPipelineState(prep_pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootUnorderedAccessView(1, args_gpu); + l.SetComputeRootUnorderedAccessView(2, count_gpu.unwrap_or(args_gpu)); + l.SetComputeRootUnorderedAccessView(3, self.indirect_args_gpu); + l.SetComputeRootUnorderedAccessView(4, self.slot_map_gpu); + l.SetComputeRootUnorderedAccessView(5, budget_gpu); + l.Dispatch(1, 1, 1); + let args_barrier = transition( + &self.indirect_args, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ); + if build_map { + let map_barrier = transition( + &self.slot_map, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ); + l.ResourceBarrier(&[uav_barrier(), args_barrier, map_barrier]); + } else { + l.ResourceBarrier(&[uav_barrier(), args_barrier]); + } + } + true + } +} diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 28cabd63..b87d6c03 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -23,6 +23,7 @@ #[cfg(windows)] mod console_insn; +#[cfg(windows)] mod crash; pub mod prepare; pub mod resolve; diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 8f5407a9..470b1640 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -94,9 +94,11 @@ impl Host { if let Some(made) = &device { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; - if let Ok(adapter) = factory.EnumAdapterByLuid::(made.GetAdapterLuid()) + if let Ok(adapter) = + factory.EnumAdapterByLuid::(made.GetAdapterLuid()) && let Ok(desc) = adapter.GetDesc1() - && (desc.Flags & 2 != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) + && (desc.Flags & 2 != 0 + || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) { return Err("the default device is the software adapter".to_owned()); } @@ -143,6 +145,14 @@ impl Host { &self, stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], ) -> Result { + self.root_signature_with_extra(stages, &[]).map(|(r, _)| r) + } + + fn root_signature_with_extra( + &self, + stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], + extra: &[D3D12_ROOT_PARAMETER1], + ) -> Result<(ID3D12RootSignature, u32), String> { let mut params: Vec = stages .iter() .map(|&(s, vis)| D3D12_ROOT_PARAMETER1 { @@ -185,6 +195,8 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + let extra_base = params.len() as u32; + params.extend_from_slice(extra); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -221,7 +233,7 @@ impl Host { }, }; // SAFETY: the description points at live arrays. - unsafe { + let root = unsafe { let mut blob = None; let mut error = None; D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) @@ -231,8 +243,9 @@ impl Host { blob.GetBufferPointer().cast::(), blob.GetBufferSize(), ); - self.device.CreateRootSignature(0, bytes).map_err(err) - } + self.device.CreateRootSignature(0, bytes).map_err(err)? + }; + Ok((root, extra_base)) } /// A compute pipeline; user data is root parameter 0. @@ -280,7 +293,10 @@ impl Host { let message = buffer.as_mut_ptr().cast::(); if queue.GetMessage(i, Some(message), &mut len).is_ok() { let m = &*message; - let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1)); + let bytes = std::slice::from_raw_parts( + m.pDescription, + m.DescriptionByteLength.saturating_sub(1), + ); text.push_str(" | "); text.push_str(&String::from_utf8_lossy(bytes)); } @@ -353,9 +369,11 @@ impl Host { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len(), }, - GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE { - pShaderBytecode: gs.as_ptr().cast(), - BytecodeLength: gs.len(), + GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + } }), SampleMask: u32::MAX, RasterizerState: D3D12_RASTERIZER_DESC { @@ -507,6 +525,113 @@ impl Host { // SAFETY: the stream points at live data and outlives the call. unsafe { device.CreatePipelineState(&desc) }.map_err(err) } + + /// Whether the host supports hardware mesh shaders at shader model 6.6. + pub fn mesh_shaders(&self) -> bool { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: writes into `options` of its exact size. + unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + } + } + + /// Dual compute + unpack vertex/pixel pipelines for an emulated mesh shader. + pub fn emulated_mesh_pipelines( + &self, + ms: &HostShader, + ps: &HostShader, + ) -> Result { + let emu = ms + .mesh_emu + .as_ref() + .ok_or("mesh shader was not translated in emulation mode")?; + let mut cs_extra = vec![D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }]; + if emu.reads_group_id { + cs_extra.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + cs_extra.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + let (cs_root, cs_base) = + self.root_signature_with_extra(&[(ms, D3D12_SHADER_VISIBILITY_ALL)], &cs_extra)?; + let cs_pso = self.compute_pipeline_with(&cs_root, &ms.dxil)?; + + let unpack_vs = + super::unpack_vertex_shader(emu, Some(&ps.dxil)).map_err(|e| e.to_string())?; + let (gfx_root, gfx_srv_param) = self.root_signature_with_extra( + &[(ps, D3D12_SHADER_VISIBILITY_PIXEL)], + &[D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: super::MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, + }], + )?; + let gfx_pso = self.pipeline_with(&gfx_root, &unpack_vs, &ps.dxil)?; + + Ok(EmulatedMeshPipelines { + cs_root, + cs_pso, + gfx_root, + gfx_pso, + cs_uav_param: cs_base, + cs_cbv_param: emu.reads_group_id.then_some(cs_base + 1), + cs_srv_param: emu.reads_group_id.then_some(cs_base + 2), + gfx_srv_param, + }) + } +} + +/// Compute + unpack graphics pipelines built for an emulated mesh shader. +pub struct EmulatedMeshPipelines { + pub cs_root: ID3D12RootSignature, + pub cs_pso: ID3D12PipelineState, + pub gfx_root: ID3D12RootSignature, + pub gfx_pso: ID3D12PipelineState, + pub cs_uav_param: u32, + pub cs_cbv_param: Option, + pub cs_srv_param: Option, + pub gfx_srv_param: u32, } /// A vertex shader that feeds `ps`'s inputs (zeros) and a position. @@ -600,6 +725,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, } } @@ -1451,3 +1577,313 @@ impl Host { } } } + +/// Bindings for [`Host::draw_emulated_mesh`]. +#[cfg(test)] +pub struct EmulatedMeshDraw<'a> { + pub cs_roots: Vec<(u32, Root)>, + pub ps_roots: Vec<(u32, Root)>, + pub size: (u32, u32), + pub groups: u32, + pub max_primitives: u32, + pub group_bytes: u32, + pub base_group: u32, + pub slot_map: Option<&'a [u32]>, +} + +#[cfg(test)] +impl Host { + /// Runs an emulated mesh shader (`cs_6_6`) followed by its unpack `vs_6_6` + /// + `ps_6_6` draw into a cleared RGBA32F render target and returns texels. + pub fn draw_emulated_mesh( + &self, + pipes: &EmulatedMeshPipelines, + d: &EmulatedMeshDraw, + ) -> Result, String> { + let dev = &self.device; + let (w, h) = d.size; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // remain alive until the fence reports GPU completion. + unsafe { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .map_err(err)?; + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .map_err(err)?; + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pipes.cs_pso) + .map_err(err)?; + let tex_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let buf_desc = |size: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(4), + 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 make = |heap: D3D12_HEAP_TYPE, + desc: &D3D12_RESOURCE_DESC, + state, + clear: Option<&D3D12_CLEAR_VALUE>| { + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + desc, + state, + clear.map(|c| c as *const _), + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let target = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, + }), + )?; + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .map_err(err)?; + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&target, None, rtv); + let views: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let sampler_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + + let out_bytes = (u64::from(d.groups.max(1)) * u64::from(d.group_bytes.max(4))).max(256); + let output = make( + D3D12_HEAP_TYPE_DEFAULT, + &buf_desc(out_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + )?; + let map_words = d.slot_map.map_or(1, |m| m.len().max(1)); + let map_bytes = ((map_words * 4).next_multiple_of(256)) as u64; + let slot_map_buf = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(map_bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut mp = std::ptr::null_mut(); + slot_map_buf.Map(0, None, Some(&mut mp)).map_err(err)?; + std::ptr::write_bytes(mp, 0, map_bytes as usize); + if let Some(map) = d.slot_map { + std::ptr::copy_nonoverlapping(map.as_ptr(), mp.cast::(), map.len()); + } + slot_map_buf.Unmap(0, None); + + let mut keep = Vec::new(); + let upload_dwords = |data: &[u32]| -> Result { + let bytes = (data.len() * 4).next_multiple_of(256) as u64; + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping(data.as_ptr(), p.cast::(), data.len()); + b.Unmap(0, None); + Ok(b) + }; + + list.SetDescriptorHeaps(&[Some(views.clone()), Some(sampler_heap.clone())]); + list.SetComputeRootSignature(&pipes.cs_root); + for (param, arg) in &d.cs_roots { + match arg { + Root::Constants(data) => list.SetComputeRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::View { srv, data } => { + let b = upload_dwords(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetComputeRootShaderResourceView(*param, va); + } else { + list.SetComputeRootConstantBufferView(*param, va); + } + keep.push(b); + } + Root::Table { .. } => return Err("descriptor tables not supported here".into()), + } + } + list.SetComputeRootUnorderedAccessView( + pipes.cs_uav_param, + output.GetGPUVirtualAddress(), + ); + if let Some(p) = pipes.cs_cbv_param { + let c = [d.base_group, 0, 0, 0]; + list.SetComputeRoot32BitConstants(p, 4, c.as_ptr().cast(), 0); + } + if let Some(p) = pipes.cs_srv_param { + list.SetComputeRootShaderResourceView(p, slot_map_buf.GetGPUVirtualAddress()); + } + list.Dispatch(d.groups, 1, 1); + + list.ResourceBarrier(&[transition( + &output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + list.SetPipelineState(&pipes.gfx_pso); + list.SetGraphicsRootSignature(&pipes.gfx_root); + for (param, arg) in &d.ps_roots { + match arg { + Root::Constants(data) => list.SetGraphicsRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::View { srv, data } => { + let b = upload_dwords(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetGraphicsRootShaderResourceView(*param, va); + } else { + list.SetGraphicsRootConstantBufferView(*param, va); + } + keep.push(b); + } + Root::Table { .. } => return Err("descriptor tables not supported here".into()), + } + } + list.SetGraphicsRootShaderResourceView( + pipes.gfx_srv_param, + output.GetGPUVirtualAddress(), + ); + list.ClearRenderTargetView(rtv, &[0.0; 4], None); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: w as f32, + Height: h as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + right: w as i32, + bottom: h as i32, + ..Default::default() + }]); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.DrawInstanced(d.groups * d.max_primitives * 3, 1, 0, 0); + + list.ResourceBarrier(&[transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let pitch = (w as usize * 16).next_multiple_of(256); + let readback = make( + D3D12_HEAP_TYPE_READBACK, + &buf_desc((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: w, + Height: h, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + queue.Signal(&fence, 1).map_err(err)?; + while fence.GetCompletedValue() < 1 { + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + std::thread::yield_now(); + } + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(err)?; + let mut out = Vec::with_capacity((w * h) as usize); + for y in 0..h as usize { + let row = std::slice::from_raw_parts( + p.cast::().add(y * pitch).cast::<[f32; 4]>(), + w as usize, + ); + out.extend_from_slice(row); + } + readback.Unmap(0, None); + drop(keep); + Ok(out) + } + } +} diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index 0266579a..6f40cb91 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -177,6 +177,7 @@ fn build( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -188,6 +189,7 @@ fn build( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -680,6 +682,7 @@ fn a_structure_that_returns_triangle_ids_is_refused_by_name() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, }); match r { Err(ShaderError::Unsupported { what, .. }) => { diff --git a/crates/victory-shader/src/emit/lower/code_table_tests.rs b/crates/victory-shader/src/emit/lower/code_table_tests.rs new file mode 100644 index 00000000..268e4b54 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/code_table_tests.rs @@ -0,0 +1,26 @@ +// Tests for where a program's constant table starts. + +use crate::{ir, resource}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// A program's constant table starts after its instructions, unless a +/// load at a fixed offset reads below that. +#[test] +fn the_code_table_starts_after_the_instructions() { + // s_nop 0, s_endpgm, then 1,000 dwords of constants. + let mut words = vec![0xBF80_0000, S_ENDPGM]; + words.extend(0..1000u32); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = ir::build(&code, false, 256).unwrap(); + let at = |offset: u32, dynamic: bool| resource::Address { + param: resource::CODE, + offset, + dynamic: dynamic.then_some(ir::Value(0)), + }; + let (computed, fixed_after, fixed_inside) = (at(0, true), at(12, false), at(4, false)); + assert_eq!(code_table_start(&p, &[&computed], 0), 8); + assert_eq!(code_table_start(&p, &[&computed, &fixed_after], 0), 8); + assert_eq!(code_table_start(&p, &[&computed, &fixed_inside], 0), 0); + assert_eq!(code_table_start(&p, &[&fixed_after], 12), 12); +} diff --git a/crates/victory-shader/src/emit/lower/mesh_emulation.rs b/crates/victory-shader/src/emit/lower/mesh_emulation.rs new file mode 100644 index 00000000..d7876d65 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/mesh_emulation.rs @@ -0,0 +1,137 @@ +// Included by lower.rs: mesh emulation setup methods. + +struct MeshEmuVals { + uav: V, + local_group: V, + group_base: V, + flat_lt_verts: Option, + flat_lt_prims: Option, + index_bytes: u32, + vertex_stride_bytes: u32, + prim_offset_bytes: u32, + prim_stride_bytes: u32, +} + +struct MeshEmuState { + threads: u32, + max_vertices: u32, + max_primitives: u32, + topology: u8, + vertex_sigs: Vec, + vertex_offsets: Vec, + vertex_dwords: u32, + prim_sigs: Vec, + prim_offsets: Vec, + prim_dwords: u32, + reads_group_id: bool, + vals: Option, +} + +fn pack_offsets(sigs: &[SigElement]) -> (Vec, u32) { + let mut offsets = Vec::with_capacity(sigs.len()); + let mut next = 0u32; + for e in sigs { + offsets.push(next); + next += u32::from(e.cols); + } + (offsets, next) +} + +impl Lower<'_> { + fn mesh_emu_init(&mut self) -> Result<(), Why> { + let (threads, raw_verts, raw_prims, topology, vertex_dwords, prim_dwords) = { + let m = self.mesh_emu.as_ref().expect("mesh emu"); + ( + m.threads, + m.max_vertices, + m.max_primitives, + m.topology, + m.vertex_dwords, + m.prim_dwords, + ) + }; + if topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads == 0 || threads > 1024 || raw_verts > 256 || raw_prims > 256 { + return Err("a mesh shader beyond the host's limits"); + } + let max_vertices = raw_verts.min(threads); + let max_primitives = raw_prims.min(threads); + if max_vertices == 0 || max_primitives == 0 { + return Err("an empty mesh shader output"); + } + let index_bytes = max_primitives * 4; + let vertex_stride_bytes = vertex_dwords * 4; + let prim_offset_bytes = index_bytes + max_vertices * vertex_stride_bytes; + let prim_stride_bytes = prim_dwords * 4; + let group_bytes = prim_offset_bytes + max_primitives * prim_stride_bytes; + + let e = self.s.entry; + let i32t = self.s.t.i32; + let uav = self.s.emu_uav_handle(); + let k0 = self.s.m.i32(0); + let local_group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[k0]); + let flat = self.mesh_thread(); + let group_stride = self.s.m.i32(group_bytes); + let group_base = self.s.m.bin(e, Bin::Mul, local_group, group_stride); + let flat_lt_verts = (threads > max_vertices).then(|| { + let mv = self.s.m.i32(max_vertices); + self.s.m.cmp(e, pred::IULT, flat, mv) + }); + let flat_lt_prims = (threads > max_primitives).then(|| { + let mp = self.s.m.i32(max_primitives); + self.s.m.cmp(e, pred::IULT, flat, mp) + }); + let m = self.mesh_emu.as_mut().expect("mesh emu"); + m.max_vertices = max_vertices; + m.max_primitives = max_primitives; + m.vals = Some(MeshEmuVals { + uav, + local_group, + group_base, + flat_lt_verts, + flat_lt_prims, + index_bytes, + vertex_stride_bytes, + prim_offset_bytes, + prim_stride_bytes, + }); + Ok(()) + } + + /// Initializes every primitive index word in the group slice as culled + /// (`bit 31 = 1`) so unexported slots never draw stale data. + fn mesh_emu_prologue(&mut self) { + let (uav, group_base, flat_lt_prims) = { + let v = self + .mesh_emu + .as_ref() + .expect("mesh emu") + .vals + .as_ref() + .expect("mesh emu init"); + (v.uav, v.group_base, v.flat_lt_prims) + }; + let flat = self.mesh_thread(); + let at = self.begin_guarded(flat_lt_prims); + let c = self.cur; + let k2 = self.s.m.i32(2); + let byte_off = self.s.m.bin(c, Bin::Shl, flat, k2); + let addr = self.s.m.bin(c, Bin::Add, group_base, byte_off); + let undef = self.s.m.undef(self.s.t.i32); + let culled = self.s.m.i32(0x8000_0000); + let mask1 = self.s.m.i8(1); + let align4 = self.s.m.i32(4); + let void = self.s.t.void; + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[uav, addr, undef, culled, undef, undef, undef, mask1, align4], + ); + self.end_guarded(at, &[]); + } +} diff --git a/crates/victory-shader/src/emit/mesh_emu.rs b/crates/victory-shader/src/emit/mesh_emu.rs new file mode 100644 index 00000000..45533b4e --- /dev/null +++ b/crates/victory-shader/src/emit/mesh_emu.rs @@ -0,0 +1,1329 @@ +//! Mesh shader emulation (`cs_6_6` + generated unpack `vs_6_6`) for SM 6.6 +//! GPUs that lack hardware mesh shaders (`D3D12_MESH_SHADER_TIER_NOT_SUPPORTED`). +//! +//! An emulated mesh program (`MeshMode::Emulate`) compiles as a compute shader +//! (`cs_6_6`) with the console's `[numthreads(threads, 1, 1)]` and LDS, writing +//! packed primitive indices, per-vertex attributes (`OSG1`), and per-primitive +//! attributes (`PSG1`) into a fixed-stride per-group slice of a raw UAV buffer +//! at `u0, space 2` ([`super::shader::MESH_EMU_SPACE`]): +//! +//! ```text +//! group g (byte offset = g * group_bytes): +//! [0 .. index_bytes) max_primitives x u32 (v0 | v1<<10 | v2<<20 | cull<<31) +//! [index_bytes .. prim_offset_bytes) max_vertices x vertex_dwords x u32 +//! [prim_offset_bytes .. group_bytes) max_primitives x prim_dwords x u32 +//! ``` +//! +//! [`unpack_vertex_shader`] builds the matching `vs_6_6` that reads that raw +//! buffer at `t0, space 2` by `SV_VertexID`, culls bit-31 primitives via quiet +//! `NaN` on `SV_Position`, and emits every vertex and per-primitive attribute in +//! the exact signature layout the title's pixel shader (`ps_6_6`) expects. + +use std::collections::BTreeMap; + +use super::bitcode::{Attr, Bin, Cast, Term, pred}; +use super::container::SigElement; +use super::shader::Shader; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC, u32_at}; + +/// Sentinel `base_group` value in `b0, space 2` telling an emulated mesh +/// compute shader that reads `SV_GroupID` to look up its per-record group ID +/// in the `slot_map` raw SRV (`t0, space 2`). +pub const INDIRECT_SLOT_MAP_FLAG: u32 = u32::MAX; + +/// Whether a console mesh shader (`HwStage::Ms`) translates to native `ms_6_6` +/// or to a compute + vertex emulation pair. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum MeshMode { + #[default] + Native, + Emulate, +} + +/// One vertex or per-primitive attribute stored in the emulated mesh buffer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshOutput { + pub name: String, + pub index: u32, + pub kind: u8, + pub comp: u8, + pub interp: u8, + pub row: Option, + pub col: u8, + pub cols: u8, + /// Dword offset of channel 0 from the start of a vertex or primitive record. + pub dword_offset: u32, +} + +/// Memory layout and metadata emitted by an emulated mesh compute shader. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshEmu { + pub threads: u32, + pub max_vertices: u32, + pub max_primitives: u32, + pub vertex_dwords: u32, + pub prim_dwords: u32, + pub reads_group_id: bool, + pub vertex_outputs: Vec, + pub prim_outputs: Vec, +} + +impl MeshEmu { + /// Bytes reserved per group for packed primitive index words. + pub fn index_bytes(&self) -> u32 { + self.max_primitives * 4 + } + + /// Byte offset of vertex attribute records within one group slice. + pub fn vertex_offset_bytes(&self) -> u32 { + self.index_bytes() + } + + /// Stride in bytes of one vertex record. + pub fn vertex_stride_bytes(&self) -> u32 { + self.vertex_dwords * 4 + } + + /// Byte offset of per-primitive attribute records within one group slice. + pub fn prim_offset_bytes(&self) -> u32 { + self.index_bytes() + self.max_vertices * self.vertex_stride_bytes() + } + + /// Stride in bytes of one per-primitive record. + pub fn prim_stride_bytes(&self) -> u32 { + self.prim_dwords * 4 + } + + /// Total bytes occupied by one threadgroup in the intermediate buffer. + pub fn group_bytes(&self) -> u32 { + self.prim_offset_bytes() + self.max_primitives * self.prim_stride_bytes() + } +} + +#[derive(Clone, Copy)] +enum OutputSource { + Vertex { dword_offset: u32, avail_cols: u8 }, + Prim { dword_offset: u32, avail_cols: u8 }, + Zero, +} + +struct UnpackOutput { + sig: SigElement, + src: OutputSource, +} + +/// Generates a `vs_6_6` DXIL container that unpacks `emu`'s raw buffer (`t0, +/// space 2`) by `SV_VertexID` into the input signature expected by `ps_dxil` +/// (or rasterizer system values only for depth-only pipelines). +pub fn unpack_vertex_shader(emu: &MeshEmu, ps_dxil: Option<&[u8]>) -> Result, ShaderError> { + if emu.max_vertices == 0 || emu.max_primitives == 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "an empty mesh shader output", + }); + } + + let plan = build_output_plan(emu, ps_dxil)?; + + let mut s = Shader::new(false); + s.inputs = vec![SigElement { + name: "SV_VertexID".into(), + index: 0, + kind: 1, + comp: 5, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }]; + s.outputs = plan.iter().map(|o| o.sig.clone()).collect(); + + let buf = s.emu_srv_handle(); + let e = s.entry; + let i32t = s.t.i32; + let undef_i32 = s.m.undef(i32t); + let vid = { + let zero = s.m.i32(0); + let z8 = s.m.i8(0); + s.op( + e, + "loadInput.i32", + Attr::ReadNone, + i32t, + 4, + &[zero, zero, z8, undef_i32], + ) + }; + + let k3 = s.m.i32(3); + let tri = s.m.bin(e, Bin::UDiv, vid, k3); + let corner = s.m.bin(e, Bin::URem, vid, k3); + let (group_idx, prim_idx) = if emu.max_primitives == 1 { + (tri, s.m.i32(0)) + } else { + let mp = s.m.i32(emu.max_primitives); + ( + s.m.bin(e, Bin::UDiv, tri, mp), + s.m.bin(e, Bin::URem, tri, mp), + ) + }; + + let group_stride = s.m.i32(emu.group_bytes()); + let group_base = s.m.bin(e, Bin::Mul, group_idx, group_stride); + let k2 = s.m.i32(2); + let prim_byte = s.m.bin(e, Bin::Shl, prim_idx, k2); + let idx_off = s.m.bin(e, Bin::Add, group_base, prim_byte); + + let idx_load = { + let mask1 = s.m.i8(1); + let align4 = s.m.i32(4); + s.op( + e, + "rawBufferLoad.f32", + Attr::ReadOnly, + s.t.res_ret, + 139, + &[buf, idx_off, undef_i32, mask1, align4], + ) + }; + let idx_f = s.m.extract(e, idx_load, 0); + let packed = s.m.cast(e, Cast::Bitcast, idx_f, i32t); + let zero_i = s.m.i32(0); + let culled = s.m.cmp(e, pred::SLT, packed, zero_i); + + let cull_bb = s.m.new_block(); + let draw_bb = s.m.new_block(); + s.m.terminate(e, Term::CondBr(culled, cull_bb, draw_bb)); + + // Culled primitive: write quiet NaN to SV_Position so the rasterizer drops + // the triangle regardless of depth-clip settings, and zero other outputs. + for (id, out) in plan.iter().enumerate() { + for c in 0..out.sig.cols { + let (suffix, val) = if out.sig.kind == 3 { + (".f32", s.m.f32(0x7FC0_0000)) + } else if out.sig.comp == 9 { + (".f32", s.m.f32(0)) + } else { + (".i32", zero_i) + }; + let id_k = s.m.i32(id as u32); + let col_k = s.m.i8(c); + s.op( + cull_bb, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &[id_k, zero_i, col_k, val], + ); + } + } + s.m.terminate(cull_bb, Term::Ret); + + // Active primitive: load vertex and/or per-primitive attributes and store them. + let needs_vert = plan + .iter() + .any(|o| matches!(o.src, OutputSource::Vertex { .. })); + let needs_prim = plan + .iter() + .any(|o| matches!(o.src, OutputSource::Prim { .. })); + + let v_base = if needs_vert { + let k10 = s.m.i32(10); + let shift = s.m.bin(draw_bb, Bin::Mul, corner, k10); + let shifted = s.m.bin(draw_bb, Bin::LShr, packed, shift); + let mask = s.m.i32(0x3FF); + let v_raw = s.m.bin(draw_bb, Bin::And, shifted, mask); + let mv = s.m.i32(emu.max_vertices); + let in_bounds = s.m.cmp(draw_bb, pred::IULT, v_raw, mv); + let last_v = s.m.i32(emu.max_vertices - 1); + let v_idx = s.m.select(draw_bb, in_bounds, v_raw, last_v); + let v_stride = s.m.i32(emu.vertex_stride_bytes()); + let v_rel = s.m.bin(draw_bb, Bin::Mul, v_idx, v_stride); + let v_off_base = s.m.i32(emu.vertex_offset_bytes()); + let v_off = s.m.bin(draw_bb, Bin::Add, v_off_base, v_rel); + Some(s.m.bin(draw_bb, Bin::Add, group_base, v_off)) + } else { + None + }; + + let p_base = if needs_prim { + let p_stride = s.m.i32(emu.prim_stride_bytes()); + let p_rel = s.m.bin(draw_bb, Bin::Mul, prim_idx, p_stride); + let p_off_base = s.m.i32(emu.prim_offset_bytes()); + let p_off = s.m.bin(draw_bb, Bin::Add, p_off_base, p_rel); + Some(s.m.bin(draw_bb, Bin::Add, group_base, p_off)) + } else { + None + }; + + let zero_f = s.m.f32(0); + let align4 = s.m.i32(4); + for (id, out) in plan.iter().enumerate() { + let (base, dword_offset, avail_cols) = match out.src { + OutputSource::Vertex { + dword_offset, + avail_cols, + } => (v_base.expect("vertex base"), dword_offset, avail_cols), + OutputSource::Prim { + dword_offset, + avail_cols, + } => (p_base.expect("prim base"), dword_offset, avail_cols), + OutputSource::Zero => { + for c in 0..out.sig.cols { + let (suffix, val) = if out.sig.comp == 9 { + (".f32", zero_f) + } else { + (".i32", zero_i) + }; + let id_k = s.m.i32(id as u32); + let col_k = s.m.i8(c); + s.op( + draw_bb, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &[id_k, zero_i, col_k, val], + ); + } + continue; + } + }; + + let load_cols = out.sig.cols.min(avail_cols).min(4); + let loaded = if load_cols > 0 { + let addr = if dword_offset == 0 { + base + } else { + let disp = s.m.i32(dword_offset * 4); + s.m.bin(draw_bb, Bin::Add, base, disp) + }; + let mask = s.m.i8((1u8 << load_cols) - 1); + Some(s.op( + draw_bb, + "rawBufferLoad.f32", + Attr::ReadOnly, + s.t.res_ret, + 139, + &[buf, addr, undef_i32, mask, align4], + )) + } else { + None + }; + + for c in 0..out.sig.cols { + let (suffix, val) = match loaded { + Some(agg) if c < load_cols => { + let f = s.m.extract(draw_bb, agg, u32::from(c)); + if out.sig.comp == 9 { + (".f32", f) + } else { + (".i32", s.m.cast(draw_bb, Cast::Bitcast, f, i32t)) + } + } + _ if out.sig.comp == 9 => (".f32", zero_f), + _ => (".i32", zero_i), + }; + let id_k = s.m.i32(id as u32); + let col_k = s.m.i8(c); + s.op( + draw_bb, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &[id_k, zero_i, col_k, val], + ); + } + } + s.m.terminate(draw_bb, Term::Ret); + Ok(s.finish()) +} + +fn build_output_plan( + emu: &MeshEmu, + ps_dxil: Option<&[u8]>, +) -> Result, ShaderError> { + let mut plan = Vec::new(); + let mut occupied: BTreeMap = BTreeMap::new(); + let mut next_row: u32 = 0; + + fn occupy(occupied: &mut BTreeMap, next_row: &mut u32, row: u32, col: u8, cols: u8) { + let mask = ((1u8 << cols.min(4)) - 1) << col.min(3); + *occupied.entry(row).or_default() |= mask; + *next_row = (*next_row).max(row + 1); + } + + let mut emitted_sys: Vec<(u8, u32)> = Vec::new(); + + if let Some(ps_bytes) = ps_dxil { + let c = Container::parse(ps_bytes)?; + let ps_inputs = match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + }; + let ps_interps = c + .part(FourCC::PSV0) + .map(|p| psv_input_interps(p.data)) + .unwrap_or_default(); + + for pi in &ps_inputs { + if !matches!(pi.kind, 0 | 3 | 4 | 5 | 6 | 7) { + continue; + } + let (found, from_prim) = match find_mesh_output(&emu.vertex_outputs, pi) { + Some(o) => (Some(o), false), + None => match find_mesh_output(&emu.prim_outputs, pi) { + Some(o) => (Some(o), true), + None => (None, false), + }, + }; + let row = pi.row.unwrap_or(next_row); + let (col, cols) = if pi.kind == 3 { + (0, 4) + } else { + (pi.col, pi.cols) + }; + let src = match found { + Some(o) if pi.kind == 3 => OutputSource::Vertex { + dword_offset: o.dword_offset, + avail_cols: o.cols, + }, + Some(o) if col >= o.col && (col - o.col) < o.cols => { + let skip = u32::from(col - o.col); + let avail_cols = o.cols - skip as u8; + let dword_offset = o.dword_offset + skip; + if from_prim { + OutputSource::Prim { + dword_offset, + avail_cols, + } + } else { + OutputSource::Vertex { + dword_offset, + avail_cols, + } + } + } + _ => OutputSource::Zero, + }; + + let ps_interp = ps_interps + .iter() + .find(|&&(r, c, k, _)| r == row && c == pi.col && k == pi.kind) + .map(|&(_, _, _, m)| m) + .unwrap_or(0); + let interp = match pi.kind { + 3 => 4, + 4 | 5 => 1, + 6 | 7 => 2, + _ => match ps_interp { + 1 => 1, + 2 | 3 | 6 => 2, + 4 | 5 | 7 => 4, + _ if from_prim => 1, + _ if pi.comp == 9 => 2, + _ => 1, + }, + }; + + if pi.kind != 0 { + emitted_sys.push((pi.kind, pi.index)); + } + occupy(&mut occupied, &mut next_row, row, col, cols); + plan.push(UnpackOutput { + sig: SigElement { + name: pi.name.clone(), + index: pi.index, + kind: pi.kind, + comp: pi.comp, + interp, + row: Some(row), + col, + cols, + usage: (1u8 << cols) - 1, + half: false, + }, + src, + }); + } + } + + for (outputs, from_prim) in [(&emu.vertex_outputs, false), (&emu.prim_outputs, true)] { + for o in outputs { + if !matches!(o.kind, 3..=7) { + continue; + } + if emitted_sys.contains(&(o.kind, o.index)) { + continue; + } + emitted_sys.push((o.kind, o.index)); + let mask = ((1u8 << o.cols.min(4)) - 1) << o.col.min(3); + let (row, col) = match o.row { + Some(r) if (occupied.get(&r).copied().unwrap_or(0) & mask) == 0 => (r, o.col), + _ => (next_row, 0), + }; + occupy(&mut occupied, &mut next_row, row, col, o.cols); + let interp = match o.kind { + 3 => 4, + 4 | 5 => 1, + _ if from_prim => 1, + _ => 2, + }; + let src = if from_prim { + OutputSource::Prim { + dword_offset: o.dword_offset, + avail_cols: o.cols, + } + } else { + OutputSource::Vertex { + dword_offset: o.dword_offset, + avail_cols: o.cols, + } + }; + plan.push(UnpackOutput { + sig: SigElement { + name: o.name.clone(), + index: o.index, + kind: o.kind, + comp: o.comp, + interp, + row: Some(row), + col, + cols: o.cols, + usage: (1u8 << o.cols) - 1, + half: false, + }, + src, + }); + } + } + + if !plan.iter().any(|o| o.sig.kind == 3) { + let row = next_row; + plan.push(UnpackOutput { + sig: SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(row), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }, + src: OutputSource::Zero, + }); + } + + Ok(plan) +} + +fn find_mesh_output<'a>(outputs: &'a [MeshOutput], pi: &SigElement) -> Option<&'a MeshOutput> { + let matches = |o: &&MeshOutput| { + if pi.kind != 0 { + o.kind == pi.kind && o.index == pi.index + } else { + o.kind == 0 && o.index == pi.index && o.name.eq_ignore_ascii_case(&pi.name) + } + }; + outputs + .iter() + .find(|o| matches(o) && o.col == pi.col) + .or_else(|| outputs.iter().find(matches)) +} + +/// Reads `(row, col, kind, interp)` tuples for `PSV0` input signature elements. +fn psv_input_interps(psv: &[u8]) -> Vec<(u32, u8, u8, u8)> { + let Ok(info_size) = u32_at(psv, 0).map(|n| n as usize) else { + return Vec::new(); + }; + if info_size < 32 || psv.len() < 4 + info_size { + return Vec::new(); + } + let input_count = usize::from(psv[4 + 28]); + let mut at = 4 + info_size; + let Ok(binding_count) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if binding_count > 0 { + let Ok(entry_size) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + at = match binding_count + .checked_mul(entry_size) + .and_then(|n| at.checked_add(n)) + { + Some(next) if next <= psv.len() => next, + _ => return Vec::new(), + }; + } + let Ok(string_bytes) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if at + string_bytes > psv.len() { + return Vec::new(); + } + at += string_bytes; + let Ok(indices_count) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if at + indices_count * 4 > psv.len() { + return Vec::new(); + } + at += indices_count * 4; + if at + 4 > psv.len() { + return Vec::new(); + } + let Ok(elem_size) = u32_at(psv, at).map(|n| n as usize) else { + return Vec::new(); + }; + at += 4; + if elem_size < 14 { + return Vec::new(); + } + let mut out = Vec::new(); + for k in 0..input_count { + let Some(e) = psv.get(at + k * elem_size..at + (k + 1) * elem_size) else { + break; + }; + let alloc = e[10]; + if alloc & 0x40 == 0 { + continue; + } + let row = u32::from(e[9]); + let col = (alloc >> 4) & 3; + let kind = e[11]; + let interp = e[13]; + out.push((row, col, kind, interp)); + } + out +} + +#[cfg(all(test, windows))] +mod tests { + use super::super::validator::Validator; + use super::*; + + fn fake_ps_container(inputs: &[SigElement]) -> Vec { + let mut s = Shader::new(true); + s.inputs = inputs.to_vec(); + s.outputs = vec![SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }]; + let b = s.entry; + let zero = s.m.f32(0); + for c in 0..4u8 { + let zero_i = s.m.i32(0); + let col_k = s.m.i8(c); + s.op( + b, + "storeOutput.f32", + Attr::NoUnwind, + s.t.void, + 5, + &[zero_i, zero_i, col_k, zero], + ); + } + s.m.terminate(b, Term::Ret); + s.finish() + } + + #[test] + fn unpack_vs_signature_matches_ps_with_per_primitive_outputs() { + let emu = MeshEmu { + threads: 32, + max_vertices: 16, + max_primitives: 8, + vertex_dwords: 8, + prim_dwords: 4, + reads_group_id: false, + vertex_outputs: vec![ + MeshOutput { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 0, + }, + MeshOutput { + name: "COLOR".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(1), + col: 0, + cols: 4, + dword_offset: 4, + }, + ], + prim_outputs: vec![MeshOutput { + name: "PRIMDATA".into(), + index: 0, + kind: 0, + comp: 9, + interp: 1, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 0, + }], + }; + + // PS places COLOR0 at row 0 (colliding with MS SV_Position row 0!) + // and PRIMDATA at row 1, without reading SV_Position. + let ps = fake_ps_container(&[ + SigElement { + name: "COLOR".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }, + SigElement { + name: "PRIMDATA".into(), + index: 0, + kind: 0, + comp: 9, + interp: 1, + row: Some(1), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }, + ]); + + let mut vs = unpack_vertex_shader(&emu, Some(&ps)).unwrap(); + let c = Container::parse(&vs).unwrap(); + let osg1 = super::super::signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(osg1.len(), 3); + assert_eq!(osg1[0].name, "COLOR"); + assert_eq!(osg1[0].row, Some(0)); + assert_eq!(osg1[1].name, "PRIMDATA"); + assert_eq!(osg1[1].row, Some(1)); + assert_eq!(osg1[2].name, "SV_Position"); + assert_eq!(osg1[2].row, Some(2)); + assert_eq!( + psv_input_interps(c.part(FourCC::PSV0).unwrap().data), + vec![(0, 0, 1, 0)] + ); + let ps_c = Container::parse(&ps).unwrap(); + assert_eq!( + psv_input_interps(ps_c.part(FourCC::PSV0).unwrap().data), + vec![(0, 0, 0, 2), (1, 0, 0, 1)] + ); + + // Depth-only pipeline (ps == None) still emits SV_Position. + let mut depth_vs = unpack_vertex_shader(&emu, None).unwrap(); + let dc = Container::parse(&depth_vs).unwrap(); + let dosg = super::super::signature(dc.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(dosg.len(), 1); + assert_eq!(dosg[0].kind, 3); + + if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { + v.validate(&mut vs).unwrap(); + v.validate(&mut depth_vs).unwrap(); + } + } + + use super::super::host::{EmulatedMeshDraw, Host}; + use super::super::{HostShader, emit_with}; + use crate::native::{HwStage, MeshIo, NativeProgram, PsInput, StageIo, Usage, VsOutput}; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + const S_BARRIER: u32 = 0xBF8A_0000; + + const fn sgpr(n: u8) -> u16 { + n as u16 + } + + const fn vgpr(n: u8) -> u16 { + 256 + n as u16 + } + + const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop1_lit(op: u16, vdst: u8, lit: u32) -> [u32; 2] { + [vop1(op, vdst, 0xFF), lit] + } + + const fn vop2(op: u16, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vopc(op: u16, src0: u16, vsrc1: u8) -> u32 { + 0x7C00_0000 | (op as u32 & 0xFF) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + ] + } + + const fn ds(op: u8, vdst: u8, vaddr: u8, vdata0: u8, vdata1: u8, offset: u16) -> [u32; 2] { + [ + 0xD800_0000 | (op as u32) << 18 | offset as u32, + (vdst as u32) << 24 | (vdata1 as u32) << 16 | (vdata0 as u32) << 8 | vaddr as u32, + ] + } + + const fn exp(target: u8, en: u8, v: [u8; 4], done: bool, vm: bool) -> [u32; 2] { + [ + 0x3E << 26 + | (vm as u32) << 12 + | (done as u32) << 11 + | (target as u32 & 0x3F) << 4 + | (en as u32 & 0xF), + (v[0] as u32) | (v[1] as u32) << 8 | (v[2] as u32) << 16 | (v[3] as u32) << 24, + ] + } + + const fn v_interp_mov_f32(vdst: u8, attr: u8, chan: u8) -> u32 { + 0xC800_0000 | (vdst as u32) << 18 | 2 << 16 | (attr as u32) << 10 | (chan as u32) << 8 | 2 + } + + fn sig_el(name: &str, kind: u8, comp: u8, row: Option, usage: u8) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row, + col: 0, + cols: 4, + usage, + half: false, + } + } + + fn compile_ms( + words: &[u32], + io_outputs: Vec, + osg1: &[SigElement], + psg1: &[SigElement], + (threads, max_vertices, max_primitives, lds_bytes): (u32, u32, u32, u32), + ) -> HostShader { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 32, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Ms(MeshIo { + outputs: io_outputs, + clip_cntl: 0, + threads, + max_vertices, + max_primitives, + topology: 2, + lds_bytes, + }), + code, + }; + let osg_bytes = super::super::container::signature(osg1, false); + let psg_bytes = super::super::container::signature(psg1, false); + let container_bytes = + crate::dxbc::build(&[(FourCC::OSG1, &osg_bytes), (FourCC::PSG1, &psg_bytes)]); + let c = Container::parse(&container_bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let raised = io::raise(&p, &native).unwrap(); + let shader = emit_with(&c, &native, &p, &st, &raised, &res, MeshMode::Emulate).unwrap(); + if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("emulated mesh CS validation failed"); + } + shader + } + + fn compile_flat_ps(semantic_name: &str) -> HostShader { + let words = [ + v_interp_mov_f32(0, 0, 0), + v_interp_mov_f32(1, 0, 1), + v_interp_mov_f32(2, 0, 2), + v_interp_mov_f32(3, 0, 3), + exp(0, 0xF, [0, 1, 2, 3], true, true)[0], + exp(0, 0xF, [0, 1, 2, 3], true, true)[1], + S_ENDPGM, + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0xF, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: Vec::new(), + }, + code, + }; + let isg1 = + super::super::container::signature(&[sig_el(semantic_name, 0, 9, Some(0), 0xF)], true); + let osg1 = + super::super::container::signature(&[sig_el("SV_Target", 16, 9, Some(0), 0xF)], false); + let container_bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&container_bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let raised = io::raise(&p, &native).unwrap(); + let shader = emit_with(&c, &native, &p, &st, &raised, &res, MeshMode::Emulate).unwrap(); + if let Ok(mut v) = Validator::load(Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("PS validation failed"); + } + shader + } + + fn run_on_hosts(mut f: impl FnMut(&str, &Host)) { + let _one = super::super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + ran += 1; + f(label, &host); + } + assert!( + ran > 0 || std::env::var("CI").is_err(), + "no SM 6.6 host available" + ); + } + + #[test] + fn emulated_mesh_draws_triangle_and_culls_bit31_and_unexported() { + let build_variant = |cull_prim0: bool| { + let mut words = Vec::new(); + // v0 = tid (0..7) + words.extend(vop3(0x365, 0, 193, 128, 0)); + // Default position: (-1, -1, 0.5, 1.0) + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + // Default color: RED (1, 0, 0, 1); scratch constants v10=3.0, v11=1.0, v12=0.0 + words.extend(vop1_lit(0x001, 5, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); + words.extend(vop1_lit(0x001, 11, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 12, 0.0f32.to_bits())); + // tid == 1 or tid == 4 -> pos.x = 3.0 + words.push(vopc(0x0C2, 129, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + words.push(vopc(0x0C2, 132, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + // tid == 2 or tid == 5 -> pos.y = 3.0 + words.push(vopc(0x0C2, 130, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + words.push(vopc(0x0C2, 133, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + // tid >= 3 (3 <= tid, i.e., 3 < tid + 1 or 2 < tid) -> green (0, 1, 0, 1) + words.push(vopc(0x0C1, 130, 0)); // 2 < v0 + words.push(vop2(0x001, 5, vgpr(5), 12)); + words.push(vop2(0x001, 6, vgpr(6), 11)); + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + // v9 = (3 | 4<<10 | 5<<20) | 0x8000_0000 (bit-31 culled green tri) + words.extend(vop1_lit(0x001, 9, 0x8050_1003)); + if !cull_prim0 { + words.extend(vop1_lit(0x001, 13, 0x0020_0400)); + words.push(vopc(0x0C2, 128, 0)); // v0 == 0 + words.push(vop2(0x001, 9, vgpr(9), 13)); + } + // Only tid < 2 (2 > v0) exports `exp prim`; slot 2 relies on prologue cull. + words.push(vopc(0x0C4, 130, 0)); // 2 > v0 + words.push(0xBE80_3C6A); // s_and_saveexec_b32 s0, vcc_lo + words.push(0xBF88_0002); // s_cbranch_execz +2 + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(0x887E_007E); // s_or_b32 exec_lo, exec_lo, s0 + words.push(S_ENDPGM); + + compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0, + fp16: false, + pack2: false, + }], + &[ + sig_el("SV_Position", 3, 9, None, 0xF), + sig_el("COLOR", 0, 9, Some(0), 0xF), + ], + &[], + (8, 6, 3, 0), + ) + }; + + let ms_active = build_variant(false); + let ms_culled = build_variant(true); + let ps = compile_flat_ps("COLOR"); + let emu_active = ms_active.mesh_emu.as_ref().unwrap().clone(); + let emu_culled = ms_culled.mesh_emu.as_ref().unwrap().clone(); + + run_on_hosts(|label, host| { + let pipes_active = host.emulated_mesh_pipelines(&ms_active, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes_active, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu_active.max_primitives, + group_bytes: emu_active.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: active draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [1.0, 0.0, 0.0, 1.0]), + "{label}: expected full red, got {:?}", + pixels[0] + ); + + let pipes_culled = host.emulated_mesh_pipelines(&ms_culled, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes_culled, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu_culled.max_primitives, + group_bytes: emu_culled.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: culled draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [0.0, 0.0, 0.0, 0.0]), + "{label}: expected all culled, got {:?}", + pixels[0] + ); + }); + } + + #[test] + fn emulated_mesh_group_id_supports_base_group_and_slot_map() { + let mut words = Vec::new(); + // s2 = group_id (from v5 via v_readfirstlane_b32) + words.push(vop1(0x002, 2, vgpr(5))); + // v0 = tid (0..3) + words.extend(vop3(0x365, 0, 193, 128, 0)); + // v5 = float(s2), v6 = 0, v7 = 0, v8 = 1.0 -> COLOR0.r = group_id + words.push(vop1(0x006, 5, sgpr(2))); + words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + // If s2 == 36 (group 9 * mesh_stride 4): draw right triangle (0, 1), (2, 1), (0, -3) + // covering top-right; otherwise draw left triangle (-1, 1), (0, 1), (-1, -3) covering top-left. + // v10 = 36, v11 = s2; compare vcc = (v11 == 36) + words.push(vop1(0x001, 11, sgpr(2))); + words.extend(vop1_lit(0x001, 10, 36)); + // Base left x (-1.0), vs right x (0.0) in v12 + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 12, 0.0f32.to_bits())); + words.push(vopc(0x0C2, vgpr(10), 11)); + words.push(vop2(0x001, 1, vgpr(1), 12)); // base x: -1 or 0 + // If tid == 1: x += 1.0 (left: -1->0) or +2.0 (right: 0->2) + words.extend(vop1_lit(0x001, 13, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 14, 2.0f32.to_bits())); + words.push(vopc(0x0C2, vgpr(10), 11)); + words.push(vop2(0x001, 13, vgpr(13), 14)); // width: 1.0 or 2.0 + words.extend(vop2_add_f32_helper(14, 1, 13)); + words.push(vopc(0x0C2, 129, 0)); // tid == 1 + words.push(vop2(0x001, 1, vgpr(1), 14)); + // y: default 1.0, tid == 2 -> -3.0; z = 0.5, w = 1.0 + words.extend(vop1_lit(0x001, 2, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 15, (-3.0f32).to_bits())); + words.push(vopc(0x0C2, 130, 0)); // tid == 2 + words.push(vop2(0x001, 2, vgpr(2), 15)); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + words.extend(vop1_lit(0x001, 9, 0x0020_0400)); + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(S_ENDPGM); + + let ms = compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0, + fp16: false, + pack2: false, + }], + &[ + sig_el("SV_Position", 3, 9, None, 0xF), + sig_el("COLOR", 0, 9, Some(0), 0xF), + ], + &[], + (4, 3, 1, 0), + ); + let emu = ms.mesh_emu.as_ref().unwrap(); + assert!(emu.reads_group_id); + let ps = compile_flat_ps("COLOR"); + + run_on_hosts(|label, host| { + let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); + // Chunked direct dispatch: 1 group starting at base_group = 5 -> top-left = 5.0 + let direct = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: 5, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: base_group draw failed: {e}")); + assert_eq!(direct[0], [20.0, 0.0, 0.0, 1.0], "{label}: direct[0]"); + + // Multi-record indirect dispatch: 2 local groups reading slot_map [2, 9] + let indirect = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 2, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: INDIRECT_SLOT_MAP_FLAG, + slot_map: Some(&[2, 9]), + }, + ) + .unwrap_or_else(|e| panic!("{label}: slot_map draw failed: {e}")); + assert_eq!(indirect[0], [8.0, 0.0, 0.0, 1.0], "{label}: top-left"); + assert_eq!(indirect[7], [36.0, 0.0, 0.0, 1.0], "{label}: top-right"); + }); + } + + const fn vop2_add_f32_helper(vdst: u8, src0_v: u8, vsrc1: u8) -> [u32; 1] { + [vop2(0x003, vdst, vgpr(src0_v), vsrc1)] + } + + #[test] + fn emulated_mesh_passes_per_primitive_psg1_to_ps() { + let mut words = Vec::new(); + words.extend(vop3(0x365, 0, 193, 128, 0)); + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); + words.push(vopc(0x0C2, 129, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + words.push(vopc(0x0C2, 130, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + + words.extend(vop1_lit(0x001, 5, 0.25f32.to_bits())); + words.extend(vop1_lit(0x001, 6, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.75f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + // Per-primitive parameter 0 (`param = 0x80` -> PSG1 PRIMCOLOR at row 0) + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + + words.extend(vop1_lit(0x001, 9, 0x0020_0400)); + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(S_ENDPGM); + + let ms = compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0x80, + fp16: false, + pack2: false, + }], + &[sig_el("SV_Position", 3, 9, None, 0xF)], + &[sig_el("PRIMCOLOR", 0, 9, Some(0), 0xF)], + (4, 3, 1, 0), + ); + let ps = compile_flat_ps("PRIMCOLOR"); + let emu = ms.mesh_emu.as_ref().unwrap().clone(); + + run_on_hosts(|label, host| { + let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [0.25, 0.5, 0.75, 1.0]), + "{label}: expected [0.25, 0.5, 0.75, 1.0], got {:?}", + pixels[0] + ); + }); + } + + #[test] + fn emulated_mesh_supports_lds_barrier_and_quad_swizzle() { + let mut words = Vec::new(); + // v0 = tid (0..3) + words.extend(vop3(0x365, 0, 193, 128, 0)); + // v14 = tid * 4 (LDS byte offset) + words.push(vop2(0x01A, 14, 130, 0)); // v_lshlrev_b32 v14, 2, v0 + // v15 = float(tid + 1) * 0.25 -> thread 2 writes 0.75 into lds[8] + words.push(vop2(0x025, 15, 129, 0)); // v_add_nc_u32 v15, 1, v0 + words.push(vop1(0x006, 15, vgpr(15))); // v_cvt_f32_u32 v15, v15 + words.extend(vop1_lit(0x001, 16, 0.25f32.to_bits())); + words.push(vop2(0x008, 15, vgpr(15), 16)); // v_mul_f32 v15, v15, v16 + words.extend(ds(0x0D, 0, 14, 15, 0, 0)); // ds_write_b32 v14, v15 + words.push(S_BARRIER); + // Each lane reads ((tid + 3) & 3) * 4 -> lane 3 reads lds[8] (0.75) + words.push(vop2(0x025, 14, 131, 0)); // v_add_nc_u32 v14, 3, v0 + words.push(vop2(0x01B, 14, 131, 14)); // v_and_b32 v14, 3, v14 + words.push(vop2(0x01A, 14, 130, 14)); // v_lshlrev_b32 v14, 2, v14 + words.extend(ds(0x36, 5, 14, 0, 0, 0)); // ds_read_b32 v5, v14 + // Broadcast quad lane 3's value (0.75) to all 4 lanes in the quad + words.extend(ds(0x35, 5, 5, 0, 0, 0x80FF)); // ds_swizzle_b32 v5, v5 offset:0x80FF + + // Position + COLOR(v5, 0, 0, 1) + words.extend(vop1_lit(0x001, 1, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 2, (-1.0f32).to_bits())); + words.extend(vop1_lit(0x001, 3, 0.5f32.to_bits())); + words.extend(vop1_lit(0x001, 4, 1.0f32.to_bits())); + words.extend(vop1_lit(0x001, 10, 3.0f32.to_bits())); + words.push(vopc(0x0C2, 129, 0)); + words.push(vop2(0x001, 1, vgpr(1), 10)); + words.push(vopc(0x0C2, 130, 0)); + words.push(vop2(0x001, 2, vgpr(2), 10)); + words.extend(vop1_lit(0x001, 6, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 7, 0.0f32.to_bits())); + words.extend(vop1_lit(0x001, 8, 1.0f32.to_bits())); + words.extend(exp(12, 0xF, [1, 2, 3, 4], false, false)); + words.extend(exp(32, 0xF, [5, 6, 7, 8], false, false)); + words.extend(vop1_lit(0x001, 9, 0x0020_0400)); + words.extend(exp(20, 0x1, [9, 0, 0, 0], true, false)); + words.push(S_ENDPGM); + + let ms = compile_ms( + &words, + vec![VsOutput { + usage: Usage::Generic, + row: 0, + param: 0, + fp16: false, + pack2: false, + }], + &[ + sig_el("SV_Position", 3, 9, None, 0xF), + sig_el("COLOR", 0, 9, Some(0), 0xF), + ], + &[], + (4, 3, 1, 16), + ); + let ps = compile_flat_ps("COLOR"); + let emu = ms.mesh_emu.as_ref().unwrap().clone(); + + run_on_hosts(|label, host| { + let pipes = host.emulated_mesh_pipelines(&ms, &ps).unwrap(); + let pixels = host + .draw_emulated_mesh( + &pipes, + &EmulatedMeshDraw { + cs_roots: Vec::new(), + ps_roots: Vec::new(), + size: (8, 8), + groups: 1, + max_primitives: emu.max_primitives, + group_bytes: emu.group_bytes(), + base_group: 0, + slot_map: None, + }, + ) + .unwrap_or_else(|e| panic!("{label}: draw failed: {e}")); + assert!( + pixels.iter().all(|&p| p == [0.75, 0.0, 0.0, 1.0]), + "{label}: expected [0.75, 0.0, 0.0, 1.0], got {:?}", + pixels[0] + ); + }); + } +} diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 9ec80fd8..ba6236af 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -415,6 +415,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }; ( host(crate::native::HwStage::Vs, vs), diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 28a36f1b..d886a115 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -12,6 +12,9 @@ pub const SAMPLER_SPACE: u32 = 0; /// Where root CBVs and SRVs are bound: `b` and /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// Where mesh shader emulation binds its scratch UAV (`u0`), indirect slot +/// map / unpack vertex input SRV (`t0`), and group base CBV (`b0`). +pub const MESH_EMU_SPACE: u32 = 2; /// The root SRV `t` in [`ROOT_CBV_SPACE`] of a shader that /// reads buffers through descriptors it picks from the view heap at an @@ -120,12 +123,12 @@ pub(crate) struct Geometry { /// RDNA3 took a page fault and removed the device. static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); -/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null. +/// See `VIEW_LIMIT`: `null_slot` is the last slot of the host's view heap, kept null. pub fn set_view_heap_limit(null_slot: u32) { VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); } -/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none). +/// See `VIEW_LIMIT`: the null slot shaders translated now clamp view indices to (0: none). pub fn view_heap_limit() -> u32 { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) } @@ -154,6 +157,9 @@ pub(crate) struct Shader { pub root_srvs: Vec<(u8, V)>, /// Root UAVs (raw buffers) read or written, likewise. pub root_uavs: Vec<(u8, V)>, + emu_cbv: Option, + emu_srv: Option, + emu_uav: Option, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, @@ -211,6 +217,9 @@ impl Shader { root_cbvs: Vec::new(), root_srvs: Vec::new(), root_uavs: Vec::new(), + emu_cbv: None, + emu_srv: None, + emu_uav: None, flags: 0, nonuniform_handles: 0, threads: None, @@ -352,6 +361,77 @@ impl Shader { h } + /// The handle of the mesh emulation group-base CBV (`b0` in [`MESH_EMU_SPACE`]). + pub fn emu_cbv_handle(&mut self) -> V { + if let Some(h) = self.emu_cbv { + return h; + } + let z = self.m.i32(0); + let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(2)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, z, f], + ); + let h = self.annotate(block, h, 13, 16); + self.emu_cbv = Some(h); + h + } + + /// The handle of the mesh emulation raw SRV (`t0` in [`MESH_EMU_SPACE`]). + pub fn emu_srv_handle(&mut self) -> V { + if let Some(h) = self.emu_srv { + return h; + } + let z = self.m.i32(0); + let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(0)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, z, f], + ); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; + self.emu_srv = Some(h); + h + } + + /// The handle of the mesh emulation raw UAV (`u0` in [`MESH_EMU_SPACE`]). + pub fn emu_uav_handle(&mut self) -> V { + if let Some(h) = self.emu_uav { + return h; + } + let z = self.m.i32(0); + let bind = [z, z, self.m.i32(MESH_EMU_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, z, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.emu_uav = Some(h); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -408,7 +488,14 @@ impl Shader { let index = if !sampler && limit != 0 { let null = self.m.i32(limit); let i32t = self.t.i32; - let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]); + let v = self.op( + block, + "binary.i32", + Attr::ReadNone, + i32t, + 40, + &[index, null], + ); self.m.tag(v, super::bitcode::Tag::Clamp); v } else if sampler { @@ -419,7 +506,14 @@ impl Shader { // heap smaller than 2,048 would need. let last = self.m.i32(2047); let i32t = self.t.i32; - let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + let v = self.op( + block, + "binary.i32", + Attr::ReadNone, + i32t, + 40, + &[index, last], + ); self.m.tag(v, super::bitcode::Tag::Clamp); v } else { @@ -478,6 +572,9 @@ impl Shader { || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() || !self.root_uavs.is_empty() + || self.emu_cbv.is_some() + || self.emu_srv.is_some() + || self.emu_uav.is_some() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -528,11 +625,34 @@ impl Shader { dxil_kind: 13, }); } + if self.emu_cbv.is_some() { + let arr = self.m.array(4, self.t.i32); + let ty = self.m.named_struct("EmuConst", vec![arr]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let ops = vec![ + Some(i32c(&mut self, cbv_list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, MESH_EMU_SPACE)), + Some(i32c(&mut self, 0)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 16)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: MESH_EMU_SPACE, + register: 0, + 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.emu_srv.is_some() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); @@ -559,9 +679,30 @@ impl Shader { dxil_kind: 11, }); } + if self.emu_srv.is_some() { + let ops = vec![ + Some(i32c(&mut self, list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, MESH_EMU_SPACE)), + Some(i32c(&mut self, 0)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(i32c(&mut self, 0)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 4, + space: MESH_EMU_SPACE, + register: 0, + dxil_kind: 11, + }); + } srvs = Some(self.m.md_node(list)); } let mut uavs = None; + let mut list = Vec::new(); if !self.root_uavs.is_empty() { let ty = self .m @@ -570,11 +711,7 @@ impl Shader { let u = self.m.undef(p); let no = self.m.bool(false); let no = self.m.md_value(no); - let mut list = Vec::new(); for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { - // Id, variable, name, space, lower bound, range size, - // shape (11: raw buffer), globally coherent, counter, - // rasterizer ordered, no extra properties. let ops = vec![ Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), @@ -596,8 +733,41 @@ impl Shader { dxil_kind: 11, }); } + } + if self.emu_uav.is_some() { + let ty = self + .m + .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let f = self.m.bool(false); + let fv = self.m.md_value(f); + let ops = vec![ + Some(i32c(&mut self, list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, MESH_EMU_SPACE)), + Some(i32c(&mut self, 0)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(fv), + Some(fv), + Some(fv), + None, + ]; + let node = self.m.md_node(ops); + list.push(Some(node)); + bindings.push(Binding { + kind: 7, + space: MESH_EMU_SPACE, + register: 0, + dxil_kind: 11, + }); + } + if !list.is_empty() { uavs = Some(self.m.md_node(list)); } + let mut samplers = None; if self.samplers > 0 { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); @@ -632,8 +802,8 @@ impl Shader { bindings.sort_by_key(|b| match b.kind { 2 => 0, 1 => 1, - 7 => 3, - _ => 2, + 3..=5 => 2, + _ => 3, }); } if let Some(r) = resources { diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index f5c20145..ca659c88 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -168,6 +168,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, }) .expect("lower"); @@ -181,6 +182,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -1555,6 +1557,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, }) .expect("lower"); @@ -1568,6 +1571,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -1622,3 +1626,116 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { } } } + +/// SOPK `op sdst, simm16`. +const fn sopk(op: u8, sdst: u8, simm16: i16) -> u32 { + 0xB000_0000 | (op as u32 & 0x1F) << 23 | (sdst as u32 & 0x7F) << 16 | (simm16 as u16) as u32 +} + +#[test] +fn signed_scalar_add_sub_scc_matches_rdna2() { + // s_add_i32 s6, s0, s1 (SOP2 0x02); s_cselect_b32 s7, 1, 0 (SOP2 0x0A); v_mov_b32 v0, s7 + let add_scc = build_valu_cs(&[ + sop2(0x02, 6, 0, 1), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + // s_sub_i32 s6, s0, s1 (SOP2 0x03); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 + let sub_scc = build_valu_cs(&[ + sop2(0x03, 6, 0, 1), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + // s_mov_b32 s6, s0; s_addk_i32 s6, +1 (SOPK 0x0F); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 + let addk_pos1 = build_valu_cs(&[ + s_mov_b32(6, 0), + sopk(0x0F, 6, 1), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + // s_mov_b32 s6, s0; s_addk_i32 s6, -32768 (SOPK 0x0F); s_cselect_b32 s7, 1, 0; v_mov_b32 v0, s7 + let addk_neg_min = build_valu_cs(&[ + s_mov_b32(6, 0), + sopk(0x0F, 6, i16::MIN), + sop2(0x0A, 7, 0x81, 0x80), + vop1(0x001, 0, sgpr(7)), + ]); + + let add_cases: &[(i32, i32)] = &[ + (0, 0), + (10, 20), + (-1, 1), // unsigned carry, no signed overflow + (i32::MAX, 0), + (i32::MAX, 1), // positive overflow + (i32::MAX, i32::MAX), // positive overflow + (i32::MIN, 0), + (i32::MIN, -1), // negative overflow + (i32::MIN, i32::MIN), // negative overflow (result 0) + (i32::MIN, i32::MAX), // -1, no overflow + ]; + let add_in: Vec<[u32; 4]> = add_cases + .iter() + .map(|&(a, b)| [a as u32, b as u32, 0, 0]) + .collect(); + run_cases(&add_scc, &add_in, |backend, i, _, got| { + let (a, b) = add_cases[i]; + let want = u32::from(a.overflowing_add(b).1); + assert_eq!( + got, want, + "{backend}: s_add_i32({a}, {b}) SCC = {got}, want {want}", + ); + }); + + let sub_cases: &[(i32, i32)] = &[ + (0, 0), + (0, 1), // unsigned borrow, no signed overflow + (0, i32::MIN), // 0 - (-2^31) overflows i32 + (i32::MIN, 0), + (i32::MIN, 1), // negative overflow + (i32::MIN, i32::MIN), // 0, no overflow + (i32::MAX, -1), // positive overflow + (i32::MAX, i32::MIN), // positive overflow + (-5, -3), // -2, no overflow + (-1, i32::MAX), // -2^31 (i32::MIN), no overflow + ]; + let sub_in: Vec<[u32; 4]> = sub_cases + .iter() + .map(|&(a, b)| [a as u32, b as u32, 0, 0]) + .collect(); + run_cases(&sub_scc, &sub_in, |backend, i, _, got| { + let (a, b) = sub_cases[i]; + let want = u32::from(a.overflowing_sub(b).1); + assert_eq!( + got, want, + "{backend}: s_sub_i32({a}, {b}) SCC = {got}, want {want}", + ); + }); + + let addk_pos_cases: &[i32] = &[0, -1, i32::MAX - 1, i32::MAX, i32::MIN]; + let addk_pos_in: Vec<[u32; 4]> = addk_pos_cases + .iter() + .map(|&a| [a as u32, 0, 0, 0]) + .collect(); + run_cases(&addk_pos1, &addk_pos_in, |backend, i, _, got| { + let a = addk_pos_cases[i]; + let want = u32::from(a.overflowing_add(1).1); + assert_eq!( + got, want, + "{backend}: s_addk_i32({a}, +1) SCC = {got}, want {want}", + ); + }); + + let addk_neg_cases: &[i32] = &[0, i32::MAX, i32::MIN + 32768, i32::MIN + 32767, i32::MIN]; + let addk_neg_in: Vec<[u32; 4]> = addk_neg_cases + .iter() + .map(|&a| [a as u32, 0, 0, 0]) + .collect(); + run_cases(&addk_neg_min, &addk_neg_in, |backend, i, _, got| { + let a = addk_neg_cases[i]; + let want = u32::from(a.overflowing_add(i32::from(i16::MIN)).1); + assert_eq!( + got, want, + "{backend}: s_addk_i32({a}, -32768) SCC = {got}, want {want}", + ); + }); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 18425e06..f0972a00 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -69,6 +69,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. @@ -84,6 +85,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 2b6edd46..a27ae5e0 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -148,7 +148,7 @@ pub struct Resources { /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, /// Scalar loads of one descriptor the code keeps per lane in VGPRs - /// ([`Tracer::lane_copies`]): they read one address, so their dwords + /// (`Tracer::lane_copies`): they read one address, so their dwords /// stand in for each other. pub lane_copied: Vec, pub waterfall: Waterfall, @@ -235,7 +235,7 @@ pub fn track( let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { let source = t.descriptor(inst, op, b).map_err(fail)?; - // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) + // A descriptor the code keeps per lane (`Tracer::lane_copies`) // is the same in every lane: its loop is lowered as it stands // and needs no proof. if !t.kept_per_lane(inst, op) { diff --git a/docs/architecture.md b/docs/architecture.md index 5e3e6b6b..fadc5e43 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -94,6 +94,14 @@ waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced to the per-lane load or choice that gives each lane its own (a mask's `v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths the lanes take, from structurisation), and accessed with a non-uniform heap -index in one pass. `victory translate` +index in one pass. On GPUs with SM 6.6 that lack hardware mesh shaders (or with +`VICTORY_MESH_EMULATION=1`), console mesh programs (`HwStage::Ms`) lower to a +compute pass (`cs_6_6`) writing packed primitive indices and attributes into a +VRAM buffer read back by a generated unpack vertex shader (`vs_6_6`). The +indirect-mesh preparation pass compacts records to one output-buffer chunk and +charges only those runnable groups against the shared per-list work budget. +For multi-record calls it also writes a slot map that preserves each +record-local mesh group id. +`victory translate` runs every shader it finds (containers, SGD5 files) through these and lists what they cannot handle yet. diff --git a/docs/compatibility.md b/docs/compatibility.md new file mode 100644 index 00000000..0c2ac78e --- /dev/null +++ b/docs/compatibility.md @@ -0,0 +1,99 @@ +# Compatibility investigation: Grand Theft Auto VI + +**Status:** Experimental; not confirmed playable +**Last updated:** 2026-11-24 + +This document records an independent compatibility investigation using +VIctory. It is a development report, not an official compatibility claim. + +## Test environment + +| Component | Configuration | +|---|---| +| CPU | Intel Core i7-8700K | +| GPU | AMD Radeon RX 5600 XT, 6 GB | +| RAM | 16 GB DDR4 | +| Operating system | Windows | +| Graphics API | Direct3D 12 | +| GPU architecture | AMD RDNA 1 (Navi 10) | + +## Test target + +- Title executable: `game_scarlett_master.exe` +- Game files are supplied locally by the tester. +- No proprietary game assets or executable contents are included in this repository. + +## Shader translation results + +A translation scan reported: + +| Metric | Result | +|---|---:| +| Containers scanned | 26,599 | +| Programs translated | 26,148 / 26,148 | +| Vertex/pixel DXIL emitted | 12,250 / 14,039 | +| Compute DXIL emitted | 1,441 / 2,582 | +| Mesh DXIL emitted | 8,278 / 8,713 | +| DXIL validated | 21,783 / 21,969 | + +Approximately 99.15% of emitted DXIL programs passed validation. + +These figures describe translation and validation only. They do not +demonstrate that the title can render or run correctly. + +Pipeline investigation also encountered failures involving mesh pipelines. +Host mesh-shader support and pipeline creation remain areas for further +investigation. + +## Runtime observations + +The title progresses into GPU initialization and resource activity but +does not reach confirmed playable gameplay. + +Observed issues include: + +- Direct3D 12 `E_OUTOFMEMORY` errors (`0x8007000E`). +- Failed allocation of a 94,371,840-byte shared buffer (90 MiB). +- Command-list submission or closing failure following allocation errors. +- D3D12 resource-state validation warnings involving + `UNORDERED_ACCESS` and `VERTEX_AND_CONSTANT_BUFFER`. + +The shared buffer uses a CPU-visible, system-memory allocation path. +Therefore, the allocation failure alone does not establish that dedicated +GPU VRAM was exhausted. + +The resource-state warnings occurred shortly before an allocation failure +in one captured run. Their causal relationship has not been established. + +## Current assessment + +**Confirmed:** +- The workspace builds successfully in release mode with GPU and core + diagnostics enabled. +- Shader translation completes for the reported program counts. +- Most emitted DXIL passes validation. +- Runtime resource allocation failures occur. + +**Not yet established:** +- The root cause of the shared-buffer allocation failure. +- Whether resource-state mismatches contribute to the failure. +- Whether the observed allocation behaviour is a memory leak, + fragmentation, budget exhaustion, or another issue. +- Whether the title can reach stable gameplay on this configuration. + +## Next investigation areas + +1. Measure shared-buffer allocations and lifetimes. +2. Investigate the lifetime and growth of loose shadow-memory allocations. +3. Trace D3D12 resource-state transitions around the first failure. +4. Determine whether allocation failures are reproducible. +5. Re-test after any targeted fixes. + +## Reporting and reproducibility + +Results depend on the exact VIctory commit, game build, graphics driver, +configuration and test conditions. + +Diagnostic logs and translation outputs are retained separately from +this repository. They may contain machine-specific information and +should be reviewed before sharing. diff --git a/docs/debugging.md b/docs/debugging.md new file mode 100644 index 00000000..cfe57885 --- /dev/null +++ b/docs/debugging.md @@ -0,0 +1,123 @@ +# D3D12 debugging notes + +This document records diagnostic procedures and observations from the +experimental VIctory compatibility investigation. + +## Diagnostic build + +Build the workspace with GPU and core diagnostics enabled: + +```powershell +cargo build --release --workspace --features victory-gpu/diagnostics,victory-core/diagnostics +``` + +## Runtime diagnostic capture + +Set the diagnostic environment variables: + +```powershell +$env:VICTORY_D3D12_DEBUG = "1" +$env:VICTORY_D3D12_DRED = "1" +$env:VICTORY_GPU_TIMING = "1" +$env:VICTORY_LOG = "victory_gpu::shadow=debug,info" +``` + +Run the title using locally supplied game files: + +```powershell +.\target\release\victory.exe run "PATH_TO_TITLE_EXECUTABLE" --execute *> .\victory-debug.log +``` + +Replace `PATH_TO_TITLE_EXECUTABLE` with the local executable path. + +These settings enable the D3D12 debug layer, DRED diagnostics, GPU timing +and shadow-memory logging. Diagnostic availability depends on the build +features and host graphics driver. + +## Observed allocation failure + +One captured run reported: + +```text +E_OUTOFMEMORY (0x8007000E) +no shared buffer +size=94371840 +``` + +The failed allocation was 94,371,840 bytes (90 MiB). + +The shared-buffer allocation path uses a CPU-visible D3D12 custom heap +with WRITE_BACK CPU page properties and the L0 memory pool. + +This is a system-memory allocation path. The error does not, by itself, +prove that dedicated GPU VRAM was exhausted. + +## Resource-state validation + +The D3D12 debug layer also reported resource-state mismatches involving: + +- `UNORDERED_ACCESS` +- `VERTEX_AND_CONSTANT_BUFFER` + +These warnings appeared shortly before an allocation failure in one +captured run. Their relationship to the allocation failure is unknown. + +Resource transitions and command-list state tracking require further +investigation. + +## Shadow-memory observations + +The shadow-memory implementation maintains host-visible copies of title +memory. + +Relevant investigation areas include: + +- Registered title buffers and their shadow allocations. +- Loose shadow-memory allocations and cache lifetime. +- Allocation sizes and alignment. +- Resource references retained by command lists. +- Allocation reuse and release behaviour. + +A previous log contained eight distinct registered buffers of at least +16 MiB, totalling approximately 446.92 MiB. + +A separate run recorded 55 unique loose-memory allocation keys totalling +approximately 252 MiB. These figures came from different runs and must +not be combined into one memory total. + +The loose-memory cache currently warrants investigation because its +entries are retained in a map. This is a hypothesis for possible +allocation growth, not a confirmed cause of the runtime failure. + +## Interpreting results + +Do not assume that `E_OUTOFMEMORY` means physical VRAM exhaustion. + +Investigate the following independently: + +1. System-memory availability at the time of failure. +2. D3D12 resource allocation sizes and heap types. +3. Resource lifetime and reference retention. +4. GPU resource-state validation messages. +5. Command-list submission and synchronization. +6. Reproducibility across repeated runs. + +A diagnostic warning occurring before an allocation failure does not +establish causation. + +## Reporting a reproducible issue + +When reporting a failure, include: + +- VIctory commit hash. +- CPU, GPU, RAM and driver version. +- Operating-system version. +- Diagnostic build features. +- Exact command and environment variables. +- First allocation failure and surrounding log messages. +- Resource-state warnings preceding the failure. +- Whether the failure reproduces on another run. + +Review logs before sharing them. Remove machine-specific paths and never +include proprietary game assets, executables, shader dumps or extracted +game data in the repository. diff --git a/docs/linux-proton.md b/docs/linux-proton.md new file mode 100644 index 00000000..f5e43fc6 --- /dev/null +++ b/docs/linux-proton.md @@ -0,0 +1,118 @@ +# Linux (Proton) + +VIctory is a Windows program, and it also runs on Linux under Proton's Wine +with vkd3d-proton for Direct3D 12. Under Proton it gets as far as on Windows: +boot, first-boot screens, intro video, start screen, saves, loading, and the +opening of the first mission (credits over the scene; the scene itself is +still dark, as on Windows). + +Tested on one machine (2026-11-24): CachyOS, Linux 7.3, AMD RX 9070 XT +(RADV, Mesa 26.3.1), Proton Experimental `experimental-11.0-20261112`. + +## Requirements + +- Steam's **Proton Experimental** (Steam → Library → Tools). Older Protons + may not work: GE-Proton 11-11's vkd3d-proton turns some translated + shaders into invalid SPIR-V, on which RADV crashes (`vkCreateGraphicsPipelines`, + exit code 3). +- A Vulkan driver with mesh shaders (RADV on RDNA 2 or later has them). +- `rustup` and [`cargo-xwin`](https://github.com/rust-cross/cargo-xwin) + to build the Windows target on Linux. + +## Building + +```sh +rustup target add x86_64-pc-windows-msvc +cargo install --locked cargo-xwin +# cargo-xwin downloads the MSVC CRT and Windows SDK; this accepts their licence. +export XWIN_ACCEPT_LICENSE=1 +cargo xwin build --release -p victory --target x86_64-pc-windows-msvc +``` + +The diagnostics build likewise: +`cargo xwin build --profile diag -p victory --features diagnostics --target x86_64-pc-windows-msvc`. + +## Running + +`scripts/proton-run.sh` runs `victory.exe` with Proton's Wine, in a prefix of +its own (`~/.local/share/victory/proton`, made on first use), with +vkd3d-proton and DXVK. Linux paths work as arguments. + +```sh +scripts/proton-run.sh config +scripts/proton-run.sh run /path/to/game/ --execute +``` + +`PROTON` selects another Proton folder, `PREFIX` another prefix and +`VICTORY_EXE` another exe (the diagnostics build, say). Saves, settings and +`crashes.log` live in the prefix's `%LOCALAPPDATA%\victory\data` unless +`victory.toml` or `VICTORY_DATA_DIR` says otherwise. + +With an Xbox controller connected, the keyboard is not a pad (as on +Windows), so `VICTORY_KEYS` presses do not reach the title either. + +### Without Proton (system Wine) + +A system Wine works too (reported with Wine 11.22 on RDNA2, RDNA3 and +RDNA 3.5). What Proton brings has to be added: + +- **vkd3d-proton 3.2 or newer**: `d3d12.dll` and `d3d12core.dll` (Proton + Experimental's `files/lib/wine/vkd3d-proton/x86_64-windows`). 3.1 turns + some translated shaders into SPIR-V RADV cannot take. +- **DXVK's `dxgi.dll`**, and `WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=n"`. +- No Microsoft `d3dcompiler_47`: Wine's built-in one compiles the argument + clamp since it no longer needs `RWByteAddressBuffer` methods. + +### Diagnostics switches + +In the diagnostics build: + +- `VICTORY_NO_WATCHDOG=1` (from #454, if merged) keeps the title's stall + watchdog from ending slow runs. +- `VICTORY_SHOW_TARGET=x-f[-]` presents an intermediate + render target instead of the final frame, the `n`th of that size and + format the frame writes (names as in `VICTORY_DUMP_TARGETS` files). The + world's G-buffer shows its geometry while the final image is dark: + `VICTORY_SHOW_TARGET=2560x1440-f28-3` on a Series X profile. +- `VICTORY_DEBUG_PS=1` draws depth-tested geometry with a debug pixel + shader (surfaces coloured by their slope, from depth derivatives) instead + of the title's: the geometry of every draw whose vertex or mesh stage + translates, whether its pixel shader does or not. With the two switches + together you can walk the world in a flat-colour view. + +In every build, a draw of depth-tested geometry whose pixel shader does +not translate (or that the host refuses) is drawn with that debug shader +instead of dropped; `VICTORY_PS_FALLBACK=0` turns that off. +`VICTORY_PIPELINE_WAIT_MS` sets how long a frame may wait for pipelines +being made (500 by default; 0 never waits, pipelines then appear a few +frames later). + +## Tests + +```sh +CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER=$PWD/scripts/proton-run.sh \ + cargo xwin test --workspace --target x86_64-pc-windows-msvc +``` + +Two tests start Linux programs from inside Wine and fail there for that +reason only: `loads_binds_and_calls_probe` (builds its fixture with `cargo`) +and `policy::tests::repository_passes_policy` (runs `git`). Run +`cargo xtask policy` natively instead. + +## Known differences + +- **Speed.** Wine emulates write watching page by page, so the copies of + title memory take longer than on Windows. Under Wine the kernel is asked + about each title allocation once per submission (`watch::new_submission`), + views of physical pages go straight to their guards, and allocations are + looked up from a cache rather than with `VirtualQuery`, which takes the + same lock as the title's write faults. +- **Software rendering does not work.** On lavapipe, Wine cannot handle the + write faults of VIctory's guarded title memory when lavapipe's own + threads take them. +- **vkd3d-proton differs from Windows drivers in a few places VIctory now + handles:** its HLSL compiler (Wine's `D3DCompile`) lacks + `RWByteAddressBuffer` methods and does not embed root signatures; it + refuses an empty pipeline library given a non-null blob pointer; it does + not check DXIL container hashes; and its descriptor layout makes a texture + descriptor read as a constant buffer (a stale slot) a read at address 0. diff --git a/docs/linux-wine.md b/docs/linux-wine.md new file mode 100644 index 00000000..4f7cc314 --- /dev/null +++ b/docs/linux-wine.md @@ -0,0 +1,115 @@ +# Linux with Wine/Proton (experimental) + +VIctory is a Windows application: the title loader uses Windows APIs and the +GPU backend uses D3D12. Linux reports have successfully run it through Wine +with vkd3d-proton translating D3D12 to Vulkan. Cross-build the Windows +executable; native Linux builds are not currently supported. + +## Reported working setup + +A community report (#879) used Arch/CachyOS, an AMD RADV GPU, Wine 11.22, and +vkd3d-proton 3.2.0 from Proton Experimental. DXVK supplied `dxgi.dll` (and +`d3d11.dll`/`d3d10core.dll`); the report used: + +```sh +WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b" +``` + +The `n,b` overrides are important: they select the native Proton DLLs before +Wine's built-ins. Use a vkd3d-proton version compatible with your GPU and +driver. The report found 3.1 crashed during world loading, while 3.2.0 reached +menus and loading. This is community-reported, not a tested or supported +configuration; other reports describe crashes and severe performance issues. + +## Build and launch + +Enter the project shell (Nix with `` available), then cross-compile +the Windows MSVC target. The shell provides Rustup, `cargo-xwin`, Vulkan +tools, Clang, LLVM, and LLD: + +```sh +nix-shell +cargo xwin build --release -p victory --target x86_64-pc-windows-msvc +``` + +Rustup reads `rust-toolchain.toml` and installs the pinned toolchain/target on +first use. Outside Nix, install Rustup and `cargo-xwin` yourself. + +The project shell prefers an installed GE-Proton compatibility tool (on this +machine it selects `GE-Proton-nix`). The helper builds if needed, creates a +dedicated prefix outside the repository, and launches through GE-Proton's own +runner. This is the path verified with the supplied game installation: + +```sh +nix-shell +./scripts/run-ge-proton.sh +``` + +The helper defaults to the game executable path supplied for this machine. +For another installation, pass the executable or set `VICTORY_TITLE_EXE`. +Override `GE_PROTON` to select another installed GE-Proton release. A GE-Proton +installation can be discovered under Steam's `compatibilitytools.d`. The helper +uses GE-Proton directly because that path was verified with the supplied game +files; UMU is another option but requires explicit pressure-vessel access for +game files outside the home directory. + +## Controller + +VIctory reads up to four XInput gamepads. Proton should expose an Xbox or +Xbox-compatible controller as XInput; connect it before starting the title. +The gamepad path includes buttons, D-pad, sticks, and analog triggers. Basic +motor rumble is sent through XInput, but the title's trigger/adaptive rumble +is not implemented. + +The launch helper runs GE-Proton outside the Steam client, so Steam Input's +virtual controller mapping is not automatically applied. If your controller +is not seen, or it is not XInput-compatible, add the built `victory.exe` to +Steam as a non-Steam game, force the installed GE-Proton compatibility tool, +enable Steam Input, and use these launch options (adjust the game path if +needed): + +```text +WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b" %command% run "Z:\mnt\data\Games\GTA6\GTA6.Xbox.v1.0.2.1\GTA6.Xbox.v1.0.2.1\game_scarlett_master.exe" --execute +``` + +As a fallback, when no gamepad is connected, the keyboard acts as a pad while +the title window is focused: WASD/IJKL are the sticks, arrows the D-pad, +Enter/Backspace/X/Y the face buttons, Q/E the shoulders, Z/C the triggers, +F/H the stick clicks, and Esc/Tab Menu/View. + +For manual Wine/Proton launches, use a win64 prefix with the Proton versions of +`d3d12.dll`, `d3d12core.dll`, and DXVK's `dxgi.dll` available to that prefix. +The exact installation method depends on whether you use system Wine or +Proton; do not mix arbitrary Wine built-ins with the Proton D3D12 stack. +The shell sets the reported DLL overrides by default; Wine falls back to its +built-ins if native DLLs are not installed, which is not a working D3D12 setup. + +Run from an active graphical session. For a KDE Wayland session launched +remotely, one report needed the session's `XDG_RUNTIME_DIR`, `DISPLAY` (for +XWayland), and `XAUTHORITY`; obtain these from that session rather than +hard-coding another user's runtime directory. + +For example, with a prefix already configured and the game directory visible +to Wine as `Z:\path\to\game`: + +```sh +export WINEPREFIX="$HOME/.wine-victory" +export WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b" +wine target/x86_64-pc-windows-msvc/release/victory.exe config +wine target/x86_64-pc-windows-msvc/release/victory.exe run \ + 'Z:\path\to\game\game.exe' --execute +``` + +Configure paths in `victory.toml` (or `VICTORY_*_DIR` variables) so they are +valid inside the Wine process. Keep the repository, game data, and derived +cache/data directories separate as required by the asset policy. + +## Current limitations + +Linux/Wine reports have reached responsive menus, but performance can be +extremely low and the world is not reliably playable. Missing shaders and +indirect draws are still dropped; the title/runtime also has reported GPU +crashes and hangs. Enabling indirect execution may require Microsoft's +`d3dcompiler_47.dll`, since some Wine versions cannot compile the required +`cs_5_1` shader. No Linux setup is currently part of the project's tested +platform matrix. diff --git a/shell.nix b/shell.nix new file mode 100644 index 00000000..263c9793 --- /dev/null +++ b/shell.nix @@ -0,0 +1,42 @@ +{ pkgs ? import { } }: + +pkgs.mkShell { + name = "victory-linux"; + + packages = with pkgs; [ + rustup + cargo-xwin + vulkan-loader + vulkan-tools + pkg-config + clang + llvm + lld + python3 + ]; + + shellHook = '' + export LD_LIBRARY_PATH="${pkgs.vulkan-loader}/lib''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + # Prefer a GE-Proton compatibility tool already installed by Steam. + if [ -z "''${GE_PROTON:-}" ]; then + for candidate in \ + "$HOME/.local/share/Steam/compatibilitytools.d/GE-Proton-nix" \ + "$HOME/.local/share/Steam/compatibilitytools.d"/GE-Proton* \ + "$HOME/.steam/root/compatibilitytools.d"/GE-Proton*; do + if [ -x "$candidate/proton" ]; then + export GE_PROTON="$candidate" + break + fi + done + fi + # Prefer an installed GE-Proton compatibility tool. + export WINEDLLOVERRIDES="''${WINEDLLOVERRIDES:-d3d12=n,b;d3d12core=n,b;dxgi=n,b}" + echo "VIctory Linux shell: cargo xwin build --release -p victory --target x86_64-pc-windows-msvc" + if [ -n "''${GE_PROTON:-}" ]; then + echo "GE-Proton: $GE_PROTON (launch with ./scripts/run-ge-proton.sh)" + else + echo "GE-Proton not found; set GE_PROTON to its installation directory." + fi + echo "Rust uses rust-toolchain.toml (rustup may download it on first use)." + ''; +} From e3d62138812f1d57ed490053c99e5b1e6d25cf4c Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:19:52 +0000 Subject: [PATCH 08/16] Integrate fxceless round 2: merge overlap files Overlap files merged as fxceless structure plus this fork's extras: the input chain (gameinput.rs auto-merged whole), the shader cache keyed on mesh mode (their fingerprint build key, strict improvement), translate_with(mesh) carrying their first-half-pairs retry, the host mesh-support detection enum and default_buffer. Dropped as superseded by their rework: the lightweight texture recheck (theirs is full), the depth-bounds stream port (theirs is complete), barrier coalescing (their copy engine rework obsoletes the audit it needs), the Wine write-watch cache and frame percentiles (to be re-applied as their own PRs). Mesh emulation pipeline creation and dispatch are the follow-up commit; mesh_emu.rs compiles against the new host but is not wired yet. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-formats/src/texture.rs | 110 +- crates/victory-gpu/Cargo.toml | 1 + crates/victory-gpu/src/capture.rs | 4 +- crates/victory-gpu/src/copystat.rs | 18 +- crates/victory-gpu/src/host.rs | 126 ++- crates/victory-gpu/src/indirect.rs | 982 +++++++++++++++++- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline.rs | 19 +- crates/victory-gpu/src/queue.rs | 2 +- crates/victory-gpu/src/shader_cache.rs | 451 +++++++- crates/victory-hle/src/modules/gameinput.rs | 372 ++++++- crates/victory-shader/src/emit/lower.rs | 949 ++++++++++++++--- crates/victory-shader/src/emit/mod.rs | 142 ++- .../victory-shader/src/emit/wave64_tests.rs | 2 + 14 files changed, 2885 insertions(+), 295 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index fa719c93..6a09c5f4 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -30,6 +30,8 @@ //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //! EXPRESS OR IMPLIED. +use std::sync::OnceLock; + /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Swizzle(pub u32); @@ -174,11 +176,14 @@ pub struct Layout { /// The first mip in the tail; `mips.len()` without one. pub first_tail_mip: u32, pub mips: Vec, - /// Byte offsets inside a block of each element coordinate bit, per - /// axis; empty for linear and unsupported modes. - pattern: [Vec; 3], + /// Byte offsets inside a block for each coordinate, per axis. + /// Empty for linear and unsupported modes. + pattern: &'static SwizzlePattern, } +type SwizzlePattern = [Vec; 3]; +static EMPTY_PATTERN: SwizzlePattern = [const { Vec::new() }; 3]; + /// Micro tile (256 bytes) patterns by log2 of the element size: for each /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` @@ -247,6 +252,18 @@ fn spread(bits: &[u32]) -> Vec { .collect() } +/// Tables depend only on the micro-tile kind, block size and element size. +/// Texture extents, mip placement and array slices only affect the base +/// address, so layouts with the same key can share these immutable tables. +fn shared_pattern(kind: usize, element_log2: u32, block_log2: u32) -> &'static SwizzlePattern { + // Indexed by MICRO kind, block size (256 B, 4 KiB, 64 KiB), then element size. + static PATTERNS: [[[OnceLock; 5]; 3]; 3] = + [const { [const { [const { OnceLock::new() }; 5] }; 3] }; 3]; + let block_index = ((block_log2 - 8) / 4) as usize; + PATTERNS[kind][block_index][element_log2 as usize] + .get_or_init(|| pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))) +} + const MAX_MIPS: u32 = 16; /// The largest width, height and depth (or array size) accepted, in texels. @@ -322,7 +339,7 @@ impl Layout { alignment: 256, first_tail_mip: d.mips, mips, - pattern: Default::default(), + pattern: &EMPTY_PATTERN, } } @@ -330,13 +347,18 @@ impl Layout { let element_log2 = d.element_bytes.trailing_zeros(); let bpe = u64::from(d.element_bytes); let block_bytes = 1u64 << block_log2; - let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); + let thick = + d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); let block = if thick { // ComputeThickBlockDimension let amp = (block_log2 - 10) / 3; let rest = (block_log2 - 10) % 3; let b = BLOCK_1K_3D[element_log2 as usize]; - [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))] + [ + b[0] << amp, + b[1] << (amp + rest / 2), + b[2] << (amp + u32::from(rest != 0)), + ] } else { // ComputeThinBlockDimension let samples_log2 = d.samples.trailing_zeros(); @@ -352,7 +374,12 @@ impl Layout { let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 }; let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 }; let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block)); - let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block)); + let padded = |i| { + ( + padded_dim(d.width, i, d.block), + padded_dim(d.height, i, d.block), + ) + }; let mut mips = Vec::with_capacity(d.mips as usize); let mut first_tail_mip = d.mips; let mut slice_size = 0u64; @@ -367,10 +394,8 @@ impl Layout { offset: 0, tail: None, }); - slice_size = u64::from(mips[0].pitch) - * u64::from(mips[0].rows) - * bpe - * u64::from(d.samples); + slice_size = + u64::from(mips[0].pitch) * u64::from(mips[0].rows) * bpe * u64::from(d.samples); } else { // GetMipTailDim: the largest mip the tail takes. let mut tail_max = block; @@ -490,9 +515,9 @@ impl Layout { } else { usize::from(d.swizzle.display()) }; - pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + shared_pattern(kind, element_log2, block_log2) } else { - Default::default() + &EMPTY_PATTERN }; Layout { desc: d, @@ -564,7 +589,8 @@ impl Layout { // offset inside the tail block. let y = y + m.tail.map_or(0, |t| t.y); let blocks = u64::from(y / bh) * u64::from(m.pitch / bw); - (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) + (blocks << log2) + + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) } /// The part of an address that depends on the column. @@ -837,7 +863,14 @@ impl Texture { 1 }; let mips = match desc.mips { - 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), + 0 => { + 32 - desc + .width + .max(desc.height) + .max(depth3d) + .max(1) + .leading_zeros() + } n => n, }; let plane = |bytes| Desc { @@ -969,7 +1002,11 @@ mod tests { let mut seen = vec![false; l.size as usize]; let mut tiled = vec![0u8; l.size as usize]; let n = d.element_bytes as usize; - let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; + let slices = if d.dimension == Dimension::Tex3d { + 1 + } else { + d.depth + }; for slice in 0..slices { for mip in 0..d.mips { let m = l.mips[mip as usize]; @@ -998,7 +1035,11 @@ mod tests { seen[at] = true; } } - assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); + assert!( + back[base + plane - 11..base + plane] + .iter() + .all(|&b| b == 0xcc) + ); } } } @@ -1077,6 +1118,41 @@ mod tests { assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); } + #[test] + fn layouts_share_identical_swizzle_tables() { + for (swizzle, kind, dimension, block_log2) in [ + (Swizzle::SW_256B_S, 0, Dimension::Tex2d, 8), + (Swizzle::SW_256B_D, 1, Dimension::Tex2d, 8), + (Swizzle::SW_4KB_S, 0, Dimension::Tex2d, 12), + (Swizzle::SW_4KB_D, 1, Dimension::Tex2d, 12), + (Swizzle::SW_64KB_S, 0, Dimension::Tex2d, 16), + (Swizzle::SW_64KB_D, 1, Dimension::Tex2d, 16), + (Swizzle::SW_4KB_S, 2, Dimension::Tex3d, 12), + (Swizzle::SW_64KB_S, 2, Dimension::Tex3d, 16), + ] { + for element_log2 in 0..5 { + let d = Desc { + dimension, + depth: 8, + ..desc(128, 96, 7, 1 << element_log2, swizzle) + }; + let first = Layout::new(&d).unwrap(); + let second = Layout::new(&Desc { + width: 32, + height: 24, + mips: 3, + depth: 1, + ..d + }) + .unwrap(); + let expected = pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)); + assert_eq!(first.pattern, &expected); + assert!(std::ptr::eq(first.pattern, second.pattern)); + assert!(std::ptr::eq(first.pattern, first.clone().pattern)); + } + } + } + /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. #[test] diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index fca8c785..b369ec18 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -31,6 +31,7 @@ windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Securit windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", + "Win32_Graphics_Direct3D_Dxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 64695fe1..b15aee6d 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -456,7 +456,7 @@ fn dump_one( } let most = |m: std::collections::HashMap| { let mut v: Vec<(u32, u32)> = m.into_iter().collect(); - v.sort_by_key(|e| std::cmp::Reverse(e.1)); + v.sort_unstable_by_key(|e| std::cmp::Reverse(e.1)); (v.len(), v.into_iter().take(12).collect::>()) }; tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)"); @@ -519,7 +519,7 @@ fn stencil_values( .enumerate() .filter(|v| v.1 != 0) .collect(); - most.sort_by_key(|v| std::cmp::Reverse(v.1)); + most.sort_unstable_by_key(|v| std::cmp::Reverse(v.1)); most.truncate(16); tracing::info!( frame, diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index a86d1e82..6e0768ed 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -657,7 +657,7 @@ fn log_memory_map() { group.1 += bytes; } let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect(); - groups.sort_by_key(|g| std::cmp::Reverse(g.1.1)); + groups.sort_unstable_by_key(|g| std::cmp::Reverse(g.1.1)); let biggest: Vec = groups .iter() .take(20) @@ -1197,7 +1197,7 @@ pub(crate) fn log(frames: f64) { // What is copied whole, largest first: memory nobody tells us about. let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut whole: Vec<_> = whole.into_iter().flatten().collect(); - whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + whole.sort_unstable_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); tracing::info!( " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", ms(c[C::WholeUs as usize]), @@ -1235,7 +1235,7 @@ pub(crate) fn log(frames: f64) { ); let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut by: Vec<_> = by.into_iter().flatten().collect(); - by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + by.sort_unstable_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); for (what, (n, us)) in by.into_iter().take(12) { tracing::info!( " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}", @@ -1246,7 +1246,7 @@ pub(crate) fn log(frames: f64) { } let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut by: Vec<_> = by.into_iter().flatten().collect(); - by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); + by.sort_unstable_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); // All of them together, and by their first word: the forty lines below // are the heaviest only (100 of 226 ms waited in run 102), and what the // commands do not account for is the layer's own lists (the card @@ -1260,7 +1260,7 @@ pub(crate) fn log(frames: f64) { None => kinds.push((word, *n, *us)), } } - kinds.sort_by_key(|k| std::cmp::Reverse(k.2)); + kinds.sort_unstable_by_key(|k| std::cmp::Reverse(k.2)); let all: u64 = kinds.iter().map(|k| k.2).sum(); let text: Vec = kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); @@ -1300,7 +1300,7 @@ pub(crate) fn log(frames: f64) { // it shaders had written. let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut compared: Vec<_> = compared.into_iter().flatten().collect(); - compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + compared.sort_unstable_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); for ((src, len), (n, written)) in compared.into_iter().take(8) { tracing::info!( @@ -1311,7 +1311,7 @@ pub(crate) fn log(frames: f64) { ); } let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner())); - submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions)); + submitters.sort_unstable_by_key(|s| std::cmp::Reverse(s.1.submissions)); for (id, s) in submitters.into_iter().take(4) { let per = |v: u64| v as f64 / 1e3 / frames; tracing::info!( @@ -1329,7 +1329,7 @@ pub(crate) fn log(frames: f64) { ); } let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner())); - recorders.sort_by_key(|r| std::cmp::Reverse(r.1)); + recorders.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); let busiest: Vec = recorders .iter() .take(6) @@ -1339,7 +1339,7 @@ pub(crate) fn log(frames: f64) { log_memory(); let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); - ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); + ranges.sort_unstable_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) { use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; // SAFETY: plain data filled in by the query. diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 766e735d..abcefdb4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3665,42 +3665,77 @@ fn hand_back(back: &[Declared]) { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MeshSupport { + Native, + Emulate, + Unsupported, +} + impl Host { - /// Whether the host runs mesh shaders at shader model 6.6 (translated - /// mesh shaders need both); logged once. - pub(crate) fn mesh_shaders(&self) -> bool { - static MESH: OnceLock = OnceLock::new(); + fn mesh_support(&self) -> MeshSupport { + static MESH: OnceLock = OnceLock::new(); *MESH.get_or_init(|| { let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6, }; // SAFETY: each query writes its own structure of the given size. - let ok = unsafe { - self.device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS7, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - .is_ok() - && self - .device + let (opt_ok, sm_ok) = unsafe { + ( + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok(), + self.device .CheckFeatureSupport( D3D12_FEATURE_SHADER_MODEL, (&raw mut model).cast(), size_of_val(&model) as u32, ) - .is_ok() + .is_ok(), + ) }; - let mesh = ok - && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED - && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; - tracing::info!(mesh, "host mesh shader support"); - mesh + let sm66 = sm_ok && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + let hardware = opt_ok && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; + let override_env = std::env::var("VICTORY_MESH_EMULATION").ok(); + let mode = match override_env.as_deref().map(str::trim) { + Some(v) if v == "1" || v.eq_ignore_ascii_case("true") => { + if sm66 { + MeshSupport::Emulate + } else { + MeshSupport::Unsupported + } + } + Some(v) if v == "0" || v.eq_ignore_ascii_case("false") => { + if sm66 && hardware { + MeshSupport::Native + } else { + MeshSupport::Unsupported + } + } + _ if !sm66 => MeshSupport::Unsupported, + _ if hardware => MeshSupport::Native, + _ => MeshSupport::Emulate, + }; + tracing::info!(?mode, sm66, hardware, "host mesh shader support"); + mode }) } + /// Whether the host runs mesh shaders itself at shader model 6.6. + pub(crate) fn mesh_shaders(&self) -> bool { + self.mesh_support() == MeshSupport::Native + } + + /// Whether mesh shaders run as compute plus generated vertex shaders. + pub(crate) fn emulate_mesh_shaders(&self) -> bool { + self.mesh_support() == MeshSupport::Emulate + } + /// Whether the host GPU supports the depth bounds test; logged once. pub(crate) fn depth_bounds(&self) -> bool { static BOUNDS: OnceLock = OnceLock::new(); @@ -7295,6 +7330,57 @@ impl Host { } } + /// A committed buffer on the default heap, in unordered-access state + /// when the flags allow it. For the mesh emulation's static buffers. + pub(crate) fn default_buffer( + &self, + size: u64, + flags: D3D12_RESOURCE_FLAGS, + ) -> Option { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + 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 state = if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 { + D3D12_RESOURCE_STATE_UNORDERED_ACCESS + } else { + D3D12_RESOURCE_STATE_COMMON + }; + let mut buffer: Option = None; + // SAFETY: plain default-heap buffer allocation with valid descriptions. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no default buffer"); + None + } + } + } + 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); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 82449abc..2aeef0f5 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -216,6 +216,137 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } "#; +/// Where `dxcompiler.dll` is looked for: `VICTORY_DXC` (the DLL or its +/// folder), beside the `dxil.dll` shader validation uses (the SDK ships them +/// together), then the executable's folder and System32. +fn dxc_library() -> windows::core::Result { + use windows::Win32::System::LibraryLoader::{ + LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + use windows::core::{HSTRING, w}; + let mut paths: Vec = Vec::new(); + if let Some(p) = std::env::var_os("VICTORY_DXC").map(std::path::PathBuf::from) { + let p = if p.is_dir() { p.join("dxcompiler.dll") } else { p }; + paths.push(std::fs::canonicalize(&p).unwrap_or(p)); + } + if let Some(dir) = victory_shader::emit::validator::Validator::default_path() + .and_then(|p| p.parent().map(|d| d.to_path_buf())) + { + paths.push(dir.join("dxcompiler.dll")); + } + for path in paths.iter().filter(|p| p.is_file()) { + // SAFETY: a NUL-terminated path; its folder (dxil.dll) is searched first. + if let Ok(m) = unsafe { + LoadLibraryExW( + &HSTRING::from(path.as_path()), + None, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, + ) + } { + return Ok(m); + } + } + // SAFETY: a bare name, searched only in the executable's folder and System32. + unsafe { + LoadLibraryExW( + w!("dxcompiler.dll"), + None, + LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } +} + +/// Compiles a compute shader with DXC (see [`dxc_library`]). +pub(crate) fn dxc_compile(source: &str) -> windows::core::Result> { + use windows::Win32::Graphics::Direct3D::Dxc::*; + use windows::Win32::System::LibraryLoader::GetProcAddress; + use windows::core::{Interface, w}; + type Create = unsafe extern "system" fn( + *const windows::core::GUID, + *const windows::core::GUID, + *mut *mut std::ffi::c_void, + ) -> windows::core::HRESULT; + // SAFETY: loading the compiler and calling its documented entry point with + // out pointers of ours; the buffer and arguments outlive the calls. + unsafe { + let library = dxc_library()?; + let create: Create = std::mem::transmute( + GetProcAddress(library, s!("DxcCreateInstance")) + .ok_or_else(windows::core::Error::from_thread)?, + ); + let mut raw = std::ptr::null_mut(); + create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut raw).ok()?; + let compiler = IDxcCompiler3::from_raw(raw); + let buffer = DxcBuffer { + Ptr: source.as_ptr().cast(), + Size: source.len(), + Encoding: DXC_CP_UTF8.0, + }; + let arguments = [w!("-T"), w!("cs_6_0"), w!("-E"), w!("main"), w!("-O3")]; + let result: IDxcResult = compiler.Compile(&buffer, Some(&arguments), None)?; + if let Err(e) = result.GetStatus()?.ok() { + if let Ok(errors) = result.GetErrorBuffer() { + let text = std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ); + tracing::warn!( + "argument clamp: DXC: {}", + String::from_utf8_lossy(text).trim() + ); + } + return Err(e); + } + let blob = result.GetResult()?; + let mut bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) + .to_vec(); + sign_dxc_bytecode(library, &mut bytes)?; + Ok(bytes) + } +} + +/// Older DXC DLLs can compile successfully without finding the signing DLL. +/// The resulting container has a zero digest and native D3D12 rejects it. +fn sign_dxc_bytecode( + compiler: windows::Win32::Foundation::HMODULE, + bytes: &mut [u8], +) -> windows::core::Result<()> { + use std::os::windows::ffi::OsStringExt; + use victory_shader::emit::validator::Validator; + use windows::Win32::Foundation::E_FAIL; + use windows::Win32::System::LibraryLoader::GetModuleFileNameW; + + if bytes + .get(4..20) + .is_some_and(|digest| digest.iter().any(|&b| b != 0)) + { + return Ok(()); + } + + let explicit = std::env::var_os("VICTORY_DXIL").map(std::path::PathBuf::from); + let beside_compiler = || { + let mut path = vec![0; 32_768]; + // SAFETY: the compiler module is loaded and the buffer is ours. + let len = unsafe { GetModuleFileNameW(Some(compiler), &mut path) } as usize; + if len == 0 || len >= path.len() { + return None; + } + let compiler = std::path::PathBuf::from(std::ffi::OsString::from_wide(&path[..len])); + let validator = compiler.with_file_name("dxil.dll"); + validator.is_file().then_some(validator) + }; + let path = explicit + .or_else(beside_compiler) + .or_else(Validator::default_path); + Validator::load(path.as_deref()) + .and_then(|mut validator| validator.validate(bytes)) + .map_err(|error| { + windows::core::Error::new(E_FAIL, format!("cannot sign DXC shader: {error}")) + }) +} + struct Clamp { root: ID3D12RootSignature, pso: ID3D12PipelineState, @@ -709,7 +840,7 @@ pub(crate) fn check_hit( true } -fn uav_barrier() -> D3D12_RESOURCE_BARRIER { +pub(crate) fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -952,6 +1083,254 @@ void main() { } } + const COUNT_PRODUCER_CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer count_buf : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + count_buf.Store(0, 1); +} +"#; + + /// The mesh prep must charge the groups it emits, not those it discards + /// at the output-buffer limit. A later indirect dispatch in the same list + /// must still run. Exercise both a CPU-filled count and a GPU-produced + /// count; the latter stays UAV and is ordered before prep by a UAV barrier. + fn run_mesh_budget_case(warp: &mut WarpHarness, gpu_count: bool) { + const STRIDE: u32 = 12; + const RECORDS: u32 = 2; + const ATTEMPTS: u32 = 16; + const GROUP_CAP: u32 = 16; + const COUNTED_GROUPS: u32 = 5; + const EXPECTED_MESH_BUDGET: u32 = + COUNTED_GROUPS * 128 + ATTEMPTS * GROUP_CAP * 128; + const DISPATCH_GROUPS: u32 = 64; + + let prep = compile_cs(&warp.device, crate::mesh_emu::PREP_SOURCE) + .expect("mesh indirect prep shader must compile on WARP"); + let producer = compile_cs(&warp.device, COUNT_PRODUCER_CS) + .expect("count producer shader must compile on WARP"); + let (args, args_ptr, args_gpu) = warp.shared_buffer(u64::from(STRIDE * RECORDS)); + let (count, count_ptr, count_gpu) = warp.shared_buffer(256); + let (budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (prepared, _, prepared_gpu) = warp.shared_buffer(256); + let (slot_map, slot_map_ptr, slot_map_gpu) = warp.shared_buffer(64 << 10); + let (next_args, next_args_ptr, _) = warp.shared_buffer(256); + let (hits, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let scratch = warp.default_uav(256); + let signature = warp.signature(2, STRIDE); + + // SAFETY: these mapped buffers all hold at least the written bytes. + unsafe { + let words = args_ptr.cast::(); + words.write_volatile(COUNTED_GROUPS); + words.add(1).write_volatile(1); + words.add(2).write_volatile(1); + words.add(3).write_volatile(65_535); + words.add(4).write_volatile(1); + words.add(5).write_volatile(1); + count_ptr.cast::().write_volatile(u32::from(!gpu_count)); + budget_ptr.cast::().write_volatile(0); + next_args_ptr.cast::().write_volatile(DISPATCH_GROUPS); + next_args_ptr.cast::().add(1).write_volatile(1); + next_args_ptr.cast::().add(2).write_volatile(1); + hits_ptr.cast::().write_volatile(0); + + warp.list.ResourceBarrier(&[ + transition( + &args, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &count, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &budget, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &prepared, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &slot_map, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &next_args, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + transition( + &hits, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + ]); + if gpu_count { + warp.list.SetComputeRootSignature(&producer.root); + warp.list.SetPipelineState(&producer.pso); + warp.list.SetComputeRootUnorderedAccessView(0, count_gpu); + warp.list.Dispatch(1, 1, 1); + warp.list.ResourceBarrier(&[uav_barrier()]); + } + + warp.list.ResourceBarrier(&[uav_barrier()]); + warp.list.SetComputeRootSignature(&prep.root); + warp.list.SetPipelineState(&prep.pso); + let constants = [STRIDE, RECORDS, 1, GROUP_CAP, 1, 1]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootUnorderedAccessView(1, args_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, count_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, prepared_gpu); + warp.list.SetComputeRootUnorderedAccessView(4, slot_map_gpu); + warp.list.SetComputeRootUnorderedAccessView(5, budget_gpu); + warp.list.Dispatch(1, 1, 1); + warp.list.ResourceBarrier(&[ + uav_barrier(), + transition( + &prepared, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + transition( + &slot_map, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + ]); + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list + .ExecuteIndirect(&signature, 1, &prepared, 0, None, 0); + warp.list.ResourceBarrier(&[ + transition( + &prepared, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &slot_map, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + ]); + + for _ in 0..ATTEMPTS { + warp.list.ResourceBarrier(&[uav_barrier()]); + warp.list.SetComputeRootSignature(&prep.root); + warp.list.SetPipelineState(&prep.pso); + let constants = [STRIDE, RECORDS, 1, GROUP_CAP, 0, 1]; + warp.list + .SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootUnorderedAccessView(1, args_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, count_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, prepared_gpu); + warp.list.SetComputeRootUnorderedAccessView(4, slot_map_gpu); + warp.list.SetComputeRootUnorderedAccessView(5, budget_gpu); + warp.list.Dispatch(1, 1, 1); + warp.list.ResourceBarrier(&[ + uav_barrier(), + transition( + &prepared, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + transition( + &slot_map, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + ]); + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list + .ExecuteIndirect(&signature, 1, &prepared, 0, None, 0); + warp.list.ResourceBarrier(&[ + transition( + &prepared, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + transition( + &slot_map, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ), + ]); + } + + assert!(record_clamp( + &warp.clamp, + &warp.list, + &scratch, + budget_gpu, + (&next_args, 0), + None, + (2, STRIDE, 1), + )); + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list + .ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + warp.submit_and_wait(); + + // SAFETY: the fence has completed and all mapped buffers remain live. + let (spent, count_value, hit_count, source, mapped_groups) = unsafe { + ( + budget_ptr.cast::().read_volatile(), + count_ptr.cast::().read_volatile(), + hits_ptr.cast::().read_volatile(), + std::slice::from_raw_parts(args_ptr.cast_const(), 24).to_vec(), + std::slice::from_raw_parts(slot_map_ptr.cast::(), 16).to_vec(), + ) + }; + assert_eq!(count_value, 1, "prep must honor the active record count"); + assert_eq!( + source, + [ + 5, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0xff, 0xff, 0, 0, 1, 0, 0, 0, 1, 0, + 0, 0, + ], + "prep must leave the source arguments unchanged" + ); + assert_eq!( + mapped_groups, + [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + "slot map must retain each emitted group's record-local id" + ); + assert_eq!( + spent, + EXPECTED_MESH_BUDGET + DISPATCH_GROUPS * 64, + "discarded mesh groups must not starve later indirect work" + ); + assert_eq!( + hit_count, + COUNTED_GROUPS + ATTEMPTS * GROUP_CAP + DISPATCH_GROUPS, + "mesh prep must emit the bounded dispatch and preserve later indirect work" + ); + } + + #[test] + fn warp_mesh_prep_budgets_only_emitted_groups_for_cpu_and_gpu_counts() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + run_mesh_budget_case(&mut warp, false); + run_mesh_budget_case(&mut warp, true); + } + /// The compare of copies in the card's memory (`crate::host`), on the /// software adapter. Told 1 it flags the pieces whose bytes are not /// what was hashed last and leaves the hashes: a piece a shader changed @@ -2652,3 +3031,604 @@ void work() { assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); } } + +/// What one small draw costs this card, bare and with one thing changed +/// between every two draws: a measurement, not a check (it asserts only +/// that the card answered). The timing run of the lit scene (run 187) has +/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no +/// log says whether that is what we put around a command or what the card +/// takes for one. Each variant here is 10,000 one-triangle draws into a +/// 2560x1440 target, timed on the card by one pair of timestamps around +/// the whole batch (not one per command, which would time the stamps). +/// +/// Run by name, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture` +#[cfg(test)] +mod bare_cost { + use windows::Win32::Foundation::{HANDLE, RECT}; + use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use crate::host::{compile, transition}; + + /// Draws in a batch. + const DRAWS: u32 = 10_000; + const WIDTH: u32 = 2560; + const HEIGHT: u32 = 1440; + + /// One small triangle in the middle of the target (about 180 pixels), + /// and two pixel programs that read one texel of a texture through a + /// table, so that the view heap set is in use. + const DRAW: &str = r#" +#define RS "DescriptorTable(SRV(t0))" +Texture2D image : register(t0); +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 0.02 - 0.01, 0.5, 1.0); +} +[RootSignature(RS)] +float4 first(float4 at : SV_Position) : SV_Target { + return image.Load(int3(0, 0, 0)); +} +[RootSignature(RS)] +float4 second(float4 at : SV_Position) : SV_Target { + return 1.0 - image.Load(int3(0, 0, 0)); +} +"#; + + /// A compute pass of next to nothing, as our clamp of an indirect + /// record is: one group of one thread that writes one word. + const WORK: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void work() { + words.Store(0, words.Load(0) + 1); +} +"#; + + /// What changes between every two draws of a batch. + #[derive(Clone, Copy, PartialEq)] + enum Between { + /// Nothing. + Nothing, + /// The pipeline: two alternate. + Pipeline, + /// A second texture goes from target to shader read and back. + BarrierPair, + /// The depth texture bound for testing goes from write to read or + /// back. + DepthMove, + /// The pair of descriptor heaps: two pairs alternate. + Heaps, + /// The colour target: two alternate. + Targets, + /// A compute pass of ours of one group, and the pipeline back. + Compute, + /// The same between two waits for every earlier shader write, as + /// the clamp records them. + ComputeWithWaits, + } + + struct Rig { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + root: ID3D12RootSignature, + pipelines: [ID3D12PipelineState; 2], + work_root: ID3D12RootSignature, + work: ID3D12PipelineState, + words: ID3D12Resource, + other: ID3D12Resource, + depth: ID3D12Resource, + /// Kept alive: the views below name them. + _kept: Vec, + _target_heaps: [ID3D12DescriptorHeap; 2], + heap_pairs: [[Option; 2]; 2], + tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], + targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + _depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, + depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + card: String, + } + + fn texture( + device: &ID3D12Device, + (width, height): (u32, u32), + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain texture creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn buffer( + device: &ID3D12Device, + size: u64, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..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 out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + let flags = if visible { + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + } else { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE + }; + // SAFETY: plain heap creation. + unsafe { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + } + } + + fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + // SAFETY: the description points at live data and never releases + // its pointer to the root signature. + unsafe { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + VS: code(vs), + PS: code(ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Depth is tested and never written, so the texture may be + // in the write state or in the read state under one view. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + device.CreateGraphicsPipelineState(&desc).unwrap() + } + } + + impl Rig { + /// The default adapter, as the layer takes it; `None` without one + /// or on a software adapter. + fn new() -> Option { + let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; + let ps = [ + compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, + compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, + ]; + let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; + // SAFETY: plain object creation on a device of our own; the + // views are made in heaps that live as long as the rig. + unsafe { + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok()? + .cast::() + .ok()? + .GetDesc1() + .ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let card = String::from_utf16_lossy(&desc.Description) + .trim_end_matches('\0') + .to_owned(); + 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 root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; + let pipelines = [ + pipeline(&device, &root, &vs, &ps[0]), + pipeline(&device, &root, &vs, &ps[1]), + ]; + let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; + let work: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&work_root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + + let size = (WIDTH, HEIGHT); + let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let target = [ + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + ]; + let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); + let depth = texture( + &device, + size, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let image = texture( + &device, + (4, 4), + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + ); + let words = buffer( + &device, + 64 << 10, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + let back = buffer( + &device, + 16, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut stamps: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut stamps, + ) + .ok()?; + let stamps = stamps?; + + // Target and depth views. + let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); + let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; + targets[1].ptr += rtv_step; + device.CreateRenderTargetView(&target[0], None, targets[0]); + device.CreateRenderTargetView(&target[1], None, targets[1]); + let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); + let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); + let mut depth_tested = depth_written; + depth_tested.ptr += dsv_step; + device.CreateDepthStencilView(&depth, None, depth_written); + let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); + + // Two pairs of shader-visible heaps: views (one view of the + // small texture each) and samplers (none used). + let view_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + ]; + let sampler_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + ]; + for views in &view_heaps { + device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + } + let tables = [ + view_heaps[0].GetGPUDescriptorHandleForHeapStart(), + view_heaps[1].GetGPUDescriptorHandleForHeapStart(), + ]; + let heap_pairs = [ + [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], + [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], + ]; + + // The first list: both targets and the depth texture cleared. + list.ClearRenderTargetView(targets[0], &[0.0; 4], None); + list.ClearRenderTargetView(targets[1], &[0.0; 4], None); + list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + let [first_target, second_target] = target; + let mut rig = Rig { + queue, + allocator, + list, + fence, + submitted: 0, + event, + root, + pipelines, + work_root, + work, + words, + other, + depth, + _kept: vec![first_target, second_target, image], + _target_heaps: [rtvs, dsvs], + heap_pairs, + tables, + targets, + _depth_written: depth_written, + depth_tested, + stamps, + back, + card, + }; + rig.finish(); + Some(rig) + } + } + + /// Closes the open list, runs it, waits for the card and opens the + /// list again. + fn finish(&mut self) { + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + /// What every list starts with: a new list has nothing set. + fn begin(&self) { + let l = &self.list; + // SAFETY: an open list and live objects and views. + unsafe { + l.SetDescriptorHeaps(&self.heap_pairs[0]); + l.SetGraphicsRootSignature(&self.root); + l.SetPipelineState(&self.pipelines[0]); + l.SetGraphicsRootDescriptorTable(0, self.tables[0]); + l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + // A triangle list. + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + } + } + + /// One batch of [`DRAWS`] draws in `lists` lists run one by one, + /// with `between` recorded before every draw: the microseconds a + /// draw took on the card, and the milliseconds recording took. + fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { + let (target, read, written, tested) = ( + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + let started = std::time::Instant::now(); + let mut drawn = 0u32; + for part in 0..lists { + let l = &self.list; + // SAFETY: an open list; our query heap; live objects. + unsafe { + if part == 0 { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + } + } + self.begin(); + // SAFETY: an open list with everything set; live objects. + // Every state moved is moved back within the batch (the + // draws of a list are an even number). + unsafe { + for _ in 0..DRAWS / lists { + let odd = (drawn % 2) as usize; + match between { + Between::Nothing => {} + Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), + Between::BarrierPair => { + l.ResourceBarrier(&[transition(&self.other, target, read)]); + l.ResourceBarrier(&[transition(&self.other, read, target)]); + } + Between::DepthMove => { + let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + l.ResourceBarrier(&[transition(&self.depth, from, to)]); + } + Between::Heaps => { + l.SetDescriptorHeaps(&self.heap_pairs[odd]); + l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); + } + Between::Targets => { + l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + } + Between::Compute | Between::ComputeWithWaits => { + let waits = between == Between::ComputeWithWaits; + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetComputeRootSignature(&self.work_root); + l.SetPipelineState(&self.work); + l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetPipelineState(&self.pipelines[0]); + } + } + l.DrawInstanced(3, 1, 0, 0); + drawn += 1; + } + if part + 1 < lists { + // The next list of the batch: this one is sent on + // its own and the list is opened again at once + // (the allocator is not reset before the card is + // done with all of them). + l.Close().unwrap(); + let run: ID3D12CommandList = l.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + l.Reset(&self.allocator, None).unwrap(); + } else { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + } + } + } + let recording = started.elapsed().as_secs_f64() * 1e3; + self.finish(); + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + // SAFETY: a read-back buffer the finished list resolved two + // timestamps into. + let ticks = unsafe { + self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let stamps = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + self.back.Unmap(0, None); + stamps[1].saturating_sub(stamps[0]) + }; + // SAFETY: a plain query of our queue. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); + (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + } + } + + #[test] + #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] + fn bare_command_cost() { + let Some(mut rig) = Rig::new() else { + eprintln!("no hardware adapter, or our shaders did not compile; skipped"); + return; + }; + eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + // The first batch pays for whatever the driver does at first use. + rig.batch(Between::Nothing, 1); + let variants = [ + ("(a) nothing changes between draws", Between::Nothing, 1), + ("(b) another pipeline every draw", Between::Pipeline, 1), + ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), + ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), + ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ("(f) another colour target every draw", Between::Targets, 1), + ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), + ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), + ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ]; + let mut least = Vec::new(); + for (name, between, lists) in variants { + let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!( + "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", + runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 + ); + least.push(runs[0].0); + } + assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d4936077..ef5f0b1b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -40,6 +40,8 @@ mod indirect; #[cfg(windows)] mod inplace; pub mod list; +#[cfg(windows)] +mod mesh_emu; pub mod object; pub mod pipeline; #[cfg(windows)] diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 327f07aa..5d183f2f 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -141,7 +141,7 @@ impl Shader { pub(crate) fn translated(&self) -> Option<&Translated> { self.translated .get_or_init(|| { - let done = translate(&self.container); + let done = translate(&self.container, self.stage); // `VICTORY_SHADER_SAVE=`: each shader as the title gave it (`.cdxil`) and as // translated (`.dxil`), by the hash crash reports name it with if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") { @@ -155,7 +155,10 @@ impl Shader { } if let Ok(t) = &done { KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); - KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed); + KEPT[3].fetch_add( + t.host.dxil.len() as u64, + std::sync::atomic::Ordering::Relaxed, + ); } match &done { Ok(t) => tracing::info!( @@ -179,16 +182,24 @@ impl Shader { } #[cfg(windows)] -fn translate(container: &[u8]) -> Result { +fn translate(container: &[u8], stage: &str) -> Result { + use victory_shader::emit::MeshMode; use victory_shader::{Container, FourCC, HwStage}; // The translation depends on it (a view index past a capped heap). crate::descriptor::host::probe_view_limit(); + let mesh = if stage == "mesh" + && crate::host::host().is_some_and(crate::host::Host::emulate_mesh_shaders) + { + MeshMode::Emulate + } else { + MeshMode::Native + }; + let host = crate::shader_cache::host_shader(container, mesh)?; let c = Container::parse(container).map_err(|e| e.to_string())?; let programs = match c.part(FourCC::DXIL) { Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?, None => Vec::new(), }; - let host = crate::shader_cache::host_shader(container)?; let stores = programs.is_empty() || programs.iter().any(stores); let used = programs .into_iter() diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 52dff4e6..c6a760a3 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -892,7 +892,7 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { /// compute queue waits for the depth the graphics queue draws). Our /// submissions run when they are made, so a wait for a value already /// reached is nothing; otherwise what the queue is given next is held -/// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the +/// (`Held`) until a signal or a list's bottom-of-pipe write gets the /// fence there. extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index c5365c4c..c5cbfba2 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -3,7 +3,8 @@ //! that translated it (its source fingerprint and settings, see `build`), so //! a changed translator never serves an old translation. Entries go through //! `victory-pipeline`'s content-addressed cache, which writes them -//! atomically; an entry that does not read back is translated again. +//! atomically; an entry that does not read back is translated again, and a +//! cache that cannot be written is skipped (it never fails a translation). //! //! The entry is our own encoding of [`HostShader`]: a field added to it //! must be added to `encode` and `decode` too (entries of older builds @@ -14,7 +15,7 @@ use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; -use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::emit::{HostShader, MeshEmu, MeshMode, MeshOutput, StaticSampler, UserData}; use victory_shader::resource::RootIndexedView; use victory_shader::{HwStage, RootType}; @@ -22,6 +23,9 @@ static CACHE: OnceLock = OnceLock::new(); static HITS: AtomicU64 = AtomicU64::new(0); static MISSES: AtomicU64 = AtomicU64::new(0); +/// The build fingerprint in front of every cache input, from [`build`]. +const BUILD_LEN: usize = 32; + /// Keeps translated shaders in `dir` from now on. pub fn use_shader_cache(dir: PathBuf) { match Cache::open(dir) { @@ -88,19 +92,22 @@ pub fn warm(container: &[u8]) -> Result { ran.store(true, Ordering::Relaxed); victory_shader::emit::translate(c).map_err(|e| e.to_string()) }; - cached(cache, &build(), container, translate).map(|_| ran.load(Ordering::Relaxed)) + cached(cache, &build(), MeshMode::Native, container, translate).map(|_| ran.load(Ordering::Relaxed)) } /// The translation of a console shader container, from the cache when /// there is one. -pub(crate) fn host_shader(container: &[u8]) -> Result { - let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); +pub(crate) fn host_shader(container: &[u8], mesh: MeshMode) -> Result { + let translate = + |c: &[u8]| victory_shader::emit::translate_with(c, mesh).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, &build(), container, translate), + Some(cache) => cached(cache, &build(), mesh, container, translate), None => translate(container), } } + + /// The cache entry's converter: the build and the container in, the /// encoded translation out. `ran` tells a miss from a hit. struct Translate { @@ -126,10 +133,15 @@ impl Result + Send + Sync> Converter for Tra fn cached( cache: &Cache, build: &[u8; 32], + mesh: MeshMode, container: &[u8], translate: impl Fn(&[u8]) -> Result + Send + Sync, ) -> Result { - let input = [&build[..], container].concat(); + let mesh_byte = match mesh { + MeshMode::Native => 0u8, + MeshMode::Emulate => 1u8, + }; + let input = [&build[..], &[mesh_byte], container].concat(); let converter = Translate { translate, ran: AtomicBool::new(false), @@ -191,7 +203,7 @@ fn root_type(code: u32) -> RootType { } } -/// Little-endian words and length-prefixed lists. +/// then the raw value for [`RootType::Other`]. fn encode(s: &HostShader) -> Vec { let mut out = MAGIC.to_vec(); let word = |out: &mut Vec, v: u32| out.extend(v.to_le_bytes()); @@ -201,9 +213,13 @@ fn encode(s: &HostShader) -> Vec { out.extend(&s.dxil); word(&mut out, s.user_data.len() as u32); for u in &s.user_data { - for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { + for v in [u.index, u32::from(u.slot), root_code(u.root)] { word(&mut out, v); } + if let RootType::Other(raw) = u.root { + word(&mut out, raw); + } + word(&mut out, u.dword); } word(&mut out, s.samplers.len() as u32); for sampler in &s.samplers { @@ -246,6 +262,44 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, value); } } + let encode_outputs = |out: &mut Vec, items: &[MeshOutput]| { + word(out, items.len() as u32); + for o in items { + let name = o.name.as_bytes(); + word(out, name.len() as u32); + out.extend(name); + for v in [ + o.index, + u32::from(o.kind), + u32::from(o.comp), + u32::from(o.interp), + o.row.unwrap_or(u32::MAX), + u32::from(o.col), + u32::from(o.cols), + o.dword_offset, + ] { + word(out, v); + } + } + }; + match &s.mesh_emu { + None => word(&mut out, 0), + Some(m) => { + word(&mut out, 1); + for v in [ + m.threads, + m.max_vertices, + m.max_primitives, + m.vertex_dwords, + m.prim_dwords, + u32::from(m.reads_group_id), + ] { + word(&mut out, v); + } + encode_outputs(&mut out, &m.vertex_outputs); + encode_outputs(&mut out, &m.prim_outputs); + } + } out } @@ -264,6 +318,36 @@ fn decode(bytes: &[u8]) -> Option { let n = self.word()? as usize; Some(self.take(n)?.to_vec()) } + fn outputs(&mut self) -> Option> { + let n = self.word()? as usize; + let mut out = Vec::with_capacity(n.min(256)); + for _ in 0..n { + let name = String::from_utf8(self.list()?).ok()?; + let index = self.word()?; + let kind = u8::try_from(self.word()?).ok()?; + let comp = u8::try_from(self.word()?).ok()?; + let interp = u8::try_from(self.word()?).ok()?; + let row = match self.word()? { + u32::MAX => None, + r => Some(r), + }; + let col = u8::try_from(self.word()?).ok()?; + let cols = u8::try_from(self.word()?).ok()?; + let dword_offset = self.word()?; + out.push(MeshOutput { + name, + index, + kind, + comp, + interp, + row, + col, + cols, + dword_offset, + }); + } + Some(out) + } } let mut r = Reader(bytes); if r.take(4)? != MAGIC { @@ -274,10 +358,22 @@ fn decode(bytes: &[u8]) -> Option { let n = r.word()? as usize; let mut user_data = Vec::with_capacity(n.min(256)); for _ in 0..n { + let index = r.word()?; + let slot = u8::try_from(r.word()?).ok()?; + let root = match r.word()? { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 2 => RootType::Table, + 3 => RootType::ImmediateSampler, + 4 => RootType::ResourceHeap, + 5 => RootType::SamplerHeap, + OTHER_ROOT => RootType::Other(r.word()?), + _ => return None, + }; user_data.push(UserData { - index: r.word()?, - slot: u8::try_from(r.word()?).ok()?, - root: root_type(r.word()?), + index, + slot, + root, dword: r.word()?, }); } @@ -303,6 +399,11 @@ fn decode(bytes: &[u8]) -> Option { let root_cbvs = r.list()?; let root_srvs = r.list()?; let root_uavs = r.list()?; + let flag = |w: u32| match w { + 0 => Some(false), + 1 => Some(true), + _ => None, + }; let n = r.word()? as usize; let mut root_indexed_views = Vec::with_capacity(n.min(256)); for _ in 0..n { @@ -314,6 +415,20 @@ fn decode(bytes: &[u8]) -> Option { shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, }); } + let mesh_emu = match r.word()? { + 0 => None, + 1 => Some(MeshEmu { + threads: r.word()?, + max_vertices: r.word()?, + max_primitives: r.word()?, + vertex_dwords: r.word()?, + prim_dwords: r.word()?, + reads_group_id: flag(r.word()?)?, + vertex_outputs: r.outputs()?, + prim_outputs: r.outputs()?, + }), + _ => return None, + }; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -324,12 +439,14 @@ fn decode(bytes: &[u8]) -> Option { root_srvs, root_uavs, root_indexed_views, + mesh_emu, }) } #[cfg(test)] mod tests { use super::*; + use victory_pipeline::CacheKey; fn shader() -> HostShader { HostShader { @@ -358,9 +475,59 @@ mod tests { byte_offset: 32, shift: 5, }], + mesh_emu: None, } } + fn mesh_emu_shader() -> HostShader { + let mut s = shader(); + s.stage = HwStage::Ms; + s.mesh_emu = Some(MeshEmu { + threads: 64, + max_vertices: 32, + max_primitives: 16, + vertex_dwords: 8, + prim_dwords: 4, + reads_group_id: true, + vertex_outputs: vec![ + MeshOutput { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: None, + col: 0, + cols: 4, + dword_offset: 0, + }, + MeshOutput { + name: "COLOR".into(), + index: 0, + kind: 0, + comp: 9, + interp: 2, + row: Some(0), + col: 0, + cols: 4, + dword_offset: 4, + }, + ], + prim_outputs: vec![MeshOutput { + name: "PRIMID".into(), + index: 0, + kind: 0, + comp: 5, + interp: 1, + row: Some(1), + col: 0, + cols: 1, + dword_offset: 0, + }], + }); + s + } + #[test] fn translations_come_back_from_the_cache() { let dir = tempfile::tempdir().unwrap(); @@ -372,26 +539,53 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, MeshMode::Native, container, translate), + Ok(shader()) + ); + assert_eq!( + cached(&cache, &build, MeshMode::Native, container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); + // Another converter id caches separately. + let emu_runs = AtomicU64::new(0); + let emu_translate = |_: &[u8]| { + emu_runs.fetch_add(1, Ordering::Relaxed); + Ok(mesh_emu_shader()) + }; + assert_eq!( + cached(&cache, &build, MeshMode::Emulate, container, emu_translate), + Ok(mesh_emu_shader()) + ); + assert_eq!(emu_runs.load(Ordering::Relaxed), 1); + // Another build translates again. - assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &[8; 32], MeshMode::Native, container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 2); // A damaged entry is a miss, translated and stored again. for e in walk(dir.path()) { - std::fs::write(e, b"VSH1 broken").unwrap(); + std::fs::write(e, b"VSH3 broken").unwrap(); } - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, MeshMode::Native, container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 3); - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!( + cached(&cache, &build, MeshMode::Native, container, translate), + Ok(shader()) + ); assert_eq!(runs.load(Ordering::Relaxed), 3); // Failures are not stored. let fail = |_: &[u8]| Err::("unsupported".to_owned()); - assert!(cached(&cache, &build, b"other", fail).is_err()); + assert!(cached(&cache, &build, MeshMode::Native, b"other", fail).is_err()); } fn walk(dir: &std::path::Path) -> Vec { @@ -406,12 +600,221 @@ mod tests { files } + /// A shader with every field at an unusual value. + fn rich_shader() -> HostShader { + HostShader { + stage: HwStage::Gs, + dxil: (0u8..=255).collect(), + user_data: vec![ + UserData { + index: 0, + slot: 0, + root: RootType::Constants, + dword: 1, + }, + UserData { + index: 7, + slot: 255, + root: RootType::Other(0xdead_beef), + dword: u32::MAX, + }, + UserData { + index: u32::MAX, + slot: 2, + root: RootType::SamplerHeap, + dword: 3, + }, + ], + samplers: vec![[1, 2, 3, 4], [0, 0, 0, 0]], + static_samplers: vec![ + StaticSampler::from_words([0x400, 0xc0_0000, 0x18f0_0000, 0]), + StaticSampler::from_words([0, 0, 0, 0]), + ], + root_cbvs: vec![0, 1, 255], + root_srvs: vec![2], + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + mesh_emu: None, + } + } + #[test] fn entries_round_trip_and_reject_damage() { - let bytes = encode(&shader()); - assert_eq!(decode(&bytes), Some(shader())); - assert_eq!(decode(&bytes[..bytes.len() - 1]), None); - assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); - assert_eq!(decode(b"VSH0"), None); + for shader in [shader(), mesh_emu_shader()] { + let bytes = encode(&shader); + assert_eq!(decode(&bytes), Some(shader)); + assert_eq!(decode(&bytes[..bytes.len() - 1]), None); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); + } + assert_eq!(decode(b"VSH2"), None); + } + + #[test] + fn the_whole_shader_survives_the_round_trip() { + assert_eq!(decode(&encode(&rich_shader())), Some(rich_shader())); + } + + #[test] + fn every_stage_round_trips() { + let stages = [ + HwStage::Ls, + HwStage::Hs, + HwStage::Es, + HwStage::Gs, + HwStage::Vs, + HwStage::Ps, + HwStage::Ms, + HwStage::Cs, + ]; + for stage in stages { + let mut s = shader(); + s.stage = stage; + assert_eq!(decode(&encode(&s)), Some(s.clone()), "{stage:?}"); + } } + + #[test] + fn every_root_type_round_trips() { + let roots = [ + RootType::Constants, + RootType::Descriptor, + RootType::Table, + RootType::ImmediateSampler, + RootType::ResourceHeap, + RootType::SamplerHeap, + RootType::Other(0), + RootType::Other(1), + RootType::Other(6), + RootType::Other(u32::MAX), + ]; + for root in roots { + let mut s = shader(); + s.user_data[0].root = root; + assert_eq!(decode(&encode(&s)), Some(s.clone()), "{root:?}"); + } + } + + #[test] + fn every_truncation_is_not_a_shader() { + let bytes = encode(&rich_shader()); + for n in 0..bytes.len() { + assert_eq!(decode(&bytes[..n]), None, "{n} of {} bytes", bytes.len()); + } + assert_eq!(decode(&bytes), Some(rich_shader())); + } + + #[test] + fn impossible_lengths_are_not_shaders() { + let s = rich_shader(); + let bytes = encode(&s); + + // The DXIL length (after the magic and the stage). + let mut b = bytes.clone(); + b[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(decode(&b), None, "an oversized DXIL"); + + // The user-data count (after the DXIL). + let at = 12 + s.dxil.len(); + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(decode(&b), None, "too many user-data entries"); + + // The root-SRV list's length: the bytes it promises are not there. + let mut at = 12 + s.dxil.len() + 4; + for u in &s.user_data { + at += 16 + usize::from(matches!(u.root, RootType::Other(_))) * 4; + } + at += 4 + s.samplers.len() * 16; + at += 4 + s.static_samplers.len() * 40; + at += 4 + s.root_cbvs.len(); + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(decode(&b), None, "a root SRV list that is not there"); + } + + #[test] + fn unknown_root_tags_are_not_shaders() { + let s = shader(); + let bytes = encode(&s); + // The first user-data entry: count, index, slot, then the root tag. + let at = 12 + s.dxil.len() + 4 + 4 + 4; + for tag in [7u32, 1000, u32::MAX] { + let mut b = bytes.clone(); + b[at..at + 4].copy_from_slice(&tag.to_le_bytes()); + assert_eq!(decode(&b), None, "{tag}"); + } + } + + #[test] + fn damaged_entries_never_panic() { + let bytes = encode(&rich_shader()); + for at in 0..bytes.len() { + for xor in [0x01u8, 0x80, 0xff] { + let mut b = bytes.clone(); + b[at] ^= xor; + let _ = decode(&b); + } + } + // Entries that are not one of ours: arbitrary bytes behind the magic. + let mut state = 0x9e37_79b9_7f4a_7c15u64; + for len in 0..96 { + let mut b = b"VSH1".to_vec(); + for _ in 0..len { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + b.push(state as u8); + } + let _ = decode(&b); + } + } + + #[test] + fn each_container_and_build_keeps_its_own_entry() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let runs = AtomicU64::new(0); + let translate = |c: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + let mut s = shader(); + s.dxil = c.to_vec(); + Ok(s) + }; + let of = |c: &[u8]| { + let mut s = shader(); + s.dxil = c.to_vec(); + s + }; + let (a, b) = (b"first container".as_slice(), b"second container"); + assert_eq!( + cached(&cache, &[7; 32], MeshMode::Native, a, translate), + Ok(of(a)) + ); + assert_eq!( + cached(&cache, &[7; 32], MeshMode::Native, b, translate), + Ok(of(b)) + ); + assert_eq!(runs.load(Ordering::Relaxed), 2); + assert_eq!(walk(dir.path()).len(), 2, "one entry per container"); + + assert_eq!( + cached(&cache, &[7; 32], MeshMode::Native, a, translate), + Ok(of(a)) + ); + assert_eq!( + cached(&cache, &[7; 32], MeshMode::Native, b, translate), + Ok(of(b)) + ); + assert_eq!(runs.load(Ordering::Relaxed), 2, "both came from the cache"); + + // Another build's translation is a separate entry too. + assert_eq!( + cached(&cache, &[8; 32], MeshMode::Native, b, translate), + Ok(of(b)) + ); + assert_eq!(runs.load(Ordering::Relaxed), 3); + assert_eq!(walk(dir.path()).len(), 3); + } + + } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 838826e1..501828ae 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,6 +1,6 @@ //! `gameinput.dll`: input devices from the host. Gamepads come from XInput -//! (host slots 0-3); while none is connected, the keyboard drives one -//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! (host slots 0-3); while none is active, the keyboard drives one stand-in +//! gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own //! too. A poll thread turns host state into readings (a new one per change) //! and runs device callbacks on connect and disconnect. #![allow(non_snake_case)] @@ -93,6 +93,25 @@ struct PadState { right_y: f32, } +/// XInput rest thresholds (`XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE` and +/// `XINPUT_GAMEPAD_TRIGGER_THRESHOLD`), so virtual or untouched controllers +/// do not silence the keyboard stand-in pad. +const LEFT_STICK_DEADZONE: f32 = 7849.0 / 32767.0; +const RIGHT_STICK_DEADZONE: f32 = 8689.0 / 32767.0; +const TRIGGER_DEADZONE: f32 = 30.0 / 255.0; + +impl PadState { + fn is_active(&self) -> bool { + self.buttons != 0 + || self.left_trigger > TRIGGER_DEADZONE + || self.right_trigger > TRIGGER_DEADZONE + || self.left_x.abs() > LEFT_STICK_DEADZONE + || self.left_y.abs() > LEFT_STICK_DEADZONE + || self.right_x.abs() > RIGHT_STICK_DEADZONE + || self.right_y.abs() > RIGHT_STICK_DEADZONE + } +} + /// One key held down: scan code (0xE0xx when extended), character, key. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -105,12 +124,41 @@ struct KeyState { const _: () = assert!(size_of::() == 12 && size_of::() == 28); +/// The mouse as the stand-in pad's camera (`VICTORY_MOUSE`): its movement +/// since the last poll as right-stick deflection (right and up positive), +/// and its buttons as triggers. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct MouseState { + x: f32, + y: f32, + left: bool, + right: bool, +} + +/// `pad` with the mouse added: movement on the right stick, the left button +/// on the right trigger, the right button on the left trigger (as in games +/// played with a mouse: right aims, left fires). Keys and mouse add up. +fn with_mouse(pad: PadState, mouse: MouseState) -> PadState { + let held = |b: bool| if b { 1.0 } else { 0.0 }; + PadState { + right_x: (pad.right_x + mouse.x).clamp(-1.0, 1.0), + right_y: (pad.right_y + mouse.y).clamp(-1.0, 1.0), + right_trigger: pad.right_trigger.max(held(mouse.left)), + left_trigger: pad.left_trigger.max(held(mouse.right)), + ..pad + } +} + /// Host input, or a fake in tests. trait Source: Send { /// The pad in host slot `slot`, `None` when the slot is empty. fn pad(&mut self, slot: usize) -> Option; /// Keys held down; none while the title's window lacks focus. fn keys(&mut self) -> Vec; + /// The mouse as a camera; nothing unless enabled and focused. + fn mouse(&mut self) -> MouseState { + MouseState::default() + } /// Motor speeds: low frequency (left), high frequency (right). fn rumble(&mut self, slot: usize, low: u16, high: u16); } @@ -320,6 +368,9 @@ struct Slot { struct State { slots: [Slot; DEVICES], + /// Host pad slots that have reported input outside rest thresholds since + /// connecting (cleared when all host pads are idle and fallback keys fire). + engaged: [bool; PADS], callbacks: Vec, /// Asynchronous enumerations, delivered by the next poll. pending: Vec, @@ -366,6 +417,7 @@ impl Hub { source: Mutex::new(source), state: Mutex::new(State { slots: Default::default(), + engaged: [false; PADS], callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), @@ -401,12 +453,12 @@ impl Hub { /// Reads the host once; device callbacks run on the calling thread. fn poll(&self) { - let (pads, keys) = { + let (pads, keys, mouse) = { let mut source = lock(&self.source); let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); - (pads, source.keys()) + (pads, source.keys(), source.mouse()) }; - let events = self.state().poll(&self.devices, pads, keys); + let events = self.state().poll(&self.devices, pads, keys, mouse); self.deliver(events); } @@ -451,14 +503,30 @@ impl State { devices: &[Device; DEVICES], pads: [Option; PADS], keys: Vec, + mouse: MouseState, ) -> Vec { let now = now(); let mut events = std::mem::take(&mut self.pending); - let any_pad = pads.iter().any(Option::is_some); + let mut any_active = false; + for (slot, pad) in pads.iter().enumerate() { + match pad { + Some(p) if p.is_active() => { + self.engaged[slot] = true; + any_active = true; + } + None => self.engaged[slot] = false, + _ => {} + } + } + let stand_in = with_mouse(fallback(&keys), mouse); + if !any_active && stand_in != PadState::default() { + self.engaged = [false; PADS]; + } + let using_pad = self.engaged.iter().any(|&e| e); for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); } - let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); + let fallback = (!using_pad).then_some(Value::Pad(stand_in)); self.update(devices, FALLBACK, fallback, now, &mut events); self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); events @@ -602,7 +670,7 @@ extern "system" fn current_reading( }; let found = if device.is_null() { (0..DEVICES) - .filter(|&i| state.slots[i].connected) + .filter(|&i| state.slots[i].connected && (i >= PADS || state.engaged[i])) .filter_map(newest) .max_by_key(|r| r.timestamp) } else { @@ -1072,6 +1140,7 @@ pub(crate) fn module() -> HleModule { mod host { use std::time::{Duration, Instant}; + use windows_sys::Win32::Foundation::{POINT, RECT}; use windows_sys::Win32::System::Threading::GetCurrentProcessId; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, @@ -1085,7 +1154,7 @@ mod host { XInputSetState, }; use windows_sys::Win32::UI::WindowsAndMessaging::{ - GetForegroundWindow, GetWindowThreadProcessId, + GetCursorPos, GetForegroundWindow, GetWindowRect, GetWindowThreadProcessId, IsWindow, SetCursorPos, }; use super::*; @@ -1127,9 +1196,47 @@ mod host { } } + /// Right-stick deflection per pixel the mouse moves in one poll, at + /// sensitivity 1: 20 pixels in 8 ms is the full stick. + /// Full stick at 4000 pixels of mouse travel per second. + const STICK_PER_PIXEL_SECOND: f32 = 1.0 / 4000.0; + #[derive(Default)] pub(super) struct Host { empty_until: [Option; PADS], + /// The cursor was put in the window's centre at the last poll, so its + /// distance from there is the mouse's movement since. + mouse_centred: bool, + /// Smoothed mouse velocity in pixels per poll: an exponential + /// moving average (half-life 50 ms of wall time) of the per-poll + /// deltas. Polls outnumber the title's frames, so raw per-poll + /// slices mostly never reach a frame; the average keeps the + /// stick proportional to the mouse's speed across the slow + /// frames, and unlike a sum it neither saturates on steady + /// sweeps nor lingers once the mouse stops. + mouse_x: f32, + mouse_y: f32, + mouse_decayed: Option, + /// The window capture started on; re-centring pauses while any + /// other window (a text-entry dialog shares the process, so the + /// focus check alone passes it) is in front. + game_window: Option, + } + + /// `VICTORY_MOUSE`: the mouse drives the stand-in pad's camera while the + /// title's window has focus, at this sensitivity (`1` is the default + /// speed; unset, empty or `0`: off). The cursor is held in the window's + /// centre meanwhile; switching windows releases it. + fn mouse_sensitivity() -> Option { + static SENSITIVITY: LazyLock> = LazyLock::new(|| { + std::env::var("VICTORY_MOUSE") + .ok()? + .trim() + .parse::() + .ok() + .filter(|s| s.is_finite() && *s > 0.0) + }); + *SENSITIVITY } impl Source for Host { @@ -1188,6 +1295,76 @@ mod host { .collect() } + fn mouse(&mut self) -> MouseState { + let Some(sensitivity) = mouse_sensitivity() else { + return MouseState::default(); + }; + if !focused() { + self.mouse_centred = false; + self.mouse_x = 0.0; + self.mouse_y = 0.0; + return MouseState::default(); + } + // SAFETY: plain queries. + let window = unsafe { GetForegroundWindow() } as isize; + if self.game_window.is_none_or(|w| unsafe { IsWindow(w as _) } == 0) { + // Capture starts on the first in-process foreground window; + // when that window closes (a startup dialog), capture moves + // to whatever is in front then. + self.game_window = Some(window); + } + if Some(window) != self.game_window { + // Another window of ours is in front (the text-entry + // dialog shares the process): the user needs the cursor. + self.mouse_centred = false; + self.mouse_x = 0.0; + self.mouse_y = 0.0; + return MouseState::default(); + } + let mut rect = RECT::default(); + let mut at = POINT::default(); + // SAFETY: plain queries on our own foreground window; the + // outputs are ours. + let (centre, read) = unsafe { + if GetWindowRect(window as _, &mut rect) == 0 { + return MouseState::default(); + } + let centre = ((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2); + let read = GetCursorPos(&mut at) != 0; + SetCursorPos(centre.0, centre.1); + (centre, read) + }; + // The first poll after gaining focus only centres the cursor. + let moved = std::mem::replace(&mut self.mouse_centred, true) && read; + // v = alpha*speed + (1-alpha)*v, alpha by the wall time + // since the last poll (half-life 50 ms). Speed is pixels per + // second — dividing the delta out of the poll interval keeps + // the camera independent of how long polls take. + let now = Instant::now(); + let elapsed = self.mouse_decayed.replace(now); + let (keep, dt) = elapsed.map_or((0.0, 0.0), |then| { + let secs = (now - then).as_secs_f32().max(0.001); + (0.5f32.powf(secs / 0.05), secs) + }); + self.mouse_x *= keep; + self.mouse_y *= keep; + if moved && dt > 0.0 { + let alpha = 1.0 - keep; + self.mouse_x += (at.x - centre.0) as f32 / dt * alpha; + self.mouse_y += (at.y - centre.1) as f32 / dt * alpha; + } + let (x, y) = (self.mouse_x, self.mouse_y); + let scale = STICK_PER_PIXEL_SECOND * sensitivity; + MouseState { + x: x * scale, + y: -(y) * scale, + // SAFETY: a plain query (VK_LBUTTON). + left: unsafe { GetAsyncKeyState(0x01) } < 0, + // SAFETY: a plain query (VK_RBUTTON). + right: unsafe { GetAsyncKeyState(0x02) } < 0, + } + } + fn rumble(&mut self, slot: usize, low: u16, high: u16) { let speeds = XINPUT_VIBRATION { wLeftMotorSpeed: low, @@ -1284,6 +1461,7 @@ mod tests { struct FakeHost { pads: [Option; PADS], keys: Vec, + mouse: MouseState, rumble: Vec<(usize, u16, u16)>, } @@ -1296,6 +1474,9 @@ mod tests { fn keys(&mut self) -> Vec { self.0.lock().unwrap().keys.clone() } + fn mouse(&mut self) -> MouseState { + self.0.lock().unwrap().mouse + } fn rumble(&mut self, slot: usize, low: u16, high: u16) { self.0.lock().unwrap().rumble.push((slot, low, high)); } @@ -1626,4 +1807,177 @@ mod tests { rumble(device, std::ptr::null()); assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); } + + fn current_any(hub: &Hub, kind: u32) -> Result<*const Reading, HRESULT> { + type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let hr = + slot::(&hub.object, 0x20)(&hub.object, kind, std::ptr::null(), &mut out); + result(hr, out) + } + + #[test] + fn idle_host_pads_keep_the_keyboard_stand_in_until_active() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + // 1. An all-zero virtual XInput pad (e.g. a keyboard presenting an unused + // XInput slot) connects its own slot without disconnecting `FALLBACK`. + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!(log.lock().unwrap()[1..], [(0, STATUS_CONNECTED, 0)]); + + host.lock().unwrap().keys = vec![key(0x0D), key(b'W')]; + hub.poll(); + let stand_in = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!( + pad(stand_in), + PadState { + buttons: A, + left_y: 1.0, + ..Default::default() + } + ); + release(stand_in); + + // Sub-deadzone stick/trigger drift on slot 0 does not steal null-device + // `GetCurrentReading(GAMEPAD_KIND, null)` away from `FALLBACK`. + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[0] = Some(PadState { + left_x: 0.15, + right_y: -0.20, + left_trigger: 0.05, + ..Default::default() + }); + hub.poll(); + let any = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(any).buttons, A); + release(any); + + // Releasing keys keeps `FALLBACK` connected and reports the neutral edge. + host.lock().unwrap().keys.clear(); + hub.poll(); + let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(rest), PadState::default()); + release(rest); + + // 2. Real input outside deadzone on slot 1 disconnects `FALLBACK` and + // takes priority even while slot 0 keeps sub-deadzone jitter. + let active_pad = PadState { + buttons: B, + left_x: 0.6, + ..Default::default() + }; + host.lock().unwrap().pads[1] = Some(active_pad); + hub.poll(); + assert_eq!( + log.lock().unwrap()[2..], + [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] + ); + assert_eq!( + current(hub, GAMEPAD_KIND, FALLBACK), + Err(DEVICE_DISCONNECTED) + ); + + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[0] = Some(PadState { + left_x: 0.12, + ..Default::default() + }); + hub.poll(); + let any = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(any), active_pad); + release(any); + + // Releasing the physical controller back to neutral keeps pad mode engaged + // without reconnecting `FALLBACK` between button presses. + host.lock().unwrap().pads[1] = Some(PadState::default()); + hub.poll(); + assert_eq!( + current(hub, GAMEPAD_KIND, FALLBACK), + Err(DEVICE_DISCONNECTED) + ); + let neutral_pad = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(neutral_pad), PadState::default()); + release(neutral_pad); + + // 3. Pressing a fallback key while all host pads are idle hands control + // back to `FALLBACK` cleanly. + host.lock().unwrap().keys = vec![key(0x0D)]; + hub.poll(); + assert_eq!(log.lock().unwrap()[4..], [(FALLBACK, STATUS_CONNECTED, 0)]); + let back = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(back).buttons, A); + release(back); + } + + #[test] + fn the_mouse_adds_to_the_stand_in_pads_camera_and_triggers() { + let mouse = MouseState { + x: 0.25, + y: -0.5, + left: true, + right: false, + }; + let pad = with_mouse(PadState::default(), mouse); + assert_eq!( + ( + pad.right_x, + pad.right_y, + pad.right_trigger, + pad.left_trigger + ), + (0.25, -0.5, 1.0, 0.0) + ); + let keys = fallback(&[key(b'L'), key(b'Z')]); + let both = with_mouse( + keys, + MouseState { + x: 0.75, + right: true, + ..Default::default() + }, + ); + assert_eq!((both.right_x, both.left_trigger), (1.0, 1.0)); + assert_eq!(with_mouse(keys, MouseState::default()), keys); + } + + #[test] + fn the_mouse_reaches_the_stand_in_pad_but_not_a_real_one() { + let (hub, host) = fake(); + host.lock().unwrap().mouse = MouseState { + x: -0.5, + y: 0.25, + left: true, + right: true, + }; + hub.poll(); + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!( + pad(r), + PadState { + right_x: -0.5, + right_y: 0.25, + left_trigger: 1.0, + right_trigger: 1.0, + ..Default::default() + } + ); + release(r); + let real = PadState { + buttons: A, + ..Default::default() + }; + host.lock().unwrap().pads[0] = Some(real); + hub.poll(); + let r = current(hub, GAMEPAD_KIND, 0).unwrap(); + assert_eq!(pad(r), real); + release(r); + assert_eq!( + current(hub, GAMEPAD_KIND, FALLBACK), + Err(DEVICE_DISCONNECTED) + ); + } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 63c4de74..f30cd93e 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -59,6 +59,7 @@ pub(crate) struct Lowered { pub samplers: Vec<[u32; 4]>, /// The wave size the shader requires of the host, if any. pub wave_size: Option, + pub mesh_emu: Option, /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, @@ -78,6 +79,7 @@ pub(crate) struct Parts<'a> { pub prims: Vec, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, + pub emulate_mesh: bool, } enum Stop { @@ -295,6 +297,8 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// Mesh shader lowered to compute + buffer output when emulating. + mesh_emu: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -358,7 +362,9 @@ fn lane_regions(st: &Structured) -> Option)>> { for (b, e) in st.exits.iter().enumerate() { match *e { LaneExit::Jump(t) => succ[b].push(t), - LaneExit::Branch { taken, not_taken, .. } => { + LaneExit::Branch { + taken, not_taken, .. + } => { succ[b].push(taken); succ[b].push(not_taken); } @@ -369,7 +375,17 @@ fn lane_regions(st: &Structured) -> Option)>> { // post-dominators (bitsets; a virtual exit after every End) let words = n.div_ceil(64); let full = vec![u64::MAX; words]; - let mut pdom: Vec> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect(); + let mut pdom: Vec> = (0..n) + .map(|b| { + if succ[b].is_empty() { + let mut v = vec![0; words]; + v[b / 64] |= 1 << (b % 64); + v + } else { + full.clone() + } + }) + .collect(); let mut changed = true; while changed { changed = false; @@ -392,8 +408,16 @@ fn lane_regions(st: &Structured) -> Option)>> { } let mut regions = Vec::new(); for (d, e) in st.exits.iter().enumerate() { - let LaneExit::Branch { when, .. } = *e else { continue }; - if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { + let LaneExit::Branch { when, .. } = *e else { + continue; + }; + if st.wide.contains(&d) + || st + .bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { continue; // a wave-wide or uniform branch: all lanes go the same way } // blocks reachable from the lane branch that do not post-dominate it @@ -418,7 +442,10 @@ fn lane_regions(st: &Structured) -> Option)>> { pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option> { let mut out = Vec::new(); for (d, region) in lane_regions(st)? { - if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) { + if needs + .iter() + .any(|&b| region.get(b).copied().unwrap_or(false)) + { st.wave_any.get(d).copied().flatten()?; out.push(d); } @@ -457,7 +484,10 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { let mut same: HashSet = HashSet::new(); for b in crate::ir::reverse_postorder(&p.blocks) { let block = &p.blocks[b]; - let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + let whole = block + .preds + .iter() + .all(|&q| all.get(q).copied().unwrap_or(false)); for phi in &block.phis { if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { same.insert(phi.value); @@ -483,14 +513,18 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { let alike = ops.iter().all(|op| match *op { Operand::Vector { reg, .. } => { // every dword of the operand the instruction reads from that register on - let read: Vec = - inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); + let read: Vec = inst + .reads + .iter() + .filter(|r| matches!(r.0, Reg::V(x) if x >= reg)) + .map(|r| r.1) + .collect(); !read.is_empty() && read.iter().all(|x| same.contains(x)) } // a scalar is one value; a lane mask is not, unless a compare of such values made it - Operand::Scalar { code, .. } if code != NULL => { - inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) - } + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .is_none_or(|x| !is_mask(x) || same.contains(&x)), _ => true, }); if alike { @@ -565,7 +599,10 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s }; // One instruction outside a section: the kind of what it writes, and whether it is a // first lane's reservation. - let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { + let step = |inst: &Inst, + kind: &HashMap, + firsts: &mut HashSet| + -> Result<(Wave, bool), Why> { let name = inst.name(); let val = |op: &Operand| match *op { Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), @@ -581,7 +618,9 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s } o } - Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + Fields::Buffer { data, .. } + if name.contains("_atomic_") || name.contains("_store_") => + { data.iter().copied().collect() } _ => Vec::new(), @@ -601,14 +640,20 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s return Err(why(k)); } } - let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); + let w = kinds + .iter() + .copied() + .find(|&k| wild(k)) + .unwrap_or(Wave::Mixed); let sum = |k: Wave| k == Wave::Total(Op::AddU); let is_mask = |o: &Operand| { val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) }; let mut reserved = false; let out = match (name, &kinds[..]) { - ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::First + } ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { Wave::Total(Op::AddU) } @@ -623,7 +668,11 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s // nothing wave-dependent goes in; what derives from a reserved base stays marked _ if !kinds.iter().any(|&k| wild(k)) => { let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); - if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } + if derives && kinds.contains(&Wave::Base) { + Wave::Base + } else { + Wave::Plain + } } ("v_mov_b32" | "s_mov_b32", [k]) => *k, ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { @@ -649,7 +698,9 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s } ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, - (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => { + Wave::Prefix + } (x, y) if sum(x) && sum(y) => x, _ => return Err(why(w)), }, @@ -669,7 +720,11 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s *x } ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { - if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + if *c == Wave::Base { + Wave::Base + } else { + Wave::Prefix + } } // the reservation: the first lane adds its wave's total to a shared counter (_, [Wave::Total(op)]) if name.contains("_atomic_") => { @@ -694,9 +749,14 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s }; Ok((out, reserved)) }; - let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + let sections: Vec<_> = (0..p.blocks.len()) + .map(|b| super::wave::sections(p, b)) + .collect(); let order = crate::ir::reverse_postorder(&p.blocks); - let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + let pass = |kind: &mut HashMap, + firsts: &mut HashSet, + check: bool| + -> Result<(), (usize, Why)> { for &b in &order { let block = &p.blocks[b]; for phi in &block.phis { @@ -725,14 +785,20 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { Wave::Plain | Wave::Base => Wave::Total(op), // the first lane's own sum of a total is that total - Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), - _ => Wave::Mixed, - }, - Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { - Wave::Plain | Wave::Base => Wave::Prefix, - Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => { + Wave::Total(op) + } _ => Wave::Mixed, }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => { + match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => { + Wave::Prefix + } + _ => Wave::Mixed, + } + } Some(_) => Wave::Mixed, }; put(kind, w, k); @@ -750,7 +816,8 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s }; // the same test as `Lower::inst`'s `effect` let effect = matches!(inst.fields, Fields::Exp { .. }) - || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || matches!(inst.fields, Fields::Flat { .. }) + && !name.starts_with("global_load_") || name.contains("store") || name.contains("atomic") || matches!(inst.fields, Fields::Ds { .. }) @@ -765,7 +832,11 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s let mut kw = match r { // "some lane is counted" keeps the count's kind; any other SCC is one bit of data Reg::Scc if !name.starts_with("s_bcnt1") => { - if wild(k) { Wave::Mixed } else { Wave::Plain } + if wild(k) { + Wave::Mixed + } else { + Wave::Plain + } } _ => k, }; @@ -773,7 +844,10 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s if guarded && matches!(r, Reg::V(_)) && kw == Wave::Plain - && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + && matches!( + of(kind, inst.read(r)), + Wave::First | Wave::Total(_) | Wave::Prefix + ) { kw = Wave::Mixed; } @@ -836,12 +910,18 @@ fn meeting_mode() -> u32 { /// barrier as before. What that cannot order is a write and a read inside one region (blocks /// joined without an all-lane block between them): refused. /// shortcut: two writes in one region are taken not to hit the same dword from both halves. -fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option> { +fn lds_meetings( + p: &crate::ir::Program, + st: &Structured, + all: &[bool], +) -> Option> { let n = st.exits.len(); let succ = |b: usize| -> Vec { match st.exits[b] { LaneExit::Jump(t) => vec![t], - LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken], + LaneExit::Branch { + taken, not_taken, .. + } => vec![taken, not_taken], LaneExit::End | LaneExit::Indirect => Vec::new(), } }; @@ -872,7 +952,10 @@ fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option let r = find(&mut region, b); for i in &block.insts { let name = i.name(); - if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") { + if !matches!(i.fields, Fields::Ds { .. }) + || name.starts_with("ds_swizzle") + || name.contains("permute") + { continue; } if name.starts_with("ds_read") { @@ -907,7 +990,14 @@ fn lane_constant_masks(st: &Structured) -> bool { LaneExit::Branch { when, .. } => Some(when), _ => None, }); - let mut work: Vec = st.guards.iter().flatten().flatten().copied().chain(whens).collect(); + let mut work: Vec = st + .guards + .iter() + .flatten() + .flatten() + .copied() + .chain(whens) + .collect(); // Through lane-mask joins too: an edge that brings a number or a constant lane set needs // the lane's own bit of it. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such @@ -1245,6 +1335,30 @@ fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } +/// Where a program's constant table starts: after its instructions, unless +/// a fixed-offset load reads below it. +fn code_table_start( + p: &crate::ir::Program, + addresses: &[&crate::resource::Address], + lowest: u32, +) -> u32 { + let code_end = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .map(|i| i.machine.offset + 4 * i.machine.words.len()) + .max() + .unwrap_or(0) as u32; + let fixed_below = addresses + .iter() + .any(|a| a.dynamic.is_none() && a.offset < code_end); + if fixed_below { + lowest + } else { + lowest.max(code_end & !3) + } +} + impl<'a> Lower<'a> { fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { let p = x.p; @@ -1300,7 +1414,10 @@ impl<'a> Lower<'a> { // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant // masks), nor when LDS may be shared within the console wave without barriers (a // group over 32 threads with LDS): those still need 64-lane waves. - if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) { + if wave == 64 + && host_max_wave() == 32 + && (console_lanes || one_wave && s.lds_dwords > 0) + { let crosses = insts().any(|i| { let n = i.name(); n.starts_with("v_mbcnt") @@ -1325,9 +1442,9 @@ impl<'a> Lower<'a> { }; if let Some(all) = all_lane_blocks(x.st) { let ok = p.blocks.iter().enumerate().all(|(b, blk)| { - blk.insts.iter().all(|inst| { - !lds(inst) || all.get(b).copied().unwrap_or(false) - }) + blk.insts + .iter() + .all(|inst| !lds(inst) || all.get(b).copied().unwrap_or(false)) }); let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) { @@ -1338,7 +1455,9 @@ impl<'a> Lower<'a> { // (the blocks whose LDS accesses not every lane runs: with the // branches around them taken wave-wide they get their barriers) for (b, blk) in p.blocks.iter().enumerate() { - if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) { + if !all.get(b).copied().unwrap_or(false) + && blk.insts.iter().any(lds) + { need(b); } } @@ -1391,7 +1510,11 @@ impl<'a> Lower<'a> { } } why.sort_unstable(); - eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); + eprintln!( + "WAVE64-WHY group={group} lds={} [{}]", + s.lds_dwords > 0, + why.join(", ") + ); } } if wave == 32 && x.native.wave64 { @@ -1418,12 +1541,11 @@ impl<'a> Lower<'a> { let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX); at(from) != usize::MAX && at(to) <= at(from) }; - let cut_short = x - .st - .exits - .iter() - .enumerate() - .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); + let cut_short = + x.st.exits + .iter() + .enumerate() + .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); let all = all_lane_blocks(x.st); (0..p.blocks.len()) .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) @@ -1438,15 +1560,38 @@ impl<'a> Lower<'a> { HashSet::new() }; let mut no_barrier = HashSet::new(); + let mut mesh_emu = None; if let StageIo::Ms(ms) = &x.native.io { - s.prims = x.prims.clone(); s.threads = Some([ms.threads, 1, 1]); s.lds_dwords = ms.lds_bytes.div_ceil(4); - s.mesh = Some(super::shader::Mesh { - max_vertices: ms.max_vertices, - max_primitives: ms.max_primitives, - topology: ms.topology, - }); + if x.emulate_mesh { + s.inputs.clear(); + s.outputs.clear(); + s.prims.clear(); + let (vertex_offsets, vertex_dwords) = pack_offsets(&x.outputs); + let (prim_offsets, prim_dwords) = pack_offsets(&x.prims); + mesh_emu = Some(MeshEmuState { + threads: ms.threads, + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + vertex_sigs: x.outputs.clone(), + vertex_offsets, + vertex_dwords, + prim_sigs: x.prims.clone(), + prim_offsets, + prim_dwords, + reads_group_id: false, + vals: None, + }); + } else { + s.prims = x.prims.clone(); + s.mesh = Some(super::shader::Mesh { + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + }); + } // Barriers order the lanes' LDS accesses; the console's // allocation request needs them too, but the host does not. One // lane sends that request, and what it dominates (the path for @@ -1512,7 +1657,8 @@ impl<'a> Lower<'a> { scalar: x.res.scalar.iter().copied().collect(), exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), interps: { - let mut m: HashMap = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); + let mut m: HashMap = + x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); // A first half whose result is also read as data (an f16 second half keeps // the other half of its dst, PS_DeferredTextured): evaluated as the pair it // starts. Approximate for those other bits (P0 + i P10 on the console); a @@ -1589,6 +1735,7 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, + mesh_emu, } } @@ -1600,22 +1747,26 @@ impl<'a> Lower<'a> { let (g, base, len) = match self.code_table { Some(t) => t, None => { - let first = self + let addresses: Vec<&crate::resource::Address> = self .x .res .scalar .iter() - .map(|s| s.1) + .map(|s| &s.1) .chain(self.x.res.descriptors.iter().flat_map(|d| { d.source.leaves().into_iter().filter_map(|l| match l { - Source::Built { address, .. } => Some(*address), + Source::Built { address, .. } => Some(address), _ => None, }) })) .filter(|a| a.param == CODE) + .collect(); + let lowest = addresses + .iter() .map(|a| a.offset & !3) .min() .ok_or("a code table")?; + let first = code_table_start(self.x.p, &addresses, lowest); let code = &self.x.native.code; let words: Vec = code .get(first as usize..) @@ -1944,7 +2095,14 @@ impl<'a> Lower<'a> { Some(_) => { // the upper half adds the lower half's total to its prefix let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float))); - let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]); + let total = self.s.op( + c, + &format!("waveActiveOp.{sfx}"), + Attr::NoUnwind, + ty, + 119, + &[arg, k0, ku], + ); let tb = bits(self, total); let c = self.cur; let (lo, _) = self.exchange_halves(c, tb); @@ -1952,7 +2110,11 @@ impl<'a> Lower<'a> { let cl = self.console_lane(); let k32 = self.s.m.i32(32); let upper = self.s.m.cmp(c, pred::IUGE, cl, k32); - let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) }; + let zero = if float { + self.s.m.f32(0) + } else { + self.s.m.i32(0) + }; let add = self.s.m.select(c, upper, lo, zero); self.s.m.bin(c, Bin::Add, r, add) } @@ -1976,7 +2138,14 @@ impl<'a> Lower<'a> { Op::MinI => 38, _ => 37, }; - self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + self.s.op( + c, + &format!("binary.{sfx}"), + Attr::ReadNone, + ty, + code, + &[lo, hi], + ) } } } @@ -1989,13 +2158,7 @@ impl<'a> Lower<'a> { /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), /// returning the low (`!high`) or high (`high`) 32-bit word. - fn active_f64_sum( - &mut self, - lo: Value, - hi: Value, - mask: Value, - high: bool, - ) -> Result { + fn active_f64_sum(&mut self, lo: Value, hi: Value, mask: Value, high: bool) -> Result { if self.mask_data == MaskData::None { return Err("a wave reduction in a mesh shader"); } @@ -2023,9 +2186,14 @@ impl<'a> Lower<'a> { .s .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); - let sum = self - .s - .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); + let sum = self.s.op( + c, + "waveActiveOp.f64", + Attr::NoUnwind, + f64t, + 119, + &[arg, k0, k0b], + ); let split = self .s .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); @@ -2046,9 +2214,14 @@ impl<'a> Lower<'a> { .s .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); let total = self.s.m.bin(c, Bin::Add, d0, d1); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); + let split = self.s.op( + c, + "splitDouble.f64", + Attr::ReadNone, + split_ty, + 102, + &[total], + ); r_lo = self.s.m.extract(c, split, 0); r_hi = self.s.m.extract(c, split, 1); } @@ -2075,7 +2248,7 @@ impl<'a> Lower<'a> { /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves; - /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the + /// `super::wave::buddies`). Each lane adds its partner's partial sum, read from the /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange /// their halves' sums for the last addition. The high half of the result is lane 0's, /// which no `v_add_f16` writes. @@ -2084,7 +2257,10 @@ impl<'a> Lower<'a> { /// own (half a sum is no sum). fn half_sum(&mut self, x: V) -> Result { const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; - let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; + let threads = self + .s + .threads + .ok_or("a wave sum of 16-bit floats outside compute")?; if threads.iter().product::() % 64 != 0 { return Err("a wave sum of 16-bit floats in a wave that is not full"); } @@ -2100,7 +2276,8 @@ impl<'a> Lower<'a> { let every = if halves { self.all_lanes(self.cur_ir) } else { - all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) + all_lane_blocks(self.x.st) + .is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) }; if !every { if halves { @@ -2111,7 +2288,9 @@ impl<'a> Lower<'a> { } let c = self.cur; let i32t = self.s.t.i32; - let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self + .s + .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let mut sum = x; for step in 0..if halves { 5 } else { 6 } { let bit = self.s.m.i32(1 << step); @@ -2119,7 +2298,11 @@ impl<'a> Lower<'a> { let theirs = self.read_lane(sum, partner); sum = self.add_halves(sum, theirs); } - let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + let (high, low, zero) = ( + self.s.m.i32(0xFFFF_0000), + self.s.m.i32(0xFFFF), + self.s.m.i32(0), + ); let first = self.read_lane(x, zero); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); @@ -2203,6 +2386,20 @@ impl<'a> Lower<'a> { self.s.m.new_block() }); } + self.cur = self.s.entry; + self.find_sections(); + if self.mesh_emu.is_some() { + self.mesh_emu_init().map_err(|w| unsupported(0, w))?; + } + self.inputs()?; + if let Some(mesh) = self.s.mesh { + self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; + } else if self.mesh_emu.is_some() { + self.mesh_emu_prologue(); + } + if self.cur != self.s.entry { + self.block[order[0]] = Some(self.cur); + } // Loop headers count iterations (`LOOP_LIMIT`). for &b in &order { let header = p.blocks[b] @@ -2215,13 +2412,6 @@ impl<'a> Lower<'a> { self.counters.insert(b, (phi, Vec::new())); } } - self.cur = self.s.entry; - self.find_sections(); - self.inputs()?; - if let Some(mesh) = self.s.mesh { - self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; - self.block[order[0]] = Some(self.cur); - } for &b in &order { self.cur = self.block[b].expect("reachable"); self.cur_ir = b; @@ -2279,12 +2469,41 @@ impl<'a> Lower<'a> { let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); let cmp_samplers = self.s.cmp_samplers; let wave_size = self.s.wave_size; + let mesh_emu = self.mesh_emu.take().map(|m| { + let to_outputs = |sigs: Vec, offsets: Vec| { + sigs.into_iter() + .zip(offsets) + .map(|(s, dword_offset)| super::MeshOutput { + name: s.name, + index: s.index, + kind: s.kind, + comp: s.comp, + interp: s.interp, + row: s.row, + col: s.col, + cols: s.cols, + dword_offset, + }) + .collect() + }; + super::MeshEmu { + threads: m.threads, + max_vertices: m.max_vertices, + max_primitives: m.max_primitives, + vertex_dwords: m.vertex_dwords, + prim_dwords: m.prim_dwords, + reads_group_id: m.reads_group_id, + vertex_outputs: to_outputs(m.vertex_sigs, m.vertex_offsets), + prim_outputs: to_outputs(m.prim_sigs, m.prim_offsets), + } + }); Ok(Lowered { wave_size, cmp_samplers, root_cbvs, root_srvs, root_uavs, + mesh_emu, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] @@ -2364,6 +2583,57 @@ impl<'a> Lower<'a> { Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), Input::MeshGroup => { + if let Some(m) = self.mesh_emu.as_mut() { + m.reads_group_id = true; + let local_group = m.vals.as_ref().expect("mesh emu init").local_group; + let cbv = self.s.emu_cbv_handle(); + let srv = self.s.emu_srv_handle(); + let c = self.cur; + let i32t = self.s.t.i32; + let k0 = self.s.m.i32(0); + let base_ret = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[cbv, k0], + ); + let base = self.s.m.extract(c, base_ret, 0); + let flag = self.s.m.i32(super::INDIRECT_SLOT_MAP_FLAG); + let is_map = self.s.m.cmp(c, pred::EQ, base, flag); + let map_bb = self.s.m.new_block(); + let add_bb = self.s.m.new_block(); + let join_bb = self.s.m.new_block(); + self.s.m.terminate(c, Term::CondBr(is_map, map_bb, add_bb)); + + let k2 = self.s.m.i32(2); + let off = self.s.m.bin(map_bb, Bin::Shl, local_group, k2); + let undef = self.s.m.undef(i32t); + let mask1 = self.s.m.i8(1); + let align4 = self.s.m.i32(4); + let r = self.s.op( + map_bb, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[srv, off, undef, mask1, align4], + ); + let f = self.s.m.extract(map_bb, r, 0); + let g_map = self.s.m.cast(map_bb, Cast::Bitcast, f, i32t); + self.s.m.terminate(map_bb, Term::Br(join_bb)); + + let g_add = self.s.m.bin(add_bb, Bin::Add, local_group, base); + self.s.m.terminate(add_bb, Term::Br(join_bb)); + + let g = self.s.m.phi(join_bb, i32t); + self.s.m.set_phi(g, vec![(g_map, map_bb), (g_add, add_bb)]); + let n = self.s.m.i32(self.x.mesh_stride); + let res = self.s.m.bin(join_bb, Bin::Mul, g, n); + self.cur = join_bb; + return Val::I32(res); + } let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { unreachable!() }; @@ -2785,7 +3055,10 @@ impl<'a> Lower<'a> { .m .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo); let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); - let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); + let hi = self + .s + .m + .bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); (sum, hi) } @@ -2795,7 +3068,9 @@ impl<'a> Lower<'a> { /// (and drops writes) through the null view at the first slot, and its /// number is left for the host, for lanes that run (`guard`). fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { - use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; + use super::shader::{ + MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE, + }; let c = self.cur; let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); let k = |l: &mut Self, v: u32| l.s.m.i32(v); @@ -2933,8 +3208,14 @@ impl<'a> Lower<'a> { args.push(self.s.m.i8((1u8 << n) - 1)); args.push(align); let at = self.begin_guarded(guard); - self.s - .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.s.op( + self.cur, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &args, + ); self.end_guarded(at, &[]); return Ok(()); } @@ -3013,9 +3294,9 @@ impl<'a> Lower<'a> { let fseen = self.as_float(seen); // `dx.op.binary`: FMax 35, FMin 36. let pick = if op == "fmin" { 36 } else { 35 }; - let wanted = self - .s - .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); + let wanted = + self.s + .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); let wanted = self.as_int(wanted); let found = self.s.op( pass, @@ -3068,7 +3349,9 @@ impl<'a> Lower<'a> { _ => return Err("a scalar memory access by address"), }; let word = |l: &mut Self, k: u8| -> Result { - let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?; + let v = inst + .read(Reg::S(base + k)) + .ok_or("an address not in SGPRs")?; l.i32_of(v) }; let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?); @@ -3118,7 +3401,8 @@ impl<'a> Lower<'a> { // say) is the ballot of the lanes that are there: all of them, where two exchanging // host waves know every lane runs that block. let made = self.def_block.get(&lo).copied(); - let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + let whole = + self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); if !self.x.st.active.contains(&lo) && !whole { if self.exchange.is_some() && !self.local { need(made.unwrap_or(0)); @@ -3154,7 +3438,9 @@ impl<'a> Lower<'a> { if !self.local_ok && !self.local_any { return Err("a lane mask read as data in a half-wave"); } - } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { + } else if !self.exchange.as_ref().is_some_and(|e| e.1) + && !b.is_none_or(|b| self.all_lanes(b)) + { // (a group of 32 or fewer has no other half to exchange with) need(b.unwrap_or(0)); return Err("a lane mask exchanged where not every lane runs"); @@ -3658,13 +3944,22 @@ impl<'a> Lower<'a> { let zero = self.s.m.i32(0); self.s.m.store(e, ptr, zero); self.group_sync(e); - let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self + .s + .op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let first = self.s.m.cmp(e, pred::EQ, lane, zero); let k32 = self.s.m.i32(32); let add = self.s.m.select(e, first, k32, zero); let ptr = self.s.m.element(e, lds, k); let old = self.s.m.atomic(e, Rmw::Add, ptr, add); - let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); + let base = self.s.op( + e, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + i32t, + 118, + &[old], + ); self.s.flags |= flags::WAVE_OPS; self.wave_base = Some(base); Some(base) @@ -3674,12 +3969,28 @@ impl<'a> Lower<'a> { /// (host waves of 32), else the wave's first thread index rounded down plus the lane. fn console_thread(&mut self) -> V { let (e, i32t) = (self.s.entry, self.s.t.i32); - let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self + .s + .op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); if let Some(base) = self.wave_base() { return self.s.m.bin(e, Bin::Add, base, lane); } - let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); - let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]); + let flat = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + i32t, + 96, + &[], + ); + let first = self.s.op( + e, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + i32t, + 118, + &[flat], + ); let wave = self.s.wave_size.unwrap_or(32); let mask = self.s.m.i32(!(wave - 1)); let base = self.s.m.bin(e, Bin::And, first, mask); @@ -3709,7 +4020,8 @@ impl<'a> Lower<'a> { fn group_sync(&mut self, block: usize) { let mode = self.s.m.i32(meeting_mode()); let void = self.s.t.void; - self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.s + .op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get @@ -3796,7 +4108,9 @@ impl<'a> Lower<'a> { }; let bit = self.boolean(m, at)?; let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); - let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); + let some = self + .s + .op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); self.s.flags |= flags::WAVE_OPS; if !self.exchange.as_ref().is_some_and(|e| !e.1) { return Ok(some); @@ -3814,8 +4128,19 @@ impl<'a> Lower<'a> { fn wave_wide(&mut self, b: usize, when: Bool) -> Result { const WHY: Why = "a wave-wide branch where not every lane runs"; - let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; - if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { + let any = self + .x + .st + .wave_any + .get(b) + .copied() + .flatten() + .ok_or("a wave-wide branch on a scalar condition")?; + if self.exchange.is_none() + && self.halves.is_none() + && self.console_lanes + && self.mask_data == MaskData::Console + { // The host's waves are the console's: the wave's own answer. The lanes that are // elsewhere have no bit set, as on the console, so "some lane" needs no one but // the lanes here, and "every lane's bit is clear" is true of the others anyway. @@ -3823,7 +4148,11 @@ impl<'a> Lower<'a> { let mine = self.boolean(when, c)?; let i1t = self.s.t.i1; self.s.flags |= flags::WAVE_OPS; - let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + let (name, code) = if any { + ("waveAnyTrue", 113) + } else { + ("waveAllTrue", 114) + }; return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine])); } if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) { @@ -3845,19 +4174,26 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Xor, mine, t) }; let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); - let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); + let some = self + .s + .op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); self.s.flags |= flags::WAVE_OPS; let some = self.s.m.cast(c, Cast::ZExt, some, i32t); let (lo, hi) = self.exchange_halves(c, some); let c = self.cur; let both = self.s.m.bin(c, Bin::Or, lo, hi); let z = self.s.m.i32(0); - Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) + Ok(self + .s + .m + .cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) } /// Whether every lane runs IR block `b` (always true without `exchange`). fn all_lanes(&self, b: usize) -> bool { - self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) + self.exchange + .as_ref() + .is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) } /// This lane's bit of the mask `lo`, `hi` (wave64). @@ -3866,7 +4202,14 @@ impl<'a> Lower<'a> { let lane = if self.exchange.is_some() { self.console_lane() } else { - self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) + self.s.op( + at, + "waveGetLaneIndex", + Attr::ReadOnly, + self.s.t.i32, + 111, + &[], + ) }; let (k31, k32, one, z) = ( self.s.m.i32(31), @@ -4075,11 +4418,15 @@ impl<'a> Lower<'a> { .collect() } + fn is_mesh(&self) -> bool { + self.s.mesh.is_some() || self.mesh_emu.is_some() + } + /// Code that depends on the lane layout: wave operations, and in compute /// the console's wave size (lanes are thread ids in group order there). /// Pixel lanes match only within a quad. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> { - if self.s.mesh.is_some() { + if self.is_mesh() { // shortcut: no wave size for mesh shaders in SM 6.6, so host // lanes cannot follow the console's; emulate through group-shared // memory if mesh programs turn out to need these. @@ -4227,6 +4574,14 @@ impl<'a> Lower<'a> { Ok(()) } + fn combine_guards(&mut self, a: Option, b: Option) -> Option { + match (a, b) { + (Some(x), Some(y)) => Some(self.s.m.bin(self.cur, Bin::And, x, y)), + (Some(x), None) | (None, Some(x)) => Some(x), + (None, None) => None, + } + } + /// Mesh: the thread's index in the group, which is its vertex and /// primitive index. fn mesh_thread(&mut self) -> V { @@ -4252,7 +4607,7 @@ impl<'a> Lower<'a> { } fn lane_index(&mut self) -> V { - if self.s.mesh.is_some() { + if self.is_mesh() { // The console's lane: mesh code reads no other lanes, so host // waves need not match the console's. let f = self.mesh_thread(); @@ -4300,24 +4655,34 @@ impl<'a> Lower<'a> { let c = self.cur; let i32t = self.s.t.i32; self.s.flags |= flags::WAVE_OPS; - let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); + let first = self + .s + .op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); let Some(g) = guard else { return (first, self.s.m.bool(true)); }; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); - let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); + let r = self + .s + .op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)); let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); // FirstbitLo (dx.op 32): the lowest set bit - let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); - let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); + let flo = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); + let fhi = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); let fhi = self.s.m.bin(c, Bin::Add, fhi, k32); let in_lo = self.s.m.cmp(c, pred::NE, lo, z); let in_hi = self.s.m.cmp(c, pred::NE, hi, z); let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi); let lane = self.s.m.select(c, in_lo, flo, fhi); // no lane in EXEC: read this lane (one that is here); the read is not used - let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let me = self + .s + .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let lane = self.s.m.select(c, any, lane, me); let at = self.read_lane(x, lane); (self.s.m.select(c, any, at, first), any) @@ -4387,7 +4752,7 @@ impl<'a> Lower<'a> { || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the // console's, so quad-local swizzles read through quad operations. - let mesh_quad = self.s.mesh.is_some() && quad; + let mesh_quad = self.is_mesh() && quad; if !mesh_quad { self.cross_lane(quad)?; } @@ -4792,7 +5157,8 @@ impl<'a> Lower<'a> { // half wrote is visible, and what it still reads is not overwritten let mode = self.s.m.i32(meeting_mode()); let void = self.s.t.void; - self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } let r = match &inst.fields { Fields::Sop { .. } => self.sop(inst), @@ -4828,9 +5194,7 @@ impl<'a> Lower<'a> { // program where its results are needed, and two trace programs // came out without their test that way. Fields::Image { .. } if name.starts_with("image_bvh") => { - return self - .bvh(inst, b, i) - .map_err(|why| unsupported(offset, why)); + return self.bvh(inst, b, i).map_err(|why| unsupported(offset, why)); } Fields::Image { .. } => self.image(inst, b, i), Fields::Buffer { .. } => self.buffer(inst, b, i), @@ -4856,7 +5220,8 @@ impl<'a> Lower<'a> { fn lds_meeting(&mut self) { let mode = self.s.m.i32(meeting_mode()); let void = self.s.t.void; - self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); } /// Whether `v` is a register no program reads as a number: a descriptor dword without @@ -4931,7 +5296,10 @@ impl<'a> Lower<'a> { let Fields::Valu(f) = &cmp.fields else { return false; }; - if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() { + if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") + || f.sdwa.is_some() + || f.dpp.is_some() + { return false; } let lanes = f.src.iter().find_map(|o| match *o { @@ -5250,14 +5618,28 @@ impl<'a> Lower<'a> { let carry = if name == "s_add_u32" { Some(self.s.m.cmp(c, pred::IULT, r, a)) } else { - None + // Signed overflow: a and b share a sign bit that r flips. + let ar = self.s.m.bin(c, Bin::Xor, a, r); + let br = self.s.m.bin(c, Bin::Xor, b, r); + let ov = self.s.m.bin(c, Bin::And, ar, br); + let z = self.s.m.i32(0); + Some(self.s.m.cmp(c, pred::SLT, ov, z)) }; (r, carry) } "s_sub_u32" | "s_sub_i32" => { let (a, b) = (src32(self, 0)?, src32(self, 1)?); let r = self.s.m.bin(c, Bin::Sub, a, b); - let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); + let carry = Some(if name == "s_sub_u32" { + self.s.m.cmp(c, pred::IULT, a, b) + } else { + // Signed overflow: a and b have opposite signs and r flips a's sign. + let ab = self.s.m.bin(c, Bin::Xor, a, b); + let ar = self.s.m.bin(c, Bin::Xor, a, r); + let ov = self.s.m.bin(c, Bin::And, ab, ar); + let z = self.s.m.i32(0); + self.s.m.cmp(c, pred::SLT, ov, z) + }); (r, carry) } "s_addc_u32" | "s_subb_u32" => { @@ -5673,10 +6055,13 @@ impl<'a> Lower<'a> { }) }) }; - let by_scalar_load = |u: &(Site, u8)| { - matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) + let by_scalar_load = + |u: &(Site, u8)| matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }); + let use_of = |of: Site| { + uses(of) + .find(|u| !by_scalar_load(u)) + .or_else(|| uses(of).next()) }; - let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); // The console compiler loads a descriptor again wherever it needs it, and for a // size it reads the dwords of a load that nothing uses as a descriptor (a texture // picked from the heap by an index held per lane: one load for its width, one for @@ -5726,9 +6111,10 @@ impl<'a> Lower<'a> { // descriptor's address or format is. let sampler = x.res.descriptors.iter().any(|d| { d.role == Role::Sampler - && d.source.leaves().into_iter().any( - |l| matches!(*l, Source::Loaded { load, .. } if load == site), - ) + && d.source + .leaves() + .into_iter() + .any(|l| matches!(*l, Source::Loaded { load, .. } if load == site)) }); if sampler { self.stale.extend(inst.writes.iter().map(|w| w.1)); @@ -5997,13 +6383,19 @@ impl<'a> Lower<'a> { // A term held per lane reached the address through // `v_readfirstlane_b32`: the first lane's. let per_lane = self.def_block.get(&value).is_some_and(|&b| { - let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_))); + let writes = |i: &Inst| { + i.writes + .iter() + .any(|w| w.1 == value && matches!(w.0, Reg::V(_))) + }; self.x.p.blocks[b].insts.iter().any(writes) }); if per_lane { self.s.flags |= flags::WAVE_OPS; let i32t = self.s.t.i32; - d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + d = self + .s + .op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); } addr = self.s.m.bin(c, Bin::Add, addr, d); } @@ -6390,9 +6782,10 @@ impl<'a> Lower<'a> { self.cur = here; index? } - Source::Phi { block: inner, args: inner_args } if depth > 0 => { - self.descriptor_phi(*inner, inner_args, sampler, depth - 1)? - } + Source::Phi { + block: inner, + args: inner_args, + } if depth > 0 => self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?, _ => return Err(WHY), }; incoming.push((index, at)); @@ -6429,7 +6822,9 @@ impl<'a> Lower<'a> { // compute one too): a root view has no bounds of its own. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); let i32t = self.s.t.i32; - let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + let slot = self + .s + .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); self.s.m.tag(slot, Tag::Clamp); let two = self.s.m.i32(2); let byte = self.s.m.bin(c, Bin::Shl, slot, two); @@ -6646,7 +7041,7 @@ impl<'a> Lower<'a> { let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?; // Quad permutations and DPP8 stay in groups the pixel layout shares. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. }); - let mesh_quad = self.s.mesh.is_some() && quad; + let mesh_quad = self.is_mesh() && quad; if !mesh_quad { self.cross_lane(quad)?; } @@ -7247,7 +7642,9 @@ impl<'a> Lower<'a> { let x = s(self, 0)?; let (s1, s2) = (s(self, 1)?, s(self, 2)?); let i32t = self.s.t.i32; - let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self + .s + .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let [k15, k8, k7, k2, k16, not31, not15] = [15, 8, 7, 2, 16, !31, !15].map(|x| self.s.m.i32(x)); let low = self.s.m.bin(c, Bin::And, lane, k15); @@ -7576,9 +7973,9 @@ impl<'a> Lower<'a> { // two host waves that exchange: the console's first lane may be in the other // one, unless every lane holds the same value let alike = match v.src.first() { - Some(&Operand::Vector { reg, .. }) => { - inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x)) - } + Some(&Operand::Vector { reg, .. }) => inst + .read(Reg::V(reg)) + .is_some_and(|x| self.uniform.contains(&x)), _ => true, }; let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; @@ -7589,7 +7986,9 @@ impl<'a> Lower<'a> { // the console wave (the ray-tracing builder's scans read a sum of // scalars this way, inside a loop whose exit is per console wave). static OWN: std::sync::OnceLock = std::sync::OnceLock::new(); - if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) { + if *OWN.get_or_init(|| { + std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1") + }) { return int(self, mine); } need(self.cur_ir); @@ -8834,7 +9233,7 @@ impl<'a> Lower<'a> { return Err("v_mbcnt of a mask that is no ballot (console lane layout)"); } self.s.flags |= flags::WAVE_OPS; - } else if self.s.mesh.is_none() { + } else if !self.is_mesh() { self.cross_lane(false)?; } let lane = self.console_lane(); @@ -9613,7 +10012,8 @@ impl<'a> Lower<'a> { // Implicit derivatives: pixel shaders only. "image_sample_c" if self.s.pixel => (64, true), "image_sample_c_cl" if self.s.pixel => (64, true), - "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true), + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" + | "image_gather4_l_o" => (73, true), "image_load" | "image_load_mip" => (66, false), "image_get_resinfo" => (72, false), _ => return Err(name), @@ -9685,11 +10085,7 @@ impl<'a> Lower<'a> { // A cube's gradients are the two of its face coordinates. let grads = if kind == 5 { 2 } else { spatial }; let deriv_regs = if op == 63 { - if *a16 { - grads.div_ceil(2) - } else { - grads - } + if *a16 { grads.div_ceil(2) } else { grads } } else { 0 }; @@ -10021,7 +10417,12 @@ impl<'a> Lower<'a> { let ch = dmask.trailing_zeros(); let mut g = [fu; 4]; let mut read = None; - let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])]; + let texels = [ + (lo[0], hi[1]), + (hi[0], hi[1]), + (hi[0], lo[1]), + (lo[0], lo[1]), + ]; for (slot, (x, y)) in g.iter_mut().zip(texels) { let r = self.s.op( c, @@ -10655,7 +11056,7 @@ impl<'a> Lower<'a> { return Err("a compressed export"); } let guard = self.guard(b, i)?; - let mesh = self.s.mesh.is_some(); + let mesh = self.is_mesh(); let c = self.cur; if let Some(g) = guard && !mesh @@ -10669,6 +11070,9 @@ impl<'a> Lower<'a> { .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); } if mesh && e.target == Target::Primitive { + if self.mesh_emu.is_some() { + return self.emit_indices_emu(e, guard); + } return self.emit_indices(e, guard); } let param_row = |usage: Usage, row: u8| match usage { @@ -10681,10 +11085,11 @@ impl<'a> Lower<'a> { // outputs are elements of `prims`. let mut stores = Vec::new(); let primitive = matches!(e.target, Target::PrimitiveParam { .. }); - let outputs = if primitive { - &self.s.prims - } else { - &self.s.outputs + let outputs = match (&self.mesh_emu, primitive) { + (Some(m), true) => &m.prim_sigs, + (Some(m), false) => &m.vertex_sigs, + (None, true) => &self.s.prims, + (None, false) => &self.s.outputs, }; let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind); // 16-bit vertex outputs: the halves each dword carries, as (output @@ -10787,7 +11192,13 @@ impl<'a> Lower<'a> { } } fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec { - if primitive { + if let Some(m) = l.mesh_emu.as_mut() { + if primitive { + &mut m.prim_sigs + } else { + &mut m.vertex_sigs + } + } else if primitive { &mut l.s.prims } else { &mut l.s.outputs @@ -10799,6 +11210,9 @@ impl<'a> Lower<'a> { { return Err("a 16-bit output the stage data does not mark"); } + if self.mesh_emu.is_some() { + return self.store_mesh_emu_outputs(guard, primitive, &stores); + } // A mesh lane writes its own vertex or primitive, where it exports. let at = if mesh { let flat = self.mesh_thread(); @@ -10937,6 +11351,174 @@ impl<'a> Lower<'a> { Ok(()) } + /// Emulated mesh: `exp prim` writes the packed primitive index word + /// (preserving bit 31 as the cull flag) to `u0, space 2`. + fn emit_indices_emu(&mut self, e: &Export, guard: Option) -> Result<(), Why> { + let v = e.values[0].ok_or("a primitive export without its indices")?; + let x = self.i32_of(v)?; + let (uav, group_base, flat_lt_prims) = { + let v = self + .mesh_emu + .as_ref() + .expect("mesh emu") + .vals + .as_ref() + .expect("mesh emu init"); + (v.uav, v.group_base, v.flat_lt_prims) + }; + let guard = self.combine_guards(guard, flat_lt_prims); + let flat = self.mesh_thread(); + let at = self.begin_guarded(guard); + let c = self.cur; + let k2 = self.s.m.i32(2); + let byte_off = self.s.m.bin(c, Bin::Shl, flat, k2); + let addr = self.s.m.bin(c, Bin::Add, group_base, byte_off); + let undef = self.s.m.undef(self.s.t.i32); + let mask1 = self.s.m.i8(1); + let align4 = self.s.m.i32(4); + let void = self.s.t.void; + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[uav, addr, undef, x, undef, undef, undef, mask1, align4], + ); + self.end_guarded(at, &[]); + Ok(()) + } + + /// Emulated mesh: stores vertex (`primitive == false`) or per-primitive + /// (`primitive == true`) exported scalars into `u0, space 2`, coalescing + /// contiguous dword slots up to 4 dwords per store. + fn store_mesh_emu_outputs( + &mut self, + guard: Option, + primitive: bool, + stores: &[(usize, u8, Value, Option)], + ) -> Result<(), Why> { + if stores.is_empty() { + return Ok(()); + } + let mut items: Vec<(u32, V, Option)> = Vec::with_capacity(stores.len()); + for &(id, col, value, half) in stores { + let x = self.i32_of(value)?; + let slot = { + let m = self.mesh_emu.as_mut().expect("mesh emu"); + let (sigs, offsets) = if primitive { + (&mut m.prim_sigs, &m.prim_offsets) + } else { + (&mut m.vertex_sigs, &m.vertex_offsets) + }; + sigs[id].usage |= 1 << col; + offsets[id] + u32::from(col) + }; + items.push((slot, x, half)); + } + items.sort_by_key(|&(slot, _, _)| slot); + let mut deduped: Vec<(u32, V, Option)> = Vec::with_capacity(items.len()); + for item in items { + if let Some(last) = deduped.last_mut() + && last.0 == item.0 + { + *last = item; + } else { + deduped.push(item); + } + } + let (uav, group_base, bound_guard, base_offset, stride_bytes) = { + let v = self + .mesh_emu + .as_ref() + .expect("mesh emu") + .vals + .as_ref() + .expect("mesh emu init"); + if primitive { + ( + v.uav, + v.group_base, + v.flat_lt_prims, + v.prim_offset_bytes, + v.prim_stride_bytes, + ) + } else { + ( + v.uav, + v.group_base, + v.flat_lt_verts, + v.index_bytes, + v.vertex_stride_bytes, + ) + } + }; + let guard = self.combine_guards(guard, bound_guard); + let flat = self.mesh_thread(); + let at = self.begin_guarded(guard); + let c = self.cur; + let mut converted = Vec::with_capacity(deduped.len()); + for (slot, mut x, half) in deduped { + if let Some(high) = half { + if high { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + x = self.as_int(f); + } + converted.push((slot, x)); + } + let stride = self.s.m.i32(stride_bytes); + let rel = self.s.m.bin(c, Bin::Mul, flat, stride); + let off = if base_offset == 0 { + rel + } else { + let base_k = self.s.m.i32(base_offset); + self.s.m.bin(c, Bin::Add, base_k, rel) + }; + let rec_base = self.s.m.bin(c, Bin::Add, group_base, off); + let undef = self.s.m.undef(self.s.t.i32); + let align4 = self.s.m.i32(4); + let void = self.s.t.void; + let mut idx = 0; + while idx < converted.len() { + let start_slot = converted[idx].0; + let mut len = 1usize; + while len < 4 + && idx + len < converted.len() + && converted[idx + len].0 == start_slot + len as u32 + { + len += 1; + } + let addr = if start_slot == 0 { + rec_base + } else { + let disp = self.s.m.i32(start_slot * 4); + self.s.m.bin(c, Bin::Add, rec_base, disp) + }; + let v0 = converted[idx].1; + let v1 = if len > 1 { converted[idx + 1].1 } else { undef }; + let v2 = if len > 2 { converted[idx + 2].1 } else { undef }; + let v3 = if len > 3 { converted[idx + 3].1 } else { undef }; + let mask = self.s.m.i8((1u8 << len) - 1); + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[uav, addr, undef, v0, v1, v2, v3, mask, align4], + ); + idx += len; + } + self.end_guarded(at, &[]); + Ok(()) + } + /// The per-vertex arbitrary row no mesh output entry names but one /// (the 2020 compiler's zeroed entry). fn unnamed_row(&self) -> Option { @@ -10948,9 +11530,11 @@ impl<'a> Lower<'a> { .iter() .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) }; - let free: std::collections::BTreeSet = self - .s - .outputs + let vertex_sigs = match &self.mesh_emu { + Some(m) => &m.vertex_sigs, + None => &self.s.outputs, + }; + let free: std::collections::BTreeSet = vertex_sigs .iter() .filter(|o| o.kind == 0) .filter_map(|o| o.row) @@ -10985,7 +11569,9 @@ impl<'a> Lower<'a> { // A negated condition branches the other way round. let (cond, taken, not_taken) = match self.x.st.bools.node(when) { _ if self.x.st.wide.contains(&b) => { - let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; + let c = self + .wave_wide(b, when) + .map_err(|w| unsupported(offset, w))?; (c, taken, not_taken) } Some((atom, Bool::TRUE, Bool::FALSE)) => { @@ -11145,7 +11731,9 @@ impl<'a> Lower<'a> { for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); - let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?; + let x = self + .boolean(args[n], qb) + .map_err(|w| unsupported(offset, w))?; incoming.push((x, qb)); } self.s.m.set_phi(v, incoming); @@ -11289,6 +11877,8 @@ fn interp_mode(kind: Barycentric) -> Option { }) } +include!("lower/mesh_emulation.rs"); + #[cfg(test)] mod tests { use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; @@ -11450,6 +12040,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + emulate_mesh: false, }) .map(|_| ()) } @@ -11500,6 +12091,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + emulate_mesh: false, }) } @@ -11519,8 +12111,14 @@ mod tests { fn buffer_cache_invalidations_lower_as_no_ops() { // MUBUF opcode 0x071/0x072 with no data operand: the title asks the // host to invalidate its cached view of a buffer. - assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); - assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); + assert!( + lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), + "buffer_gl0_inv" + ); + assert!( + lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), + "buffer_gl1_inv" + ); } #[test] @@ -11573,9 +12171,7 @@ mod tests { S_ENDPGM, ]; - let code: Vec = words.iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -11592,9 +12188,12 @@ mod tests { let p = ir::build(&native.code, false, 256).unwrap(); - assert!(p.blocks.iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32")); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); let st = structure::structure(&p).unwrap(); let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); @@ -11611,13 +12210,13 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, - }).unwrap(); + emulate_mesh: false, + }) + .unwrap(); - let container = - crate::Container::parse(&emitted.dxil).unwrap(); + let container = crate::Container::parse(&emitted.dxil).unwrap(); - let features = - container.part(crate::FourCC::SFI0).unwrap(); + let features = container.part(crate::FourCC::SFI0).unwrap(); u64::from_le_bytes(features.data.try_into().unwrap()) } @@ -11894,3 +12493,7 @@ mod tests { assert_eq!(half(0xBC00 << half_shift(16)), -1.0); } } + + +#[cfg(test)] +include!("lower/code_table_tests.rs"); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5217df8d..e1db5764 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -84,11 +84,12 @@ mod bitcode; mod container; #[cfg(all(test, windows))] mod diff_tests; -#[cfg(all(test, windows))] -mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +#[cfg(all(test, windows))] +mod intersect_tests; mod lower; +mod mesh_emu; mod own_bits; mod rect; mod sampler; @@ -100,22 +101,23 @@ pub mod validator; mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; +mod wave; #[cfg(all(test, windows))] mod wave64_tests; -mod wave; use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; -pub use sampler::StaticSampler; pub use lower::set_host_max_wave; +pub use mesh_emu::{INDIRECT_SLOT_MAP_FLAG, MeshEmu, MeshMode, MeshOutput, unpack_vertex_shader}; pub use rect::rect_list_gs; +pub use sampler::StaticSampler; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, - set_view_heap_limit, view_heap_limit, + MEMORY_FAULTS, MEMORY_PAGES, MESH_EMU_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, + SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, + USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit, }; /// The loop limit without an override: 2^20. @@ -161,10 +163,16 @@ pub fn loop_limit() -> u32 { /// does). pub fn group_sync() -> u8 { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); - *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) { - Some("0") => 0, - Some("1") => 1, - _ => 2, + *MODE.get_or_init(|| { + match std::env::var("VICTORY_GROUP_SYNC") + .ok() + .as_deref() + .map(str::trim) + { + Some("0") => 0, + Some("1") => 1, + _ => 2, + } }) } @@ -266,6 +274,9 @@ pub struct HostShader { pub root_uavs: Vec, /// Heap descriptors that can be selected from root state at bind time. pub root_indexed_views: Vec, + /// Populated when a mesh program (`HwStage::Ms`) was translated in + /// [`MeshMode::Emulate`] mode as a `cs_6_6` compute shader. + pub mesh_emu: Option, } impl HostShader { @@ -296,7 +307,7 @@ pub struct UserData { } /// Translates the vertex, pixel, compute or mesh program of a console -/// shader container. +/// shader container with native mesh output. /// /// A program refused because the first half of an interpolation is read as /// data is translated once more with first halves evaluated as the pair @@ -305,15 +316,21 @@ pub struct UserData { /// already translated came out changed (an extra evaluation in each), for /// the sake of 9 that did not translate. pub fn translate(container: &[u8]) -> Result { - match translate_plain(container) { + translate_with(container, MeshMode::Native) +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container using `mesh` mode for mesh programs (`HwStage::Ms`). +pub fn translate_with(container: &[u8], mesh: MeshMode) -> Result { + match translate_plain(container, mesh) { Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => { - lower::with_first_half_pairs(|| translate_plain(container)) + lower::with_first_half_pairs(|| translate_plain(container, mesh)) } other => other, } } -fn translate_plain(container: &[u8]) -> Result { +fn translate_plain(container: &[u8], mesh: MeshMode) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) @@ -337,10 +354,10 @@ fn translate_plain(container: &[u8]) -> Result { let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; let io = io::raise(&p, &native)?; let st = st?; - emit(&c, &native, &p, &st, &io, &res) + emit_with(&c, &native, &p, &st, &io, &res, mesh) } -/// Emits a program whose earlier stages already ran. +/// Emits a program whose earlier stages already ran, with native mesh output. pub fn emit( c: &Container, native: &NativeProgram, @@ -348,10 +365,24 @@ pub fn emit( st: &structure::Structured, io: &io::Io, res: &resource::Resources, +) -> Result { + emit_with(c, native, p, st, io, res, MeshMode::Native) +} + +/// Emits a program whose earlier stages already ran, using `mesh` mode for +/// mesh programs (`HwStage::Ms`). +pub fn emit_with( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, + mesh: MeshMode, ) -> Result { // (what an earlier program's lowering on this thread left behind) lower::take_needs(); - let original = emit_program(c, native, p, st, io, res); + let original = emit_program(c, native, p, st, io, res, mesh); // A console wave64 compute program on a host of 32-lane waves that // still needs 64 lanes, or whose cross-lane code sits where not every // lane runs: once more with its early-outs left out @@ -389,7 +420,9 @@ pub fn emit( Ok(()) => true, Err((offset, what)) => { if why { - eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}"); + eprintln!( + "WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}" + ); } false } @@ -410,7 +443,7 @@ pub fn emit( ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { - let again = emit_program(c, native, p, st, io, res); + let again = emit_program(c, native, p, st, io, res, mesh); report(name, &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -433,9 +466,13 @@ pub fn emit( // lane runs, where the two host waves can exchange. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); - let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; + let deep = if deep_on { + form(ir::without_skips(p, true)) + } else { + None + }; if let Some((p, st, io, res)) = &deep { - let again = emit_program(c, native, p, st, io, res); + let again = emit_program(c, native, p, st, io, res, mesh); report("without skips, scalars followed", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -470,16 +507,31 @@ pub fn emit( if let Some((p, st, io, res)) = f && idiom(p, st) == exact { - let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); - report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); + let local = + lower::with_local_waves(|| emit_program(c, native, p, st, io, res, mesh)); + report( + &format!( + "local waves ({}), {name}", + if exact { "idiom" } else { "APPROXIMATE" } + ), + &local, + ); if done(&local) { return local.map(|(shader, _)| shader); } } } if idiom(p, st) == exact { - let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); - report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + let local = + lower::with_local_waves(|| emit_program(c, native, p, st, io, res, mesh)); + report( + if exact { + "local waves (idiom)" + } else { + "local waves (APPROXIMATE)" + }, + &local, + ); if done(&local) { return local.map(|(shader, _)| shader); } @@ -490,14 +542,20 @@ pub fn emit( if !strict { for (name, f) in &forms { if let Some((p, st, io, res)) = f { - let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); - report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); + let local = lower::with_local_waves_any(|| { + emit_program(c, native, p, st, io, res, mesh) + }); + report( + &format!("local waves (APPROXIMATE, any mask), {name}"), + &local, + ); if done(&local) { return local.map(|(shader, _)| shader); } } } - let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + let local = + lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res, mesh)); report("local waves (APPROXIMATE, any mask)", &local); if done(&local) { return local.map(|(shader, _)| shader); @@ -517,7 +575,7 @@ pub fn emit( let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); match again { Ok(_) => again, - Err(_) => emit_program(c, native, p, st, io, res), + Err(_) => emit_program(c, native, p, st, io, res, mesh), } } other => other, @@ -536,7 +594,7 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res, mesh).map(|(shader, _)| shader) } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -574,7 +632,7 @@ fn widen( let io = io::raise(p, native)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; lower::take_needs(); - let r = emit_program(c, native, p, &st, &io, &res); + let r = emit_program(c, native, p, &st, &io, &res, MeshMode::Native); let needs = lower::take_needs(); // (or translated for 64-lane waves still: shared memory read and written where not // every lane runs, whose blocks the lowering names too) @@ -594,7 +652,10 @@ fn widen( .collect(); if more.is_empty() { if why { - eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len()); + eprintln!( + "WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", + wide.len() + ); } return r; } @@ -610,6 +671,7 @@ fn emit_program( st: &structure::Structured, io: &io::Io, res: &resource::Resources, + mesh: MeshMode, ) -> Result<(HostShader, Option), ShaderError> { let sig = |fourcc| -> Result, ShaderError> { match c.part(fourcc) { @@ -678,6 +740,7 @@ fn emit_program( outputs, prims, mesh_stride, + emulate_mesh: native.stage == HwStage::Ms && mesh == MeshMode::Emulate, })?; let wave_size = l.wave_size; let shader = HostShader { @@ -701,6 +764,7 @@ fn emit_program( root_srvs: l.root_srvs, root_uavs: l.root_uavs, root_indexed_views: res.root_indexed_views.clone(), + mesh_emu: l.mesh_emu, }; Ok((shader, wave_size)) } @@ -799,6 +863,7 @@ fn signature(part: &[u8]) -> Result, ShaderError> { #[cfg(test)] mod tests { + #[cfg(windows)] use super::bitcode::Attr; use super::lower::LOOP_LIMIT; use super::parse_loop_limit; @@ -825,6 +890,7 @@ mod tests { } } use super::container::SigElement; + #[cfg(windows)] use super::shader::Shader; use super::*; use crate::native::{ComputeIo, StageIo}; @@ -1076,6 +1142,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -1088,6 +1155,7 @@ mod tests { root_srvs: Vec::new(), root_uavs: Vec::new(), root_indexed_views: Vec::new(), + mesh_emu: None, }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -1184,8 +1252,7 @@ mod tests { let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); let st = crate::structure::structure(&p).unwrap(); - let res = - crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); // dxil.dll, where there is one, checks PSV0 against the module. @@ -1356,9 +1423,13 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, }) .unwrap(); + #[cfg(windows)] let mut dxil = l.dxil; + #[cfg(not(windows))] + let _ = l.dxil; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), @@ -1377,6 +1448,7 @@ mod tests { root_srvs: l.root_srvs, root_uavs: l.root_uavs, root_indexed_views: Vec::new(), + mesh_emu: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let inputs: Vec = [ diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 55cc55de..1501bd19 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -119,6 +119,7 @@ fn lowered_on( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + emulate_mesh: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; @@ -132,6 +133,7 @@ fn lowered_on( root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, + mesh_emu: None, }) } From e63f09e49fbba1d395c542e89859284c7dd1807e Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:21:46 +0000 Subject: [PATCH 09/16] indirect: dedupe the bare-cost test module, mesh budget test on record_clamp_as Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/indirect.rs | 605 +---------------------------- 1 file changed, 3 insertions(+), 602 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 2aeef0f5..4f1dd851 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1269,14 +1269,15 @@ void main() { ]); } - assert!(record_clamp( + assert!(record_clamp_as( &warp.clamp, &warp.list, - &scratch, + (&scratch, D3D12_RESOURCE_STATE_COMMON), budget_gpu, (&next_args, 0), None, (2, STRIDE, 1), + false, )); warp.list.SetComputeRootSignature(&warp.worker.root); warp.list.SetPipelineState(&warp.worker.pso); @@ -3032,603 +3033,3 @@ void work() { } } -/// What one small draw costs this card, bare and with one thing changed -/// between every two draws: a measurement, not a check (it asserts only -/// that the card answered). The timing run of the lit scene (run 187) has -/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no -/// log says whether that is what we put around a command or what the card -/// takes for one. Each variant here is 10,000 one-triangle draws into a -/// 2560x1440 target, timed on the card by one pair of timestamps around -/// the whole batch (not one per command, which would time the stamps). -/// -/// Run by name, no game needed: -/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture` -#[cfg(test)] -mod bare_cost { - use windows::Win32::Foundation::{HANDLE, RECT}; - use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; - use windows::Win32::Graphics::Direct3D12::*; - use windows::Win32::Graphics::Dxgi::Common::*; - use windows::Win32::Graphics::Dxgi::*; - use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; - use windows::core::{Interface, s}; - - use crate::host::{compile, transition}; - - /// Draws in a batch. - const DRAWS: u32 = 10_000; - const WIDTH: u32 = 2560; - const HEIGHT: u32 = 1440; - - /// One small triangle in the middle of the target (about 180 pixels), - /// and two pixel programs that read one texel of a texture through a - /// table, so that the view heap set is in use. - const DRAW: &str = r#" -#define RS "DescriptorTable(SRV(t0))" -Texture2D image : register(t0); -[RootSignature(RS)] -float4 corner(uint i : SV_VertexID) : SV_Position { - float2 p = float2((i << 1) & 2, i & 2); - return float4(p * 0.02 - 0.01, 0.5, 1.0); -} -[RootSignature(RS)] -float4 first(float4 at : SV_Position) : SV_Target { - return image.Load(int3(0, 0, 0)); -} -[RootSignature(RS)] -float4 second(float4 at : SV_Position) : SV_Target { - return 1.0 - image.Load(int3(0, 0, 0)); -} -"#; - - /// A compute pass of next to nothing, as our clamp of an indirect - /// record is: one group of one thread that writes one word. - const WORK: &str = r#" -#define RS "UAV(u0)" -RWByteAddressBuffer words : register(u0); -[RootSignature(RS)] -[numthreads(1, 1, 1)] -void work() { - words.Store(0, words.Load(0) + 1); -} -"#; - - /// What changes between every two draws of a batch. - #[derive(Clone, Copy, PartialEq)] - enum Between { - /// Nothing. - Nothing, - /// The pipeline: two alternate. - Pipeline, - /// A second texture goes from target to shader read and back. - BarrierPair, - /// The depth texture bound for testing goes from write to read or - /// back. - DepthMove, - /// The pair of descriptor heaps: two pairs alternate. - Heaps, - /// The colour target: two alternate. - Targets, - /// A compute pass of ours of one group, and the pipeline back. - Compute, - /// The same between two waits for every earlier shader write, as - /// the clamp records them. - ComputeWithWaits, - } - - struct Rig { - queue: ID3D12CommandQueue, - allocator: ID3D12CommandAllocator, - list: ID3D12GraphicsCommandList, - fence: ID3D12Fence, - submitted: u64, - event: HANDLE, - root: ID3D12RootSignature, - pipelines: [ID3D12PipelineState; 2], - work_root: ID3D12RootSignature, - work: ID3D12PipelineState, - words: ID3D12Resource, - other: ID3D12Resource, - depth: ID3D12Resource, - /// Kept alive: the views below name them. - _kept: Vec, - _target_heaps: [ID3D12DescriptorHeap; 2], - heap_pairs: [[Option; 2]; 2], - tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], - targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], - _depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, - depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, - stamps: ID3D12QueryHeap, - back: ID3D12Resource, - card: String, - } - - fn texture( - device: &ID3D12Device, - (width, height): (u32, u32), - format: DXGI_FORMAT, - flags: D3D12_RESOURCE_FLAGS, - state: D3D12_RESOURCE_STATES, - ) -> ID3D12Resource { - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: u64::from(width), - Height: height, - DepthOrArraySize: 1, - MipLevels: 1, - Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Flags: flags, - ..Default::default() - }; - let mut out: Option = None; - // SAFETY: plain texture creation. - unsafe { - device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) - .unwrap(); - } - out.unwrap() - } - - fn buffer( - device: &ID3D12Device, - size: u64, - kind: D3D12_HEAP_TYPE, - flags: D3D12_RESOURCE_FLAGS, - state: D3D12_RESOURCE_STATES, - ) -> ID3D12Resource { - let heap = D3D12_HEAP_PROPERTIES { - Type: kind, - ..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 out: Option = None; - // SAFETY: plain buffer creation. - unsafe { - device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) - .unwrap(); - } - out.unwrap() - } - - fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { - let flags = if visible { - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE - } else { - D3D12_DESCRIPTOR_HEAP_FLAG_NONE - }; - // SAFETY: plain heap creation. - unsafe { - device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: count, - Flags: flags, - NodeMask: 0, - }) - .unwrap() - } - } - - fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { - let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }; - let mut blend = D3D12_BLEND_DESC::default(); - blend.RenderTarget[0].RenderTargetWriteMask = 0xf; - let mut formats = [DXGI_FORMAT(0); 8]; - formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - // SAFETY: the description points at live data and never releases - // its pointer to the root signature. - unsafe { - let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(root), - VS: code(vs), - PS: code(ps), - BlendState: blend, - SampleMask: u32::MAX, - RasterizerState: D3D12_RASTERIZER_DESC { - FillMode: D3D12_FILL_MODE_SOLID, - CullMode: D3D12_CULL_MODE_NONE, - DepthClipEnable: true.into(), - ..Default::default() - }, - // Depth is tested and never written, so the texture may be - // in the write state or in the read state under one view. - DepthStencilState: D3D12_DEPTH_STENCIL_DESC { - DepthEnable: true.into(), - DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, - DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, - ..Default::default() - }, - PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - NumRenderTargets: 1, - RTVFormats: formats, - DSVFormat: DXGI_FORMAT_D32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - ..Default::default() - }; - device.CreateGraphicsPipelineState(&desc).unwrap() - } - } - - impl Rig { - /// The default adapter, as the layer takes it; `None` without one - /// or on a software adapter. - fn new() -> Option { - let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; - let ps = [ - compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, - compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, - ]; - let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; - // SAFETY: plain object creation on a device of our own; the - // views are made in heaps that live as long as the rig. - unsafe { - let mut device: Option = None; - D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; - let device = device?; - let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) - .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) - .ok()? - .cast::() - .ok()? - .GetDesc1() - .ok()?; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { - return None; - } - let card = String::from_utf16_lossy(&desc.Description) - .trim_end_matches('\0') - .to_owned(); - 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 root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; - let pipelines = [ - pipeline(&device, &root, &vs, &ps[0]), - pipeline(&device, &root, &vs, &ps[1]), - ]; - let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; - let work: ID3D12PipelineState = device - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&work_root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: cs.as_ptr().cast(), - BytecodeLength: cs.len(), - }, - ..Default::default() - }) - .ok()?; - - let size = (WIDTH, HEIGHT); - let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); - let target = [ - colour(D3D12_RESOURCE_STATE_RENDER_TARGET), - colour(D3D12_RESOURCE_STATE_RENDER_TARGET), - ]; - let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); - let depth = texture( - &device, - size, - DXGI_FORMAT_D32_FLOAT, - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, - D3D12_RESOURCE_STATE_DEPTH_WRITE, - ); - let image = texture( - &device, - (4, 4), - DXGI_FORMAT_R8G8B8A8_UNORM, - D3D12_RESOURCE_FLAG_NONE, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - ); - let words = buffer( - &device, - 64 << 10, - D3D12_HEAP_TYPE_DEFAULT, - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - ); - let back = buffer( - &device, - 16, - D3D12_HEAP_TYPE_READBACK, - D3D12_RESOURCE_FLAG_NONE, - D3D12_RESOURCE_STATE_COPY_DEST, - ); - let mut stamps: Option = None; - device - .CreateQueryHeap( - &D3D12_QUERY_HEAP_DESC { - Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, - Count: 2, - NodeMask: 0, - }, - &mut stamps, - ) - .ok()?; - let stamps = stamps?; - - // Target and depth views. - let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); - let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; - let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; - targets[1].ptr += rtv_step; - device.CreateRenderTargetView(&target[0], None, targets[0]); - device.CreateRenderTargetView(&target[1], None, targets[1]); - let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); - let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; - let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); - let mut depth_tested = depth_written; - depth_tested.ptr += dsv_step; - device.CreateDepthStencilView(&depth, None, depth_written); - let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { - Format: DXGI_FORMAT_D32_FLOAT, - ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, - Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, - ..Default::default() - }; - device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); - - // Two pairs of shader-visible heaps: views (one view of the - // small texture each) and samplers (none used). - let view_heaps = [ - heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), - heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), - ]; - let sampler_heaps = [ - heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), - heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), - ]; - for views in &view_heaps { - device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); - } - let tables = [ - view_heaps[0].GetGPUDescriptorHandleForHeapStart(), - view_heaps[1].GetGPUDescriptorHandleForHeapStart(), - ]; - let heap_pairs = [ - [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], - [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], - ]; - - // The first list: both targets and the depth texture cleared. - list.ClearRenderTargetView(targets[0], &[0.0; 4], None); - list.ClearRenderTargetView(targets[1], &[0.0; 4], None); - list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); - let [first_target, second_target] = target; - let mut rig = Rig { - queue, - allocator, - list, - fence, - submitted: 0, - event, - root, - pipelines, - work_root, - work, - words, - other, - depth, - _kept: vec![first_target, second_target, image], - _target_heaps: [rtvs, dsvs], - heap_pairs, - tables, - targets, - _depth_written: depth_written, - depth_tested, - stamps, - back, - card, - }; - rig.finish(); - Some(rig) - } - } - - /// Closes the open list, runs it, waits for the card and opens the - /// list again. - fn finish(&mut self) { - self.submitted += 1; - // SAFETY: our list, queue and fence; the allocator is reset - // only after the card finished everything recorded from it. - unsafe { - self.list.Close().unwrap(); - let run: ID3D12CommandList = self.list.cast().unwrap(); - self.queue.ExecuteCommandLists(&[Some(run)]); - self.queue.Signal(&self.fence, self.submitted).unwrap(); - self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); - WaitForSingleObject(self.event, INFINITE); - self.allocator.Reset().unwrap(); - self.list.Reset(&self.allocator, None).unwrap(); - } - } - - /// What every list starts with: a new list has nothing set. - fn begin(&self) { - let l = &self.list; - // SAFETY: an open list and live objects and views. - unsafe { - l.SetDescriptorHeaps(&self.heap_pairs[0]); - l.SetGraphicsRootSignature(&self.root); - l.SetPipelineState(&self.pipelines[0]); - l.SetGraphicsRootDescriptorTable(0, self.tables[0]); - l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); - l.RSSetViewports(&[D3D12_VIEWPORT { - TopLeftX: 0.0, - TopLeftY: 0.0, - Width: WIDTH as f32, - Height: HEIGHT as f32, - MinDepth: 0.0, - MaxDepth: 1.0, - }]); - l.RSSetScissorRects(&[RECT { - left: 0, - top: 0, - right: WIDTH as i32, - bottom: HEIGHT as i32, - }]); - // A triangle list. - l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); - } - } - - /// One batch of [`DRAWS`] draws in `lists` lists run one by one, - /// with `between` recorded before every draw: the microseconds a - /// draw took on the card, and the milliseconds recording took. - fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { - let (target, read, written, tested) = ( - D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_DEPTH_WRITE, - D3D12_RESOURCE_STATE_DEPTH_READ, - ); - let started = std::time::Instant::now(); - let mut drawn = 0u32; - for part in 0..lists { - let l = &self.list; - // SAFETY: an open list; our query heap; live objects. - unsafe { - if part == 0 { - l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); - } - } - self.begin(); - // SAFETY: an open list with everything set; live objects. - // Every state moved is moved back within the batch (the - // draws of a list are an even number). - unsafe { - for _ in 0..DRAWS / lists { - let odd = (drawn % 2) as usize; - match between { - Between::Nothing => {} - Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), - Between::BarrierPair => { - l.ResourceBarrier(&[transition(&self.other, target, read)]); - l.ResourceBarrier(&[transition(&self.other, read, target)]); - } - Between::DepthMove => { - let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; - l.ResourceBarrier(&[transition(&self.depth, from, to)]); - } - Between::Heaps => { - l.SetDescriptorHeaps(&self.heap_pairs[odd]); - l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); - } - Between::Targets => { - l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); - } - Between::Compute | Between::ComputeWithWaits => { - let waits = between == Between::ComputeWithWaits; - if waits { - l.ResourceBarrier(&[super::uav_barrier()]); - } - l.SetComputeRootSignature(&self.work_root); - l.SetPipelineState(&self.work); - l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); - l.Dispatch(1, 1, 1); - if waits { - l.ResourceBarrier(&[super::uav_barrier()]); - } - l.SetPipelineState(&self.pipelines[0]); - } - } - l.DrawInstanced(3, 1, 0, 0); - drawn += 1; - } - if part + 1 < lists { - // The next list of the batch: this one is sent on - // its own and the list is opened again at once - // (the allocator is not reset before the card is - // done with all of them). - l.Close().unwrap(); - let run: ID3D12CommandList = l.cast().unwrap(); - self.queue.ExecuteCommandLists(&[Some(run)]); - l.Reset(&self.allocator, None).unwrap(); - } else { - l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); - l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); - } - } - } - let recording = started.elapsed().as_secs_f64() * 1e3; - self.finish(); - let mut data = std::ptr::null_mut(); - let range = D3D12_RANGE { Begin: 0, End: 16 }; - // SAFETY: a read-back buffer the finished list resolved two - // timestamps into. - let ticks = unsafe { - self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); - let stamps = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); - self.back.Unmap(0, None); - stamps[1].saturating_sub(stamps[0]) - }; - // SAFETY: a plain query of our queue. - let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); - (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) - } - } - - #[test] - #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] - fn bare_command_cost() { - let Some(mut rig) = Rig::new() else { - eprintln!("no hardware adapter, or our shaders did not compile; skipped"); - return; - }; - eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); - // The first batch pays for whatever the driver does at first use. - rig.batch(Between::Nothing, 1); - let variants = [ - ("(a) nothing changes between draws", Between::Nothing, 1), - ("(b) another pipeline every draw", Between::Pipeline, 1), - ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), - ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), - ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), - ("(f) another colour target every draw", Between::Targets, 1), - ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), - ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), - ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), - ]; - let mut least = Vec::new(); - for (name, between, lists) in variants { - let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); - runs.sort_by(|a, b| a.0.total_cmp(&b.0)); - eprintln!( - "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", - runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 - ); - least.push(runs[0].0); - } - assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); - } -} From f0a8aba63548fc9abd84107ffb05e294b69ba5c1 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:26:00 +0000 Subject: [PATCH 10/16] gpu: wire the emulated mesh pipeline creation onto the new pipeline architecture emulated_mesh_pipeline + push_stage_params ported onto the fxceless round-2 pipeline/host.rs (their stream/depth-bounds/library machinery unchanged); HostPipeline gains mesh_emu; the creation hook emulates when the host has no native mesh tier. shader_cache: mesh byte in the converter input is stripped with the build fingerprint (input[33..]). Dispatch wiring in draw.rs is the remaining piece. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/pipeline/host.rs | 397 +++++++++++++++++++++++- crates/victory-gpu/src/shader_cache.rs | 24 +- 2 files changed, 402 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 9aef7b8f..9e78c6e0 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -8,7 +8,9 @@ use std::ffi::{CStr, CString}; use std::sync::Arc; -use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use victory_shader::emit::{ + MESH_EMU_SPACE, MeshEmu, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, unpack_vertex_shader, +}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -300,6 +302,19 @@ impl Stage { } } +/// Additional pipelines and binding slots of a mesh pipeline emulated as +/// compute plus a generated vertex shader. +pub(crate) struct EmulatedMeshPipeline { + pub(crate) emu: MeshEmu, + pub(crate) cs_pso: ID3D12PipelineState, + pub(crate) cs_root: ID3D12RootSignature, + pub(crate) cs_stage: Stage, + pub(crate) cs_uav_param: u32, + pub(crate) cs_cbv_param: Option, + pub(crate) cs_srv_param: Option, + pub(crate) draw_srv_param: u32, +} + pub(crate) struct HostPipeline { /// A compute pipeline (else graphics). pub(crate) compute: bool, @@ -307,8 +322,12 @@ pub(crate) struct HostPipeline { pub(crate) mesh: bool, pub(crate) pso: ID3D12PipelineState, pub(crate) root: ID3D12RootSignature, - /// Vertex, then pixel stage, or the compute stage. + /// Vertex, then pixel stage, or the compute stage. For an emulated mesh + /// pipeline this holds only the pixel stage; the mesh compute stage lives + /// in `mesh_emu`. pub(crate) stages: Vec, + /// Compute and unpack-vertex pipeline state for emulated mesh shaders. + pub(crate) mesh_emu: Option, /// The vertex buffer slots it reads (bit per slot). pub(crate) slots: u32, pub(crate) inputs: Vec, @@ -335,6 +354,366 @@ fn refuse(reason: &'static str, shaders: &[Arc]) -> Option None } +#[allow(clippy::vec_box)] // boxed ranges keep stable addresses until the root signature is serialized +fn push_stage_params( + shader: &Arc, + visibility: D3D12_SHADER_VISIBILITY, + params: &mut Vec, + ranges: &mut Vec>, + samplers: &mut Vec, +) -> Option { + let t = &shader.translated()?.host; + let mut stage = Stage { + shader: shader.clone(), + user_data: None, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + }; + let dwords = t.user_data_dwords(); + if dwords > 0 { + stage.user_data = Some((params.len() as u32, dwords)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + }); + } + for (slots, kind, out) in [ + ( + &t.root_cbvs, + D3D12_ROOT_PARAMETER_TYPE_CBV, + &mut stage.root_cbvs, + ), + ( + &t.root_srvs, + D3D12_ROOT_PARAMETER_TYPE_SRV, + &mut stage.root_srvs, + ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), + ] { + for &slot in slots { + let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV; + // Ours, not the title's, stay root descriptors: the table of + // strides, the directory of title memory by address and its + // fault notes. + let ours = if uav { + slot == victory_shader::emit::SLOT_FAULTS + } else { + slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_MEMORY + }; + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && 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. + ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { + RangeType: if uav { + D3D12_DESCRIPTOR_RANGE_TYPE_UAV + } else { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV + }, + NumDescriptors: 1, + BaseShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + })); + let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?; + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: range, + }, + }, + ShaderVisibility: visibility, + }); + continue; + } + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } + } + for (n, s) in t.static_samplers.iter().enumerate() { + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(s.filter as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), + MipLODBias: s.mip_lod_bias, + MaxAnisotropy: s.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32), + MinLOD: s.min_lod, + MaxLOD: s.max_lod, + ShaderRegister: n as u32, + RegisterSpace: SAMPLER_SPACE, + ShaderVisibility: visibility, + }); + } + Some(stage) +} + +/// A mesh pipeline emulated as compute plus a generated vertex shader. +/// The compute step writes the mesh records into the shared emulation +/// buffer; the graphics step unpacks them with no input assembler data. +fn emulated_mesh_pipeline( + ms: &Arc, + ps: Option<&Arc>, + emu: &MeshEmu, + g: &GraphicsState, + shaders: &[Arc], +) -> Option { + let host = host()?; + let group_bytes = u64::from(emu.max_primitives) * 4 + + u64::from(emu.max_vertices) * u64::from(emu.vertex_dwords) * 4 + + u64::from(emu.max_primitives) * u64::from(emu.prim_dwords) * 4; + if group_bytes > u64::from(u32::MAX) { + tracing::warn!(?shaders, "emulated mesh group layout overflows u32"); + return None; + } + let mut cs_params = Vec::new(); + let mut cs_ranges = Vec::new(); + let mut cs_samplers = Vec::new(); + let cs_stage = push_stage_params( + ms, + D3D12_SHADER_VISIBILITY_ALL, + &mut cs_params, + &mut cs_ranges, + &mut cs_samplers, + )?; + let cs_uav_param = cs_params.len() as u32; + cs_params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + let (cs_cbv_param, cs_srv_param) = if emu.reads_group_id { + let cbv = cs_params.len() as u32; + cs_params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: MESH_EMU_SPACE, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + let srv = cs_params.len() as u32; + cs_params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + (Some(cbv), Some(srv)) + } else { + (None, None) + }; + let (cs_root, cs_root_blob) = match root_signature(&host.device, &cs_params, &cs_samplers, true) + { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "emulated mesh CS root signature refused"); + return None; + } + }; + let cs_dxil = &ms.translated()?.host.dxil; + let cs_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: borrowed root signature pointer for the Create/Load call. + pRootSignature: unsafe { std::mem::transmute_copy(&cs_root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs_dxil.as_ptr().cast(), + BytecodeLength: cs_dxil.len(), + }, + ..Default::default() + }; + let cs_name = super::library::name("mesh-emu-cs", &cs_root_blob, &[cs_dxil], ""); + let cs_pso = match super::library::pipeline( + &cs_name, + // SAFETY: descriptor points at live root signature and CS DXIL bytes. + |library, name| unsafe { library.LoadComputePipeline(name, &cs_desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateComputePipelineState(&cs_desc) }, + ) { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "emulated mesh CS pipeline refused"); + host.log_messages(); + return None; + } + }; + crate::host::name(&cs_pso, || format!("{shaders:?} [mesh-emu cs]")); + + let ps_dxil = match ps { + Some(ps) => Some(ps.translated()?.host.dxil.as_slice()), + None => None, + }; + let unpack_vs = match unpack_vertex_shader(emu, ps_dxil) { + Ok(vs) => vs, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "unpack vertex shader generation failed"); + return None; + } + }; + let mut gfx_params = Vec::new(); + let mut gfx_ranges = Vec::new(); + let mut gfx_samplers = Vec::new(); + let mut gfx_stages = Vec::new(); + if let Some(ps) = ps { + gfx_stages.push(push_stage_params( + ps, + D3D12_SHADER_VISIBILITY_PIXEL, + &mut gfx_params, + &mut gfx_ranges, + &mut gfx_samplers, + )?); + } + let draw_srv_param = gfx_params.len() as u32; + gfx_params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, + RegisterSpace: MESH_EMU_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, + }); + let (gfx_root, gfx_root_blob) = match root_signature( + &host.device, + &gfx_params, + &gfx_samplers, + false, + ) { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "emulated mesh graphics root signature refused"); + return None; + } + }; + let ps_code = ps_dxil.map_or_else(D3D12_SHADER_BYTECODE::default, |b| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }); + let gfx_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed root signature pointer for the Create/Load call. + pRootSignature: unsafe { std::mem::transmute_copy(&gfx_root) }, + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: unpack_vs.as_ptr().cast(), + BytecodeLength: unpack_vs.len(), + }, + PS: ps_code, + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: std::ptr::null(), + NumElements: 0, + }, + IBStripCutValue: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: g.targets.NumRenderTargets, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + let depth_bounds = if g.depth_bounds { + host.depth_bounds() + } else { + false + }; + let state = g.describe(); + let gfx_name = super::library::name( + "mesh-emu-gfx", + &gfx_root_blob, + &[&unpack_vs, ps_dxil.unwrap_or(&[])], + &state, + ); + let made = if depth_bounds { + graphics_depth_bounds_pipeline(&host.device, &gfx_root, &gfx_desc, g.depth1(), &gfx_name) + } else { + super::library::pipeline( + &gfx_name, + // SAFETY: descriptor points at live root signature, VS, and PS bytes. + |library, name| unsafe { library.LoadGraphicsPipeline(name, &gfx_desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateGraphicsPipelineState(&gfx_desc) }, + ) + }; + let gfx_pso = match made { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "emulated mesh graphics pipeline refused"); + host.log_messages(); + return None; + } + }; + crate::host::name(&gfx_pso, || format!("{shaders:?} [mesh-emu gfx]")); + tracing::info!(?shaders, "host emulated mesh pipeline"); + Some(HostPipeline { + compute: false, + mesh: true, + pso: gfx_pso, + root: gfx_root, + stages: gfx_stages, + mesh_emu: Some(EmulatedMeshPipeline { + emu: emu.clone(), + cs_pso, + cs_root, + cs_stage, + cs_uav_param, + cs_cbv_param, + cs_srv_param, + draw_srv_param, + }), + slots: 0, + inputs: Vec::new(), + rects: false, + name: format!("{shaders:?}"), + state: String::new(), + }) +} + impl HostPipeline { /// A host pipeline for vertex and pixel shaders with the graphics /// state `g`, or for one compute shader. @@ -370,13 +749,22 @@ impl HostPipeline { stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); stages }; - if mesh.is_some() && !host()?.mesh_shaders() { + if mesh.is_some() && !(host()?.mesh_shaders() || host()?.emulate_mesh_shaders()) { return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); } for (s, _) in &stages { s.translated()?; } let host = host()?; + if let Some(ms) = mesh + && host.emulate_mesh_shaders() + && let Some(emu) = ms.translated()?.host.mesh_emu.as_ref() + { + let Some(g) = g else { + return refuse("graphics state not kept (plain description)", shaders); + }; + return emulated_mesh_pipeline(ms, find("pixel"), emu, g, shaders); + } // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); @@ -549,6 +937,7 @@ impl HostPipeline { pso, root, stages: bound, + mesh_emu: None, name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), @@ -602,6 +991,7 @@ impl HostPipeline { pso, root, stages: bound, + mesh_emu: None, name: format!("{shaders:?}"), slots: 0, inputs: Vec::new(), @@ -718,6 +1108,7 @@ impl HostPipeline { pso, root, stages: bound, + mesh_emu: None, name: format!("{shaders:?}"), slots: g.slots(), inputs: g.elements(), diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index c5cbfba2..807af7fa 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -125,7 +125,7 @@ impl Result + Send + Sync> Converter for Tra } fn convert(&self, input: &[u8]) -> anyhow::Result> { self.ran.store(true, Ordering::Relaxed); - let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; + let shader = (self.translate)(&input[33..]).map_err(anyhow::Error::msg)?; Ok(encode(&shader)) } } @@ -179,7 +179,11 @@ const STAGES: [HwStage; 8] = [ HwStage::Cs, ]; -fn root_code(r: RootType) -> u32 { +/// The tag of [`RootType::Other`]: a tag cannot hold every `u32`, so its +/// raw value follows it as its own word. +const OTHER_ROOT: u32 = 6; + +fn root_tag(r: RootType) -> u32 { match r { RootType::Constants => 0, RootType::Descriptor => 1, @@ -187,19 +191,7 @@ fn root_code(r: RootType) -> u32 { RootType::ImmediateSampler => 3, RootType::ResourceHeap => 4, RootType::SamplerHeap => 5, - RootType::Other(x) => 6 + x, - } -} - -fn root_type(code: u32) -> RootType { - match code { - 0 => RootType::Constants, - 1 => RootType::Descriptor, - 2 => RootType::Table, - 3 => RootType::ImmediateSampler, - 4 => RootType::ResourceHeap, - 5 => RootType::SamplerHeap, - x => RootType::Other(x - 6), + RootType::Other(_) => OTHER_ROOT, } } @@ -213,7 +205,7 @@ fn encode(s: &HostShader) -> Vec { out.extend(&s.dxil); word(&mut out, s.user_data.len() as u32); for u in &s.user_data { - for v in [u.index, u32::from(u.slot), root_code(u.root)] { + for v in [u.index, u32::from(u.slot), root_tag(u.root)] { word(&mut out, v); } if let RootType::Other(raw) = u.root { From 7b25fda340e73ec83199e8ebc1ac5c1bbb0c8436 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:32:29 +0000 Subject: [PATCH 11/16] gpu: emulated mesh shaders dispatch on hardware without mesh support Re-applies the mesh-emulation dispatch path onto the round-2 base: bind_parts split (title vs host compute state) with a thin bind wrapper, the emulated compute/graphics bind and restore helpers, the chunked direct dispatch, and the ExecuteIndirect mesh path with its slot-map preparation. Target state handling shared through ensure_targets. Also fixes newer-clippy lints: PLACED_TWINS getter gated to diagnostics, BUILD_LEN used in the cache key strip, is_multiple_of, sort key. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 442 ++++++++++++++++++++++--- crates/victory-gpu/src/resource.rs | 2 +- crates/victory-gpu/src/shader_cache.rs | 2 +- crates/victory-gpu/src/shadow.rs | 2 +- 4 files changed, 404 insertions(+), 44 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c5e7655d..0060f6b5 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -15,14 +15,14 @@ use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; use windows::Win32::Foundation::RECT; -use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; +use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; -use crate::host::HostList; +use crate::host::{HostList, transition}; use crate::object::This; -use crate::pipeline::host::HostPipeline; +use crate::pipeline::host::{HostPipeline, Stage}; /// A root argument as the title set it. #[derive(Debug, Clone, Default)] @@ -911,6 +911,13 @@ impl State { // SAFETY: an open list; the view names a live host buffer. unsafe { l.IASetIndexBuffer(Some(&view)) }; } + self.ensure_targets(list); + true + } + + /// Render targets in render-target state and the depth texture in its + /// read or write state: what a draw's targets need before it runs. + fn ensure_targets(&self, list: &HostList) { const RENDER_TARGET: u32 = 0x4; for &t in &self.targets { crate::list::ensure_state(list, t as This, RENDER_TARGET); @@ -918,11 +925,6 @@ impl State { 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 - // put it out of the state those views need, and a move to it - // and back for every such draw). let state = if self.depth_state == DEPTH_READ { let (tested, read) = TESTED_DEPTH.get(); if read && tested == self.depth { @@ -935,7 +937,6 @@ impl State { }; crate::list::ensure_state(list, self.depth as This, state); } - true } /// A descriptor a shader reads through a table: its host slot made if @@ -946,11 +947,26 @@ impl State { /// False if the draw or dispatch must not run: a root SRV it reads /// could not be given a view. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + self.bind_parts(list, p, &p.root, &p.pso, &p.name, &p.stages, compute, compute) + } + + #[allow(clippy::too_many_arguments)] + fn bind_parts( + &mut self, + list: &HostList, + pipeline: &HostPipeline, + root_signature: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + name: &str, + stages: &[Stage], + title_compute: bool, + host_compute: bool, + ) -> bool { let l = &list.list; // Textures picked by index, before anything asks for them. - self.early_textures(list, p, compute); + self.early_textures(list, pipeline, title_compute); if crate::host::walls_trace() { - self.walls_census(p, compute); + self.walls_census(pipeline, title_compute); } // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -970,39 +986,39 @@ impl State { } // The depth target a draw only tests, for the views of it that the // draw's shaders read (`readable`). - let tested = if !compute && self.depth_state == DEPTH_READ { + let tested = if !title_compute && self.depth_state == DEPTH_READ { self.depth } else { 0 }; TESTED_DEPTH.set((tested, false)); - let root = p.root.as_raw() as usize; - if self.host_roots[usize::from(compute)] != root { + let root = root_signature.as_raw() as usize; + if self.host_roots[usize::from(host_compute)] != root { // SAFETY: an open list and a live root signature. unsafe { - if compute { - l.SetComputeRootSignature(&p.root); + if host_compute { + l.SetComputeRootSignature(root_signature); } else { - l.SetGraphicsRootSignature(&p.root); + l.SetGraphicsRootSignature(root_signature); } } - self.host_roots[usize::from(compute)] = root; + self.host_roots[usize::from(host_compute)] = root; } // By host object: a title pipeline released and another made at its // address is another host pipeline (the list keeps the old one). - if self.host_pipeline != p.pso.as_raw() as usize { + if self.host_pipeline != pso.as_raw() as usize { // SAFETY: an open list and a live pipeline. - unsafe { l.SetPipelineState(&p.pso) }; - self.host_pipeline = p.pso.as_raw() as usize; - list.used_pipeline(&p.name); + unsafe { l.SetPipelineState(pso) }; + self.host_pipeline = pso.as_raw() as usize; + list.used_pipeline(name); // The title may release the pipeline before it submits the list. - list.keep(&p.pso); - list.keep(&p.root); + list.keep(pso); + list.keep(root_signature); } - for stage in &p.stages { + for stage in stages { let t = stage.translated(); STORES.set(t.stores); - let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); + let made = self.tables(list, &t.used, &t.host.root_indexed_views, title_compute); STORES.set(true); if made.iter().any(|m| m.1 == u32::MAX) { once!("a draw whose descriptor table found no free slots is dropped"); @@ -1014,7 +1030,7 @@ impl State { && !crate::pipeline::builder_quarantined(self.pipeline as This); // Title memory by address: what the shader finds it by. let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { - let Some(ready) = self.memory_ready(list, compute, writes) else { + let Some(ready) = self.memory_ready(list, title_compute, writes) else { once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); return false; }; @@ -1027,7 +1043,7 @@ impl State { for u in &t.host.user_data { if let RootType::Other(kind) = u.root { values[u.index as usize] = - self.host_word(compute, kind, u.slot, u.dword, memory.as_ref()); + self.host_word(title_compute, kind, u.slot, u.dword, memory.as_ref()); continue; } let fresh = made @@ -1035,12 +1051,12 @@ impl State { .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, - None => self.user_value(compute, u.slot, u.root, u.dword), + None => self.user_value(title_compute, u.slot, u.root, u.dword), }; } // SAFETY: an open list; `values` covers the parameter. unsafe { - if compute { + if host_compute { l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); } else { l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); @@ -1055,7 +1071,7 @@ impl State { // SAFETY: an open list; the directory lives as // long as the process and the list holds it. unsafe { - if compute { + if host_compute { l.SetComputeRootShaderResourceView(param, m.directory); } else { l.SetGraphicsRootShaderResourceView(param, m.directory); @@ -1071,7 +1087,7 @@ impl State { // SAFETY: an open list; the table lives as long // as the heap the list holds. Some(gpu) => unsafe { - if compute { + if host_compute { l.SetComputeRootShaderResourceView(param, gpu); } else { l.SetGraphicsRootShaderResourceView(param, gpu); @@ -1082,11 +1098,11 @@ impl State { continue; } let tabled = srv && crate::pipeline::host::bounded_root_srvs(); - let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) + let Some(&Root::View(address)) = self.roots_ref(title_compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); // A table left unset is undefined: a null view. - if tabled && !self.root_srv_table(list, None, param, compute, false) { + if tabled && !self.root_srv_table(list, None, param, host_compute, false) { return false; } continue; @@ -1098,7 +1114,7 @@ impl State { && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS) }); if tabled { - if !self.root_srv_table(list, Some(address), param, compute, biased) { + if !self.root_srv_table(list, Some(address), param, host_compute, biased) { return false; } continue; @@ -1108,7 +1124,7 @@ impl State { }; if biased { gpu -= u64::from(self.host_word( - compute, + title_compute, victory_shader::emit::USER_VIEW_BIAS, slot, 0, @@ -1117,7 +1133,7 @@ impl State { } // SAFETY: an open list; the address is in live memory. unsafe { - match (compute, srv) { + match (host_compute, srv) { (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), (true, false) => l.SetComputeRootConstantBufferView(param, gpu), @@ -1133,7 +1149,7 @@ impl State { // SAFETY: an open list; the buffer lives as long as // the process and the list holds it. unsafe { - if compute { + if host_compute { l.SetComputeRootUnorderedAccessView(param, m.faults); } else { l.SetGraphicsRootUnorderedAccessView(param, m.faults); @@ -1142,14 +1158,14 @@ impl State { } continue; } - let address = match self.roots_ref(compute).get(usize::from(slot)) { + let address = match self.roots_ref(title_compute).get(usize::from(slot)) { Some(&Root::View(address)) => Some(address), _ => { once!(slot, "a shader writes through a root view the title did not set"); None } }; - if !self.root_uav(list, address, param, compute, writes) { + if !self.root_uav(list, address, param, host_compute, writes) { return false; } } @@ -2350,6 +2366,16 @@ impl State { self.window = None; #[cfg(feature = "diagnostics")] self.trace("mesh", x, 0); + if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) + && p.mesh_emu.is_some() + { + if !self.dispatch_mesh_emulated(list, p, x) { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + return; + } let ran = mesh_test() != 1 && mesh_kept(self.pipeline) && self.prepare_for(list, false, true) @@ -2403,7 +2429,7 @@ impl State { let draws: u32 = census.1.values().sum(); if draws > 0 { let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); - rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); let scissors: Vec = rects .iter() .take(5) @@ -2441,6 +2467,327 @@ impl State { } } + fn bind_emulated_cs( + &mut self, + list: &HostList, + p: &HostPipeline, + buffers: &crate::mesh_emu::Buffers, + base_group: u32, + slot_map_gpu: u64, + ) -> bool { + let Some(emu) = &p.mesh_emu else { + return false; + }; + if !self.bind_parts( + list, + p, + &emu.cs_root, + &emu.cs_pso, + &p.name, + std::slice::from_ref(&emu.cs_stage), + false, + true, + ) { + return false; + } + let l = &list.list; + // SAFETY: an open list; emulation buffers are static and also kept + // with the list below. + unsafe { + l.SetComputeRootUnorderedAccessView(emu.cs_uav_param, buffers.output_gpu); + if let Some(param) = emu.cs_cbv_param { + let constants = [base_group, 0, 0, 0]; + l.SetComputeRoot32BitConstants(param, 4, constants.as_ptr().cast(), 0); + } + if let Some(param) = emu.cs_srv_param { + l.SetComputeRootShaderResourceView(param, slot_map_gpu); + } + } + list.keep(&buffers.output); + list.keep(&buffers.slot_map); + list.keep(&buffers.dummy_srv); + true + } + + fn bind_emulated_gfx( + &mut self, + list: &HostList, + p: &HostPipeline, + buffers: &crate::mesh_emu::Buffers, + ) -> bool { + let Some(emu) = &p.mesh_emu else { + return false; + }; + if !self.bind_parts(list, p, &p.root, &p.pso, &p.name, &p.stages, false, false) { + return false; + } + let l = &list.list; + // SAFETY: an open list; `output` is live and in non-pixel shader + // resource state when the draw is recorded. + unsafe { + l.SetGraphicsRootShaderResourceView(emu.draw_srv_param, buffers.output_gpu); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + } + self.ensure_targets(list); + true + } + + fn restore_mesh_emu_state(&mut self, list: &HostList) { + if self.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32 { + self.set_topology(list, self.topology); + } + self.host_pipeline = 0; + self.host_roots = [0; 2]; + } + + fn dispatch_mesh_emulated(&mut self, list: &HostList, p: &HostPipeline, x: u32) -> bool { + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + return false; + } + let Some(emu_pipe) = &p.mesh_emu else { + return false; + }; + if mesh_test() == 1 || !mesh_kept(self.pipeline) { + return false; + } + if x == 0 { + DRAWN.fetch_add(1, Ordering::Relaxed); + return true; + } + let Some(buffers) = crate::mesh_emu::buffers() else { + return false; + }; + let group_cap = buffers.group_cap(emu_pipe.emu.group_bytes()); + if group_cap == 0 { + once!( + group_bytes = emu_pipe.emu.group_bytes(), + "mesh emulation buffer too small for one group" + ); + return false; + } + let mut base = 0u32; + while base < x { + let chunk = (x - base).min(group_cap); + if !self.bind_emulated_cs(list, p, buffers, base, buffers.dummy_srv_gpu) { + self.restore_mesh_emu_state(list); + return false; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("mesh-emu {chunk} (base {base})"), false)); + // SAFETY: open list with the emulated compute pipeline bound and + // `output` in unordered-access state. + unsafe { + list.list.Dispatch(chunk, 1, 1); + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + if !self.bind_emulated_gfx(list, p, buffers) { + // SAFETY: restore `output` for the next compute step. + unsafe { + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + self.restore_mesh_emu_state(list); + return false; + } + // SAFETY: open list with the unpack graphics pipeline bound and + // `output` readable as a shader resource. + let Some(vertices) = chunk + .checked_mul(emu_pipe.emu.max_primitives) + .and_then(|n| n.checked_mul(3)) + else { + self.restore_mesh_emu_state(list); + return false; + }; + self.mesh_scissor(list, true); + unsafe { + list.list.DrawInstanced(vertices, 1, 0, 0); + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + self.mesh_scissor(list, false); + base += chunk; + } + self.restore_mesh_emu_state(list); + DRAWN.fetch_add(1, Ordering::Relaxed); + true + } + + fn execute_indirect_mesh_emulated( + &mut self, + list: &HostList, + p: &HostPipeline, + (stride, max): (u32, u32), + (args, arguments, len): (&std::sync::Arc, u64, u64), + counter: Option<(&std::sync::Arc, u64)>, + why: &dyn Fn(&str), + ) -> bool { + // A non-windowed indirect call ends any cached run of clamped draws. + self.window = None; + if mesh_test() == 1 || !mesh_kept(self.pipeline) { + why("mesh draws are switched off (VICTORY_MESH_TEST)"); + return false; + } + if stride < 12 { + why("indirect mesh stride smaller than 12 bytes"); + return false; + } + // Bound CPU/GPU preparation work without rejecting a sparse call + // whose API maximum exceeds the slot-map capacity. + let record_count = max.min(crate::mesh_emu::MAX_INDIRECT_RECORDS); + let Some(emu_pipe) = &p.mesh_emu else { + return false; + }; + let Some(buffers) = crate::mesh_emu::buffers() else { + why("no mesh emulation buffers"); + return false; + }; + let group_cap = buffers.group_cap(emu_pipe.emu.group_bytes()); + if group_cap == 0 { + why("mesh emulation buffer smaller than one group"); + return false; + } + let (Some(dispatch_sig), Some(draw_sig)) = (host_signature(2, 12), host_signature(0, 16)) + else { + why("no host indirect command signature"); + return false; + }; + let count_gpu = counter.map(|(s, at)| s.gpu(at)); + if count_gpu.is_some_and(|g| !g.is_multiple_of(4)) { + why("count not 4-byte aligned"); + return false; + } + let Some(budget_gpu) = list.budget() else { + why("indirect mesh work budget unavailable"); + return false; + }; + if !stride.is_multiple_of(4) + || u64::from(stride) * u64::from(record_count) > u64::from(u32::MAX) + || !args.gpu(arguments).is_multiple_of(4) + { + why("indirect mesh arguments are unaligned or exceed the shader address range"); + return false; + } + let refresh_len = + len.min(u64::from(stride) * u64::from(record_count.max(1))); + args.refresh(list, arguments, refresh_len); + if let Some((s, at)) = counter { + s.refresh(list, at, 4); + } + if !buffers.prepare_indirect( + list, + args.gpu(arguments), + count_gpu, + budget_gpu, + stride, + record_count, + emu_pipe.emu.max_primitives, + group_cap, + ) { + why("no mesh indirect preparation pipeline"); + return false; + } + list.keep(&buffers.indirect_args); + self.host_pipeline = 0; + self.host_roots = [0; 2]; + + let finish_indirect = |list: &HostList| { + let args_back = transition( + &buffers.indirect_args, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + // SAFETY: an open list; emulation buffers return to UAV for the + // next preparation pass. + unsafe { + if max > 1 { + let map_back = transition( + &buffers.slot_map, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + list.list.ResourceBarrier(&[args_back, map_back]); + } else { + list.list.ResourceBarrier(&[args_back]); + } + } + }; + + let (base_group, slot_map_gpu) = if max > 1 { + ( + victory_shader::emit::INDIRECT_SLOT_MAP_FLAG, + buffers.slot_map_gpu, + ) + } else { + (0, buffers.dummy_srv_gpu) + }; + if !self.bind_emulated_cs(list, p, buffers, base_group, slot_map_gpu) { + finish_indirect(list); + self.restore_mesh_emu_state(list); + why("prepare emulated mesh CS failed"); + return false; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text( + format!("indirect mesh-emu max {max} at {arguments:#x}"), + false, + ) + }); + // SAFETY: open list with the emulated compute pipeline bound, + // generated indirect arguments, and `output` in UAV state. + unsafe { + list.list + .ExecuteIndirect(&dispatch_sig, 1, &buffers.indirect_args, 0, None, 0); + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + if !self.bind_emulated_gfx(list, p, buffers) { + // SAFETY: restore `output` for the next dispatch. + unsafe { + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + finish_indirect(list); + self.restore_mesh_emu_state(list); + why("prepare emulated mesh graphics failed"); + return false; + } + // SAFETY: open list with the unpack graphics pipeline bound and + // generated draw arguments at offset 16. + self.mesh_scissor(list, true); + unsafe { + list.list + .ExecuteIndirect(&draw_sig, 1, &buffers.indirect_args, 16, None, 0); + list.list.ResourceBarrier(&[transition( + &buffers.output, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + self.mesh_scissor(list, false); + finish_indirect(list); + self.restore_mesh_emu_state(list); + DRAWN.fetch_add(1, Ordering::Relaxed); + true + } + fn roots_ref(&self, compute: bool) -> &Vec { if compute { &self.compute @@ -2959,6 +3306,19 @@ impl State { }, None => None, }; + if kind == MESH + && let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) + && p.mesh_emu.is_some() + { + return self.execute_indirect_mesh_emulated( + list, + p, + (stride, max), + (&args, arguments, len), + counter.as_ref().map(|(s, at)| (s, *at)), + &why, + ); + } let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) .then(|| host_signature(kind, stride)) .flatten() diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 244a76cc..96074b82 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2549,7 +2549,7 @@ static PLACED_RAW: std::sync::Mutex static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// See [`PLACED_TWINS`]. -#[cfg(windows)] +#[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn placed_filler_twins() -> u64 { PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) } diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 807af7fa..e32a873f 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -125,7 +125,7 @@ impl Result + Send + Sync> Converter for Tra } fn convert(&self, input: &[u8]) -> anyhow::Result> { self.ran.store(true, Ordering::Relaxed); - let shader = (self.translate)(&input[33..]).map_err(anyhow::Error::msg)?; + let shader = (self.translate)(&input[BUILD_LEN + 1..]).map_err(anyhow::Error::msg)?; Ok(encode(&shader)) } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index da0a2683..eb151300 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2672,7 +2672,7 @@ impl Shadow { } OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; - if n % 16384 == 0 { + if n.is_multiple_of(16384) { tracing::info!( "what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way", OWN_WRITES[1].load(Ordering::Relaxed) >> 20, From 57ccee74993cc2295aee6551c38eb9fa446c3261 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:38:30 +0000 Subject: [PATCH 12/16] shader: lower tests in their own include (asset policy: lower.rs over the 512 KiB cap) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-shader/src/emit/lower.rs | 614 +----------------- crates/victory-shader/src/emit/lower/tests.rs | 613 +++++++++++++++++ 2 files changed, 614 insertions(+), 613 deletions(-) create mode 100644 crates/victory-shader/src/emit/lower/tests.rs diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index fa91e7b8..2e8b418c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -11880,619 +11880,7 @@ fn interp_mode(kind: Barycentric) -> Option { include!("lower/mesh_emulation.rs"); #[cfg(test)] -mod tests { - use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - const S_ENDPGM: u32 = 0xBF81_0000; - - #[test] - fn packed_pixel_inputs_find_their_second_row() { - use super::super::container::SigElement; - use super::half_input_partners; - use crate::native::{PsInput, Usage}; - let entry = |row, row2, pack2| PsInput { - usage: Usage::Generic, - row, - mask: 0xF, - attr: row, - flat: false, - fp16: true, - pack2, - row2, - }; - let element = |row| SigElement { - name: "TEXCOORD".into(), - index: row, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col: 0, - cols: 4, - usage: 0, - half: true, - }; - // Rows 0 and 3 pack and leave their second row out; 5 names its - // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. - let io = StageIo::Ps { - inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }; - let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); - let p = half_input_partners(&io, &sig); - assert_eq!(p.get(&0), Some(&1)); - assert_eq!(p.get(&3), Some(&4)); - assert_eq!(p.get(&5), None); - } - - /// The packed pedestrian layouts of the title: an element - /// behind another one in its register follows in the first parameter - /// with a dword left, and is not a half of its register's row. - #[test] - fn packed_elements_behind_another_take_the_first_free_dword() { - use super::super::container::SigElement; - use super::packed_half; - let element = |index, row, col, cols| SigElement { - name: "TEXCOORD".into(), - index, - kind: 0, - comp: 9, - interp: 2, - row: Some(row), - col, - cols, - usage: 0, - half: true, - }; - // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel - // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 - // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. - let sig = vec![ - element(1, 2, 0, 4), - element(2, 3, 0, 4), - element(4, 4, 0, 3), - element(6, 4, 3, 1), - element(3, 5, 0, 4), - element(5, 6, 0, 4), - element(7, 7, 0, 2), - element(9, 9, 0, 3), - element(11, 10, 0, 3), - element(15, 12, 0, 4), - ]; - let packs = [ - (2, Some(3)), - (4, Some(5)), - (6, Some(7)), - (9, Some(10)), - (12, None), - ]; - let at = |a, h| packed_half(&sig, &packs, a, h); - // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. - assert_eq!(at(4, 2), Some((4, 2))); - assert_eq!(at(4, 3), None); - assert_eq!(at(4, 4), Some((5, 0))); - assert_eq!(at(4, 7), Some((5, 3))); - // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. - assert_eq!(at(6, 3), Some((6, 3))); - assert_eq!(at(6, 5), Some((7, 1))); - assert_eq!(at(6, 6), Some((4, 3))); - assert_eq!(at(6, 7), None); - // Parameters without such an element are as before. - assert_eq!(at(9, 3), None); - assert_eq!(at(9, 4), Some((10, 0))); - assert_eq!(at(12, 3), Some((12, 3))); - assert_eq!(at(12, 4), None); - // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at - // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, - // TEXCOORD7. - let sig = vec![ - element(0, 1, 0, 2), - element(7, 1, 2, 2), - element(1, 2, 0, 4), - element(2, 3, 0, 4), - element(4, 4, 0, 3), - ]; - let packs = [(3, Some(4)), (1, Some(2))]; - let at = |a, h| packed_half(&sig, &packs, a, h); - assert_eq!(at(1, 1), Some((1, 1))); - assert_eq!(at(1, 2), Some((2, 0))); - assert_eq!(at(1, 5), Some((2, 3))); - assert_eq!(at(1, 6), Some((1, 2))); - assert_eq!(at(1, 7), Some((1, 3))); - assert_eq!(at(3, 6), Some((4, 2))); - assert_eq!(at(3, 7), None); - // A row no element holds gives nothing, as before. - assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); - } - - /// Whether a synthetic compute program translates with these input registers. - fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - emulate_mesh: false, - }) - .map(|_| ()) - } - - /// Lowers a compute program with the root parameters `layout` (in user - /// SGPRs from s0 on) and the used resources `used`. - fn lower_with( - words: &[u32], - layout: Vec, - used: Vec, - ) -> Result { - lower_wave(words, layout, used, false) - } - - /// [`lower_with`] in wave64 if `wave64`. - fn lower_wave( - words: &[u32], - layout: Vec, - used: Vec, - wave64: bool, - ) -> Result { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 256, - layout, - used, - io: StageIo::Cs(ComputeIo { - // The layout's user SGPRs (at least two), 512 bytes of LDS. - rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, wave64, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - emulate_mesh: false, - }) - } - - /// Root parameter `slot` in user SGPRs from `user_data` on. - fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { - RootParam { - root, - table_offset_dwords: 0, - sgprs: if root == RootType::Descriptor { 2 } else { 1 }, - base_register: 0, - user_data, - slot, - } - } - - #[test] - fn buffer_cache_invalidations_lower_as_no_ops() { - // MUBUF opcode 0x071/0x072 with no data operand: the title asks the - // host to invalidate its cached view of a buffer. - assert!( - lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), - "buffer_gl0_inv" - ); - assert!( - lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), - "buffer_gl1_inv" - ); - } - - #[test] - fn a_scalar_carry_chain_reaches_the_select() { - // The high dword of a 64-bit add or subtract, then a select on the - // carry (borrow) the high half leaves in SCC, and a branch on it - // (only code with an effect needs its operands). - let add = [ - 0xBE80_03C1, // s_mov_b32 s0, -1 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8000_8100, // s_add_u32 s0, s0, 1 - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - let sub = [ - 0xBE80_0380, // s_mov_b32 s0, 0 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8080_8100, // s_sub_u32 s0, s0, 1 - 0x8281_8001, // s_subb_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - - for words in [add, sub] { - lowers(&words, 0).unwrap(); - } - } - - fn perm_features(selector: u32) -> u64 { - // Synthetic compute shader: - // v0 is the thread ID and can supply a dynamic selector. - // Store the result in LDS to keep the permutation live. - let words = [ - 0x7E02_02FFu32, - 0x817F_34AB, - 0x7E04_02FF, - 0xFE01_56CD, - 0xD744_0003, - 257 | (258 << 9) | (selector << 18), - 0x3408_0082, - 0xD834_0000, - 0x0000_0304, - S_ENDPGM, - ]; - - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [64, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, false, 256).unwrap(); - - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32") - ); - - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - - let io = io::raise(&p, &native).unwrap(); - - let emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - emulate_mesh: false, - }) - .unwrap(); - - let container = crate::Container::parse(&emitted.dxil).unwrap(); - - let features = container.part(crate::FourCC::SFI0).unwrap(); - - u64::from_le_bytes(features.data.try_into().unwrap()) - } - - #[test] - fn perm_constant_selector_needs_no_int64() { - assert_eq!(perm_features(128) & 0x8000, 0); - } - - #[test] - fn perm_dynamic_selector_needs_no_int64() { - assert_eq!( - perm_features(256) & 0x8000, - 0, - "dynamic v_perm_b32 must not require INT64" - ); - } - - #[test] - fn a_descriptor_selected_by_scc_picks_its_heap_index() { - // Two buffer descriptors loaded from the table at s0, one picked by - // a root constant (s1) with s_cselect_b64 per half, and loaded - // through by index and stored to LDS so the load is needed. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] - 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] - 0xE030_2000, - 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - // Both are structured buffers of dwords in the table's range. - let used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, layout(), used()).unwrap(); - } - - /// Tables of 2D textures at s0 and samplers at s1. - fn texture_tables() -> (Vec, Vec) { - let range = |kind, user_data, slot| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, - user_data, - slot, - }; - ( - vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], - vec![ - range(ResourceType::Srv, 0, 0), - range(ResourceType::Sampler, 1, 1), - ], - ) - } - - #[test] - fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { - use crate::resource::tests::{ - WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, - }; - for (words, wave64) in [ - (WATERFALL_FETCHED_WAVE32, false), - (WATERFALL_FETCHED_WAVE64, true), - (WATERFALL_PICKED_WAVE32, false), - ] { - let (layout, used) = texture_tables(); - let l = lower_wave(words, layout, used, wave64).unwrap(); - // The loop's reads of the first lane became each lane's own - // dwords: no wave operation is left. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. - pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { - let (layout, mut used) = texture_tables(); - used.push(UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 16, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }); - (layout, used) - } - - #[test] - fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { - use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; - for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { - let (layout, used) = texture_and_uav_tables(); - let l = lower_wave(words, layout, used, false).unwrap(); - // One image handle, from the join's per-lane heap index. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - #[test] - fn scalar_bit_tests_lower() { - // Each tests one bit of a constant into SCC and branches on it (only - // code with an effect needs its operands). - let tail = [ - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let bit_tests: [&[u32]; 4] = [ - &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 - &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 - ], - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 - ], - ]; - for head in bit_tests { - let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words, 0).unwrap(); - } - } - - #[test] - #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] - fn a_missing_value_stays_missing_through_two_live_joins() { - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // skip the first overwrite - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) - 0xBF85_0001, // skip the second overwrite - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // use the result to branch - 0xBE83_0380, - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - // Compare to a direct read so future timestamp support works in both cases. - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[8..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead - lowers(&words, group_ids_xy).expect("dead timestamp"); - } - - #[test] - fn buffer_formats_by_number() { - // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(78), None); - } - - #[test] - fn packed_buffer_formats_by_number() { - // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, - // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT - // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. - assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); - assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); - assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); - assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); - assert_eq!( - buffer_format(44), - Some((&[2, 10, 10, 10][..], Numeric::Unorm)) - ); - assert_eq!( - buffer_format(45), - Some((&[2, 10, 10, 10][..], Numeric::Snorm)) - ); - assert_eq!( - buffer_format(46), - Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) - ); - assert_eq!( - buffer_format(47), - Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) - ); - assert_eq!( - buffer_format(48), - Some((&[2, 10, 10, 10][..], Numeric::Uint)) - ); - assert_eq!( - buffer_format(49), - Some((&[2, 10, 10, 10][..], Numeric::Sint)) - ); - } - - /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as - /// `legacyF16ToF32` widens it. - fn half(h: u32) -> f32 { - let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); - let v = match e { - 0 => m as f32 * 2f32.powi(-24), - 31 if m == 0 => f32::INFINITY, - 31 => f32::NAN, - _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), - }; - if s == 1 { -v } else { v } - } - - #[test] - fn small_floats_widen_as_halves() { - // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a - // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. - let f11 = |x: u32| half(x << half_shift(11)); - let f10 = |x: u32| half(x << half_shift(10)); - assert_eq!(f11(0), 0.0); - assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal - assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal - assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal - assert_eq!(f11(0x3C0), 1.0); - assert_eq!(f11(0x3E0), 1.5); - assert_eq!(f11(0x7BF), 65024.0); // largest - assert_eq!(f11(0x7C0), f32::INFINITY); - assert!(f11(0x7C1).is_nan()); - assert_eq!(f10(0x001), 2f32.powi(-19)); - assert_eq!(f10(0x020), 2f32.powi(-14)); - assert_eq!(f10(0x1E0), 1.0); - assert_eq!(f10(0x3DF), 64512.0); - assert_eq!(f10(0x3E0), f32::INFINITY); - assert!(f10(0x3FF).is_nan()); - // A 16-bit float is a half already, sign included. - assert_eq!(half(0xBC00 << half_shift(16)), -1.0); - } -} +include!("lower/tests.rs"); #[cfg(test)] diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs new file mode 100644 index 00000000..0ff20571 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/tests.rs @@ -0,0 +1,613 @@ +mod tests { + use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + + #[test] + fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); + } + + /// The packed pedestrian layouts of the title: an element + /// behind another one in its register follows in the first parameter + /// with a dword left, and is not a half of its register's row. + #[test] + fn packed_elements_behind_another_take_the_first_free_dword() { + use super::super::container::SigElement; + use super::packed_half; + let element = |index, row, col, cols| SigElement { + name: "TEXCOORD".into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: true, + }; + // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel + // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 + // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. + let sig = vec![ + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + element(6, 4, 3, 1), + element(3, 5, 0, 4), + element(5, 6, 0, 4), + element(7, 7, 0, 2), + element(9, 9, 0, 3), + element(11, 10, 0, 3), + element(15, 12, 0, 4), + ]; + let packs = [ + (2, Some(3)), + (4, Some(5)), + (6, Some(7)), + (9, Some(10)), + (12, None), + ]; + let at = |a, h| packed_half(&sig, &packs, a, h); + // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. + assert_eq!(at(4, 2), Some((4, 2))); + assert_eq!(at(4, 3), None); + assert_eq!(at(4, 4), Some((5, 0))); + assert_eq!(at(4, 7), Some((5, 3))); + // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. + assert_eq!(at(6, 3), Some((6, 3))); + assert_eq!(at(6, 5), Some((7, 1))); + assert_eq!(at(6, 6), Some((4, 3))); + assert_eq!(at(6, 7), None); + // Parameters without such an element are as before. + assert_eq!(at(9, 3), None); + assert_eq!(at(9, 4), Some((10, 0))); + assert_eq!(at(12, 3), Some((12, 3))); + assert_eq!(at(12, 4), None); + // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at + // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, + // TEXCOORD7. + let sig = vec![ + element(0, 1, 0, 2), + element(7, 1, 2, 2), + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + ]; + let packs = [(3, Some(4)), (1, Some(2))]; + let at = |a, h| packed_half(&sig, &packs, a, h); + assert_eq!(at(1, 1), Some((1, 1))); + assert_eq!(at(1, 2), Some((2, 0))); + assert_eq!(at(1, 5), Some((2, 3))); + assert_eq!(at(1, 6), Some((1, 2))); + assert_eq!(at(1, 7), Some((1, 3))); + assert_eq!(at(3, 6), Some((4, 2))); + assert_eq!(at(3, 7), None); + // A row no element holds gives nothing, as before. + assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); + } + + /// Whether a synthetic compute program translates with these input registers. + fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + emulate_mesh: false, + }) + .map(|_| ()) + } + + /// Lowers a compute program with the root parameters `layout` (in user + /// SGPRs from s0 on) and the used resources `used`. + fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, + ) -> Result { + lower_wave(words, layout, used, false) + } + + /// [`lower_with`] in wave64 if `wave64`. + fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, + ) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + emulate_mesh: false, + }) + } + + /// Root parameter `slot` in user SGPRs from `user_data` on. + fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } + } + + #[test] + fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!( + lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), + "buffer_gl0_inv" + ); + assert!( + lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), + "buffer_gl1_inv" + ); + } + + #[test] + fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } + } + + fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); + + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + emulate_mesh: false, + }) + .unwrap(); + + let container = crate::Container::parse(&emitted.dxil).unwrap(); + + let features = container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) + } + + #[test] + fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); + } + + #[test] + fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); + } + + #[test] + fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); + } + + /// Tables of 2D textures at s0 and samplers at s1. + fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) + } + + #[test] + fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. + pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) + } + + #[test] + fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + #[test] + fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } + } + + #[test] + #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] + fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + + #[test] + fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); + } + + #[test] + fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); + } + + /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as + /// `legacyF16ToF32` widens it. + fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } + } + + #[test] + fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); + } +} From 8398a5fefe8c22b3652f537cbe44c85307710a94 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:39:27 +0000 Subject: [PATCH 13/16] gpu: strip trailing whitespace in draw.rs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/draw.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 33b98f50..461ba95f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2647,11 +2647,11 @@ impl State { } } - - - + + + fn dispatch_mesh_emulated(&mut self, list: &HostList, p: &HostPipeline, x: u32) -> bool { #[cfg(feature = "diagnostics")] @@ -3606,7 +3606,7 @@ impl State { } true } - + } /// The host command signature for one argument of `kind` with records From af9dc5e3d9559b3e27d6e747d4d39f2d98b65439 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:46:44 +0000 Subject: [PATCH 14/16] gpu: drop unused CacheKey import in shader cache tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/shader_cache.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index e32a873f..9e062210 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -438,7 +438,6 @@ fn decode(bytes: &[u8]) -> Option { #[cfg(test)] mod tests { use super::*; - use victory_pipeline::CacheKey; fn shader() -> HostShader { HostShader { From ff68f0323888f84e73550e21bae88707efd5f06e Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:47:41 +0000 Subject: [PATCH 15/16] gpu: satisfy clippy spacing around mesh pipeline docs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/pipeline/host.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 18dd46dd..927c399f 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -477,8 +477,6 @@ fn refuse(reason: &'static str, shaders: &[Arc]) -> Option } #[allow(clippy::vec_box)] // boxed ranges keep stable addresses until the root signature is serialized - - /// A mesh pipeline emulated as compute plus a generated vertex shader. /// The compute step writes the mesh records into the shared emulation /// buffer; the graphics step unpacks them with no input assembler data. @@ -1158,8 +1156,7 @@ impl HostPipeline { /// A mesh pipeline emulated as compute plus a generated vertex shader. /// The compute step writes the mesh records into the shared emulation /// buffer; the graphics step unpacks them with no input assembler data. - - +/// /// A stream subobject: its type, then its description, pointer-aligned. #[repr(C, align(8))] struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); From 7b84311c9eb8c8bfc693f323fefa9fae76ddbbc7 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Wed, 25 Nov 2026 14:50:33 +0000 Subject: [PATCH 16/16] gpu: delink private page_writes from public watch documentation Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/victory-gpu/src/watch.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 057f938f..12d1998c 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -907,7 +907,7 @@ pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::syn /// Upstream's c75fdba does the same for its trackers (its `Writing` marks /// the pages once more when dropped; page destinations are reported at /// each address showing them). Here it is counted always and acted on as -/// [`page_writes`] says. Called without the runtime's page-table lock; +/// `page_writes` says. Called without the runtime's page-table lock; /// takes the guards' lock, then, alone, the lock of the ranges kept for /// the texture pass. pub fn title_memory_written(at: usize, len: usize, pages: bool) {