diff --git a/README.md b/README.md index 364ad8c6..ed1955ec 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,281 @@ +# VIctory fork (work in progress) + +A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), a +compatibility layer that runs an Xbox Series title natively on Windows from +files the user supplies. This fork follows upstream +`main` and adds fixes aimed at one goal: getting the game's world to render +correctly and playably on one particular PC. + +**This repository contains no game files, code or assets.** You need your own +copy of the game. It is not affiliated with or endorsed by the game's +developer or publisher. + +## Credits + +- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its + contributors is the base of everything here: the loader, the runtime + services, the Direct3D 12 back end and the shader recompiler. Licensed + GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below + the single commit that carries this fork's changes. +- **[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) + +**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.** +Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, +32 GB RAM. The Series X profile is used throughout. + +| Stage | State in this fork | +|-------|--------------------| +| Boot, menus, start screen | works, 30 fps (as upstream) | +| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots | +| Saves | the game autosaves a checkpoint and loads it again | +| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | +| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | +| 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) + +**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). +- 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. +- 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: 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): + - `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. +- 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. 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 + 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). + - `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. 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). + - 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. + 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). + +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: +- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed. +- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed. +- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer. +- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed. +- Gathers at a named mip level (with and without an offset) read level 0; fixed. +- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. +- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. +- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md). + +Speed and memory: +- Waits for memory values, write-watch queries and page queries no longer walk page tables per call. +- Large title buffers get a copy in card memory, with shader writes found by hashing on the card. +- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). +- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. +- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. + +- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off). + +Most of the newer speed changes sit behind environment switches that are off +by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, +`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). +Each is described in a comment where it is read. + +### Known problems + +- Everything in shadow is black (see above). +- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. +- Around 24 GB of memory is in use during play. +- A few style lints are switched off for this fork in the workspace `Cargo.toml` until the newer code is tidied. +- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does. + +Everything below this line is upstream VIctory's own README, unchanged; its +status section describes upstream, not this fork. + +--- + # VIctory Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files 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 7087c111..bb0835d6 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -166,6 +166,87 @@ fn mesh_mode(host: Option<&Host>) -> emit::MeshMode { } } +/// `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 d8632edc..6a09c5f4 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -620,17 +620,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. @@ -643,30 +633,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; @@ -692,6 +671,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); } @@ -714,12 +698,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; @@ -727,16 +711,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); } } } @@ -744,16 +734,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; + } } } @@ -1025,6 +1046,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/Cargo.toml b/crates/victory-gpu/Cargo.toml index 867727d8..b369ec18 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 15221434..b15aee6d 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 7f66bd0d..6e0768ed 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]; @@ -743,6 +749,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 \ @@ -962,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))); @@ -975,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) { @@ -1121,6 +1152,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. @@ -1242,6 +1279,14 @@ 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); 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} \ 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 84850149..c96ff17e 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 { @@ -121,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::Mutex> = std::sync::Mutex::new(Vec::new()); +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 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))?; @@ -155,11 +170,147 @@ 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 _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) }; + 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); + // 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 + // 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, {:.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 + ); +} + +/// 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)] +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)] 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() @@ -172,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); } } @@ -353,7 +504,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 +635,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 +683,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 +695,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 +721,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 +872,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 +897,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, } } @@ -946,11 +1121,15 @@ 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 { 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))] @@ -1003,6 +1182,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(); @@ -1029,6 +1236,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(); @@ -1104,8 +1363,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..7970fc5f 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 @@ -85,7 +89,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 +173,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 +292,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 +335,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 +530,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 +610,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) { @@ -759,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), @@ -770,7 +963,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 +1183,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 +1211,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 +1231,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 +1309,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 +1560,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); @@ -1432,6 +1794,130 @@ 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; + } + // 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". (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() { + 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 + } + + /// [`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 @@ -1517,6 +2003,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). @@ -1684,6 +2180,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 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). +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 @@ -1783,6 +2396,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 }; @@ -1854,6 +2483,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 { @@ -1869,7 +2521,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)) @@ -2104,6 +2756,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 +2887,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 +3132,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 +3272,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 +3397,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] @@ -2792,3 +3587,58 @@ mod tests { assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } } + +#[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; + + /// 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 25c92bc2..461ba95f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -15,9 +15,7 @@ use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; use windows::Win32::Foundation::RECT; -use windows::Win32::Graphics::Direct3D::{ - D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, -}; +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; @@ -167,7 +165,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. @@ -191,9 +191,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. @@ -380,6 +384,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. @@ -402,6 +410,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). @@ -913,6 +935,8 @@ impl State { 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 { @@ -921,11 +945,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 { @@ -948,14 +967,9 @@ 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, - ) + self.bind_parts(list, p, &p.root, &p.pso, &p.name, &p.stages, compute, compute) } - /// [`State::bind`], split so mesh emulation can bind its compute step - /// against the title's graphics root arguments while writing host - /// compute root parameters. #[allow(clippy::too_many_arguments)] fn bind_parts( &mut self, @@ -1035,15 +1049,9 @@ impl State { let writes = (t.stores || !write_skip()) && !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 memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { 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" - ); + once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); return false; }; Some(ready) @@ -1112,8 +1120,7 @@ impl State { continue; } let tabled = srv && crate::pipeline::host::bounded_root_srvs(); - let Some(&Root::View(address)) = - self.roots_ref(title_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. @@ -1463,6 +1470,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 { @@ -1551,7 +1559,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); @@ -1659,7 +1669,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; } @@ -1757,15 +1770,33 @@ 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"); } 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) { @@ -1935,7 +1966,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; @@ -2015,6 +2054,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 { @@ -2155,6 +2199,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); @@ -2556,7 +2606,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_key(|a| std::cmp::Reverse(a.1)); + rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); let scissors: Vec = rects .iter() .take(5) @@ -2597,6 +2647,12 @@ impl State { } } + + + + + + 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) { @@ -2634,7 +2690,6 @@ impl State { 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. - list.flush_barriers(); unsafe { list.list.Dispatch(chunk, 1, 1); list.list.ResourceBarrier(&[transition( @@ -2665,7 +2720,6 @@ impl State { return false; }; self.mesh_scissor(list, true); - list.flush_barriers(); unsafe { list.list.DrawInstanced(vertices, 1, 0, 0); list.list.ResourceBarrier(&[transition( @@ -2682,6 +2736,171 @@ impl State { 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 @@ -3137,6 +3356,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; @@ -3240,13 +3466,26 @@ impl State { .window .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)); + .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, 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 @@ -3328,7 +3567,6 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &bounded); why("prepare failed"); return false; } @@ -3358,7 +3596,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 { @@ -3366,170 +3606,7 @@ impl State { } 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 - } } /// The host command signature for one argument of `kind` with records @@ -3770,13 +3847,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/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..0d90bae5 --- /dev/null +++ b/crates/victory-gpu/src/framelog.rs @@ -0,0 +1,647 @@ +//! 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::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 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!( + "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) +} + +/// 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(); + *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 843c53ea..3c7d6104 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(); @@ -344,6 +351,38 @@ static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [ 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. @@ -390,7 +429,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. @@ -557,6 +596,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. @@ -771,7 +811,7 @@ fn hardware_adapter() -> Option<(IDXGIAdapter, u64, String)> { /// 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))?; @@ -887,13 +927,23 @@ 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 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")] @@ -1366,6 +1416,16 @@ 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]; +/// 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 /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). @@ -1586,6 +1646,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 @@ -1642,6 +1730,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 @@ -1654,9 +1883,34 @@ void main(uint3 id : SV_DispatchThreadID) { /// 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 @@ -1700,6 +1954,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. @@ -1751,8 +2014,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 { @@ -1957,6 +2226,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 @@ -1979,9 +2328,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 @@ -2218,16 +2657,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); } @@ -2249,6 +2713,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 @@ -2276,10 +3101,14 @@ 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; - return spans.iter().any(|(shadow, from, to)| { - shadow.merge_under_writes(*from, *to - *from, &mut runs_left) + // (`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() @@ -2388,6 +3217,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"); @@ -2484,7 +3314,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 @@ -2510,6 +3340,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)")); @@ -2611,7 +3442,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); @@ -2624,6 +3455,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; \ @@ -2671,17 +3505,33 @@ 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, 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); @@ -2817,7 +3667,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(); @@ -2908,7 +3759,7 @@ fn hand_back(back: &[Declared]) { ); 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); } @@ -2940,7 +3791,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); } @@ -3009,7 +3860,7 @@ impl Host { }) } - /// Whether the host runs native mesh shaders at shader model 6.6. + /// Whether the host runs mesh shaders itself at shader model 6.6. pub(crate) fn mesh_shaders(&self) -> bool { self.mesh_support() == MeshSupport::Native } @@ -3117,8 +3968,11 @@ impl Host { prelude, pipelines: Mutex::default(), budget: OnceLock::new(), + card_budget: OnceLock::new(), 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")] @@ -3162,8 +4016,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(); @@ -3244,10 +4098,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 @@ -3258,7 +4185,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; @@ -3293,7 +4233,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()); @@ -3316,6 +4268,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")); @@ -3328,20 +4327,20 @@ 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 { 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, - ); - crate::shadow::CARD_STATS[0] - .fetch_add((b - a) as u64, Ordering::Relaxed); + 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); @@ -3395,6 +4394,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(()) @@ -3405,12 +4405,16 @@ impl Host { } used.push((false, sync)); } + numbered(); drop(order); let mut plan = CardPlan { ranges: Vec::new(), 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. @@ -3456,6 +4460,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, @@ -3493,6 +4498,41 @@ 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; + } + crate::cardmeter::end(list, timed); list.Close()?; list.cast() })() @@ -3565,7 +4605,44 @@ 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. - fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + /// + /// 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. + /// `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 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)) @@ -3578,8 +4655,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| { @@ -3594,7 +4671,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 { @@ -3611,11 +4697,33 @@ impl Host { } } } + BESIDE_STATS[0].fetch_add(again, Ordering::Relaxed); if pieces.is_empty() { - // 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 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.1.sent_as).max() { + crate::shadow::relay_fetched(last); + } + return; + } + 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() { + INFLIGHT_STATS[3].fetch_add(1, Ordering::Relaxed); + } if fetch.is_none() { *fetch = self.make_relay_fetch(); } @@ -3637,6 +4745,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 { @@ -3667,6 +4801,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); { @@ -3686,23 +4831,176 @@ impl Host { shadow.walls_merged(gpu.len(), merged); 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); + 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`). + let landed = plans.iter().map(|p| p.1.sent_as).max(); + crate::shadow::relay_fetched(fallback_fetched_mark(inflight_fetch(), after, landed)); } - /// [`relay`], on the thread that lands flights: `items` are the first - /// things of the line, flights the card has run and what follows them. - /// What their shaders wrote goes into title memory (copies in the - /// card's memory first, then the others, each byte once whichever - /// flights declared it); then every flight's ranges are done with; - /// then, in the line's order, each flight's read-backs, its - /// bottom-of-pipe writes and the fence signals behind it. Title memory - /// is complete before the title is told anything. - fn relay_land(&self, items: Vec, fetch: &mut Option) { - let landing = std::time::Instant::now(); - { - let flights: Vec<&Flight> = items + /// [`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, 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. + 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 + /// things of the line, flights the card has run and what follows them. + /// What their shaders wrote goes into title memory (copies in the + /// card's memory first, then the others, each byte once whichever + /// flights declared it); then every flight's ranges are done with; + /// then, in the line's order, each flight's read-backs, its + /// bottom-of-pipe writes and the fence signals behind it. Title memory + /// is complete before the title is told anything. + fn relay_land(&self, items: Vec, fetch: &mut Option) { + let landing = std::time::Instant::now(); + { + let flights: Vec<&Flight> = items .iter() .filter_map(|l| match l { Late::Run(flight) => Some(flight), @@ -3721,8 +5019,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 { @@ -3746,7 +5047,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); } @@ -3777,6 +5078,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(); @@ -3867,6 +5169,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 { @@ -3962,7 +5282,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); @@ -3973,6 +5293,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); } @@ -4163,7 +5486,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") @@ -4210,7 +5533,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; @@ -4265,6 +5588,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()); @@ -4284,6 +5609,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 @@ -4385,7 +5713,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)); } @@ -4404,14 +5732,8 @@ 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, - ); + let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); + submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); submitting(0, 0); #[cfg(feature = "diagnostics")] crate::copystat::submission_ends(lock); @@ -4489,8 +5811,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 @@ -4561,7 +5883,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. @@ -4692,6 +6014,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 { @@ -4864,6 +6248,12 @@ impl HostList { } self.flush_barriers(); 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(); + 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); @@ -4916,6 +6306,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, @@ -5494,6 +6886,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; @@ -5501,7 +6894,8 @@ 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()); @@ -5511,9 +6905,84 @@ impl HostList { 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 @@ -5538,11 +7007,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::() { @@ -5589,7 +7109,9 @@ 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); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); @@ -5600,6 +7122,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 @@ -5654,8 +7177,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); } } } @@ -5677,6 +7200,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. @@ -5693,6 +7240,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, } @@ -5701,6 +7253,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]; @@ -5725,6 +7290,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. @@ -5734,8 +7322,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 @@ -5749,6 +7337,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) { @@ -5765,7 +7378,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 @@ -5773,6 +7386,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(..) @@ -5782,13 +7399,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 { @@ -5839,7 +7456,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, @@ -5925,7 +7544,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 @@ -6010,15 +7631,19 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us } impl Host { - /// A default-heap GPU buffer, starting in `UNORDERED_ACCESS` when its - /// flags allow unordered access. - pub(crate) fn default_buffer( - &self, - size: u64, - flags: D3D12_RESOURCE_FLAGS, - ) -> Option { + /// 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. + pub(crate) fn read_back_buffer(&self, size: u64) -> Option { let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, + Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -6032,22 +7657,16 @@ impl Host { 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. + // SAFETY: plain creation of a read-back buffer. let made = unsafe { self.device.CreateCommittedResource( &heap, D3D12_HEAP_FLAG_NONE, &desc, - state, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buffer, ) @@ -6055,20 +7674,21 @@ impl Host { match made { Ok(()) => buffer, Err(e) => { - tracing::warn!(error = %e, size, "no default buffer"); + tracing::warn!(error = %e, size, "no read-back buffer"); None } } } -} -impl Host { - /// 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. - pub(crate) fn read_back_buffer(&self, size: u64) -> Option { + /// 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_READBACK, + Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -6082,16 +7702,22 @@ impl Host { 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 creation of a read-back buffer. + // SAFETY: plain default-heap buffer allocation with valid descriptions. let made = unsafe { self.device.CreateCommittedResource( &heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COPY_DEST, + state, None, &mut buffer, ) @@ -6099,7 +7725,7 @@ impl Host { match made { Ok(()) => buffer, Err(e) => { - tracing::warn!(error = %e, size, "no read-back buffer"); + tracing::warn!(error = %e, size, "no default buffer"); None } } @@ -6281,8 +7907,36 @@ 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" ); + // (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!( + "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); 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); @@ -6356,6 +8010,17 @@ 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] = [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); @@ -6379,6 +8044,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 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" }, + 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", @@ -6520,6 +8198,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 { @@ -7313,3 +8998,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 42ad4388..ed784819 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,33 +56,68 @@ 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; + // 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; + } draw_counts = uint2(count, instances); - } else if (kind == 2) { + } 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) { @@ -81,7 +125,7 @@ void main(uint3 id : SV_DispatchThreadID) { } 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 @@ -90,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); @@ -293,13 +376,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, @@ -372,9 +461,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), @@ -383,7 +474,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 @@ -403,28 +494,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)>, @@ -478,7 +582,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")] @@ -489,11 +595,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(), @@ -522,21 +624,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 } pub(crate) fn uav_barrier() -> D3D12_RESOURCE_BARRIER { @@ -968,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); @@ -1099,6 +1401,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() { @@ -1212,14 +1615,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 { @@ -1235,15 +1639,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 @@ -1251,20 +1654,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 { @@ -1280,7 +1686,6 @@ void main() { COUNT_OFFSET_2 as u64, ); } - done_on(&warp.list, &dst_buf); warp.submit_and_wait(); @@ -1377,27 +1782,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. @@ -1446,9 +1846,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 @@ -1467,31 +1869,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(); @@ -1517,7 +1915,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"); @@ -1531,13 +1930,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; }; @@ -1553,47 +1955,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 @@ -2194,3 +3032,4 @@ void work() { 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/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/inplace.rs b/crates/victory-gpu/src/inplace.rs index 25461dfa..6ecf22e6 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,201 @@ 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 +} + +/// 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)`. diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index e67425e4..ef5f0b1b 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; @@ -39,9 +45,15 @@ mod mesh_emu; pub mod object; pub mod pipeline; #[cfg(windows)] +mod plaincopy; +#[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)] @@ -52,6 +64,8 @@ pub mod shader_cache; mod memory; #[cfg(windows)] mod shadow; +#[cfg(windows)] +mod tiles; pub mod signature; #[cfg(windows)] mod texture; @@ -64,5 +78,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 f4d54565..af5fcf71 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). @@ -840,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)] { @@ -853,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) { @@ -861,10 +884,24 @@ 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); + 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); - list.flush_barriers(); - crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. @@ -957,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; @@ -985,18 +1024,37 @@ 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 // source above too). list.twin_use(dst.resource, false, true); - ensure_state(list, dst.resource, COPY_DEST); + // 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)); 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::()); @@ -1150,6 +1208,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/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 2c4540ac..5d183f2f 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() @@ -274,6 +280,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 { @@ -703,6 +790,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/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 37f5a4a4..927c399f 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -476,6 +476,244 @@ fn refuse(reason: &'static str, shaders: &[Arc]) -> Option None } +#[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. +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. @@ -511,17 +749,15 @@ impl HostPipeline { stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); stages }; - let host = host()?; - 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, - ); + 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 { @@ -920,240 +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. -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(), - }) -} - +/// /// A stream subobject: its type, then its description, pointer-aligned. #[repr(C, align(8))] struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); 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..4f3e9a41 --- /dev/null +++ b/crates/victory-gpu/src/plaincopy.rs @@ -0,0 +1,318 @@ +//! 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, 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. +#[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; + } + 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 +} + +/// With the frame line: what [`copy`] did per frame over `frames`. +pub(crate) fn line(frames: f64) { + if !on() { + return; + } + 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; 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 + ); +} + +#[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) }; + } + + /// 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() { + // 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/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 a9a40286..c6a760a3 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -53,8 +53,109 @@ 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, + /// 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()); @@ -131,7 +232,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 +408,134 @@ 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() { + crate::framelog::keep_on_fast_cores("victory-submit"); + loop { + { + let mut work = lock(&WORK.0); + while !*work { + work = WORK.1.wait(work).unwrap_or_else(|e| e.into_inner()); + } + *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)); + } +} + +#[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 +545,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 +587,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> = @@ -403,6 +629,27 @@ pub(crate) fn release_held(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) => { @@ -514,6 +761,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; } @@ -755,30 +1014,70 @@ 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() { + 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. #[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)] @@ -815,7 +1114,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/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/resource.rs b/crates/victory-gpu/src/resource.rs index f38c7cda..90979806 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,67 @@ 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 + // (`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)] +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 +1583,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 +1597,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 +1621,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 +1707,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 +1718,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 +1810,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 +1954,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 +2043,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 +2110,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 +2153,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 15cb51b3..9e062210 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, and a //! cache that cannot be written is skipped (it never fails a translation). @@ -12,7 +12,7 @@ use std::path::PathBuf; use std::sync::OnceLock; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; use victory_shader::emit::{HostShader, MeshEmu, MeshMode, MeshOutput, StaticSampler, UserData}; @@ -41,143 +41,117 @@ 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; BUILD_LEN] { - static BUILD: OnceLock<[u8; BUILD_LEN]> = 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 } - // The host wave width too: translations can differ across - // GPUs even when the executable is unchanged. - bytes.extend_from_slice(&victory_shader::emit::host_max_wave().to_le_bytes()); - // 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(), MeshMode::Native, container, translate).map(|_| ran.load(Ordering::Relaxed)) } /// The translation of a console shader container, from the cache when /// there is one. -/// The translation of a console shader container in `mesh` mode. Native and -/// emulated mesh translations use separate converter ids: the same console -/// container has two independent cache entries. pub(crate) fn host_shader(container: &[u8], mesh: MeshMode) -> Result { - let id = match mesh { - MeshMode::Native => "shader.dxil", - MeshMode::Emulate => "shader.dxil.mesh-emu", - }; 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(), id, 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. `translated` keeps what it produced, so a -/// store that cannot publish the entry costs no second translation. +/// encoded translation out. `ran` tells a miss from a hit. struct Translate { - id: &'static str, translate: F, - translated: OnceLock, + ran: AtomicBool, } impl Result + Send + Sync> Converter for Translate { fn id(&self) -> &'static str { - self.id + "shader.dxil" } fn version(&self) -> u32 { // The build fingerprint in the input does the versioning. 1 } fn convert(&self, input: &[u8]) -> anyhow::Result> { - let Some((_, container)) = input.split_at_checked(BUILD_LEN) else { - anyhow::bail!("shader cache input lacks the build fingerprint"); - }; - let shader = (self.translate)(container).map_err(anyhow::Error::msg)?; - let _ = self.translated.set(shader.clone()); + self.ran.store(true, Ordering::Relaxed); + let shader = (self.translate)(&input[BUILD_LEN + 1..]).map_err(anyhow::Error::msg)?; Ok(encode(&shader)) } } fn cached( cache: &Cache, - build: &[u8; BUILD_LEN], - id: &'static str, + 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 { - id, translate, - translated: OnceLock::new(), + ran: AtomicBool::new(false), }; for _ in 0..2 { - let path = match cache.get_or_convert(&converter, &input) { - Ok(path) => path, - // The cache never fails a translation: a store it cannot publish - // still holds the translation (a miss), and a translation that - // failed inside it fails here. - Err(e) => { - let message = format!("{e:#}"); - tracing::debug!(error = %message, "shader cache unusable"); - return match converter.translated.get() { - Some(shader) => { - MISSES.fetch_add(1, Ordering::Relaxed); - Ok(shader.clone()) - } - None => Err(message), - }; - } - }; + let path = cache + .get_or_convert(&converter, &input) + .map_err(|e| format!("{e:#}"))?; if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { - let (counter, what) = if converter.translated.get().is_some() { + let (counter, what) = if converter.ran.load(Ordering::Relaxed) { (&MISSES, "translated and cached") } else { (&HITS, "from the cache") @@ -190,15 +164,10 @@ fn cached( let _ = std::fs::remove_file(&path); } MISSES.fetch_add(1, Ordering::Relaxed); - // A translation that already happened (the store had no usable entry - // afterwards) is used as is. - if let Some(shader) = converter.translated.get() { - return Ok(shader.clone()); - } (converter.translate)(container) } -const MAGIC: &[u8; 4] = b"VSH3"; +const MAGIC: &[u8; 4] = b"VSH1"; const STAGES: [HwStage; 8] = [ HwStage::Ls, HwStage::Hs, @@ -226,7 +195,6 @@ fn root_tag(r: RootType) -> u32 { } } -/// Little-endian words and length-prefixed lists; a root type is its tag, /// then the raw value for [`RootType::Other`]. fn encode(s: &HostShader) -> Vec { let mut out = MAGIC.to_vec(); @@ -470,7 +438,6 @@ fn decode(bytes: &[u8]) -> Option { #[cfg(test)] mod tests { use super::*; - use victory_pipeline::CacheKey; fn shader() -> HostShader { HostShader { @@ -564,11 +531,11 @@ mod tests { Ok(shader()) }; assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), + cached(&cache, &build, MeshMode::Native, container, translate), Ok(shader()) ); assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), + cached(&cache, &build, MeshMode::Native, container, translate), Ok(shader()) ); assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); @@ -580,20 +547,14 @@ mod tests { Ok(mesh_emu_shader()) }; assert_eq!( - cached( - &cache, - &build, - "shader.dxil.mesh-emu", - container, - emu_translate, - ), + 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], "shader.dxil", container, translate), + cached(&cache, &[8; 32], MeshMode::Native, container, translate), Ok(shader()) ); assert_eq!(runs.load(Ordering::Relaxed), 2); @@ -603,19 +564,19 @@ mod tests { std::fs::write(e, b"VSH3 broken").unwrap(); } assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), + cached(&cache, &build, MeshMode::Native, container, translate), Ok(shader()) ); assert_eq!(runs.load(Ordering::Relaxed), 3); assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), + 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, "shader.dxil", b"other", fail).is_err()); + assert!(cached(&cache, &build, MeshMode::Native, b"other", fail).is_err()); } fn walk(dir: &std::path::Path) -> Vec { @@ -817,83 +778,34 @@ mod tests { }; let (a, b) = (b"first container".as_slice(), b"second container"); assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", a, translate), + cached(&cache, &[7; 32], MeshMode::Native, a, translate), Ok(of(a)) ); assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", b, translate), + 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], "shader.dxil", a, translate), + cached(&cache, &[7; 32], MeshMode::Native, a, translate), Ok(of(a)) ); assert_eq!( - cached(&cache, &[7; 32], "shader.dxil", b, translate), + 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], "shader.dxil", b, translate), + 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); } - #[test] - fn a_cache_that_cannot_be_written_still_translates() { - // A directory where the entry goes makes the atomic rename fail. - let dir = tempfile::tempdir().unwrap(); - let cache = Cache::open(dir.path()).unwrap(); - let build = [7; 32]; - let container = b"a console container".as_slice(); - let translate = |_: &[u8]| -> Result { Ok(shader()) }; - let converter = Translate { - id: "shader.dxil", - translate, - translated: OnceLock::new(), - }; - let input = [&build[..], container].concat(); - let path = cache.path_for(&CacheKey::new(&converter, &input)); - std::fs::create_dir_all(&path).unwrap(); - let runs = AtomicU64::new(0); - let translate = |_: &[u8]| { - runs.fetch_add(1, Ordering::Relaxed); - Ok(shader()) - }; - assert_eq!( - cached(&cache, &build, "shader.dxil", container, translate), - Ok(shader()) - ); - assert_eq!(runs.load(Ordering::Relaxed), 1, "no second translation"); - assert!(path.is_dir(), "the entry path is still unusable"); - } - - #[test] - fn the_converter_needs_the_build_fingerprint() { - let converter = Translate { - id: "shader.dxil", - translate: |c: &[u8]| -> Result { - let mut s = shader(); - s.dxil = c.to_vec(); - Ok(s) - }, - translated: OnceLock::new(), - }; - assert!(converter.convert(b"short").is_err()); - let input = [&[0u8; 32][..], b"container"].concat(); - let mut expected = shader(); - expected.dxil = b"container".to_vec(); - assert_eq!( - converter.convert(&input).ok().and_then(|b| decode(&b)), - Some(expected) - ); - } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 083e0794..96c36e83 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -162,6 +162,56 @@ 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). +/// +/// 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_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. +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_REFUSED[1].load(Ordering::Relaxed)) +} + /// The copies in the card's memory. static CARDED: Mutex>> = Mutex::new(Vec::new()); @@ -212,9 +262,32 @@ 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 hundredths = if card_room_kept_on() { 97 } else { 80 }; if let Some([budget, used, ..]) = host.video_memory() - && used + size > budget / 10 * 8 + && 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 { @@ -448,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() { @@ -576,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; @@ -598,6 +772,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 +1180,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 +1238,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 +1664,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]; @@ -1334,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. @@ -1363,7 +1816,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 +2043,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 +2511,28 @@ 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::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 + // 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,14 +2616,73 @@ 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::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.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, + 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 @@ -2221,9 +2848,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 +2903,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)); @@ -2311,7 +2932,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; } @@ -2435,7 +3056,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 +3283,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; @@ -2673,7 +3297,9 @@ 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); written = n; } @@ -2738,6 +3364,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); @@ -2748,7 +3377,12 @@ impl Shadow { if !mapped || !changed { 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); n } @@ -3175,6 +3809,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, enclosing, grid, holder, longest_tail, tail_of, window_of}; @@ -3304,6 +4014,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/texture.rs b/crates/victory-gpu/src/texture.rs index d30db273..084e791c 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -56,6 +56,75 @@ 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, + /// 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 @@ -225,6 +294,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); list.flush_barriers(); let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { @@ -333,7 +403,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 } @@ -389,6 +463,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)); + } + } } } @@ -578,6 +661,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 @@ -590,6 +699,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); list.flush_barriers(); @@ -652,11 +762,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) @@ -677,7 +983,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 } @@ -838,6 +1146,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!( @@ -855,6 +1177,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) @@ -1098,6 +1425,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)) { @@ -1140,7 +1470,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{}", @@ -1165,6 +1495,11 @@ 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), + pooled, }); 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..6d3c3d8d --- /dev/null +++ b/crates/victory-gpu/src/tiles.rs @@ -0,0 +1,1587 @@ +//! 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 + }) +} + +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(|| 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 +/// 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 + .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.NumPackedMips > 0 && packed_tiles == 0) || 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) { + 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_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 + /// 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 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); + } + 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()); + 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) { + 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. + #[cfg(test)] + pub(crate) fn give_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + 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 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 (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 first >= levels { + return; + } + 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); + } + _ => {} + } +} + +/// 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] + ); + } + + #[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 39b04964..12d1998c 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; @@ -30,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, @@ -46,10 +70,6 @@ struct Journal { /// other ahead asking is made, and `ahead` stays, until /// [`ask_once_end`]. kept: bool, - /// Under Wine: ranges the kernel answered this submission (whole - /// allocations included), so another range inside one is answered from - /// the journal instead of scanning the same allocation again. - asked_now: Vec<(usize, usize)>, } static JOURNAL: Mutex = Mutex::new(Journal { @@ -58,119 +78,9 @@ static JOURNAL: Mutex = Mutex::new(Journal { found: Vec::new(), ahead: Vec::new(), ahead_asked: 0, - asked_now: Vec::new(), kept: false, }); -/// Whether we run under Wine (its ntdll exports `wine_get_version`). -fn on_wine() -> bool { - static WINE: std::sync::LazyLock = std::sync::LazyLock::new(|| { - use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; - // SAFETY: plain lookups in ntdll, always loaded. - unsafe { - let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); - !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() - } - }); - *WINE -} - -/// A title allocation as Wine reports it, in [`PAGE`] units. -#[derive(Clone, Copy)] -struct Region { - /// The allocation base, for dropping stale entries. - base: usize, - first: usize, - last: usize, - /// A file view (xmem's physical pages): not write-watched. - mapped: bool, - /// Small enough (4 GiB at most) to be asked about whole. - whole: bool, -} - -/// The allocation holding `at`, cached by allocation base (walking an -/// allocation's regions under Wine costs one VirtualQuery each). Those -/// above 4 GiB are not asked about whole. -fn allocation(at: usize) -> Option { - use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; - let page = at / PAGE; - // Known allocations first: under Wine VirtualQuery takes the same lock - // the title's write faults do. - if let Some((_, &r)) = REGIONS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .range(..=page) - .next_back() - && page < r.last - { - return Some(r); - } - let query = |p: usize| { - // SAFETY: plain data filled in by the query. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; - (n != 0).then_some(info) - }; - let info = query(at)?; - let base = info.AllocationBase as usize; - if base == 0 { - return None; - } - // Walk the allocation's regions (Wine splits it by protection, one - // region per run of pages); a long walk stops, and the allocation is - // then only remembered as far as it went, never asked about whole. - let mut end = base; - let mut done = false; - for _ in 0..256 { - let Some(i) = query(end) else { - done = true; - break; - }; - if i.AllocationBase as usize != base { - done = true; - break; - } - end = i.BaseAddress as usize + i.RegionSize; - } - if !done { - // At least past `at`, so the next asking here is a cache hit — but - // never past what the walk verified: a neighbouring allocation - // inside an unverified range would inherit this one's `mapped`. - end = end.max((at / PAGE + 1) * PAGE); - } - if end <= at { - return None; - } - let r = Region { - base, - first: base.div_ceil(PAGE), - last: end / PAGE, - mapped: info.Type == MEM_MAPPED, - whole: done && end - base <= (4usize << 30), - }; - if r.first * PAGE > at || r.last <= r.first { - return None; - } - let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); - // An allocation that replaced older ones in its range. - regions.retain(|_, o| o.last <= r.first || o.first >= r.last); - regions.insert(r.first, r); - Some(r) -} - -/// Allocations seen by [`allocation`], by first page. Remaps (xmem's views) -/// and failed askings drop entries. -static REGIONS: Mutex> = Mutex::new(BTreeMap::new()); - -fn forget_region(base: usize) { - REGIONS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .retain(|_, r| r.base != base); -} - - /// Ranges of one submission closer than this are asked about together: /// walking the pages between them costs less than another kernel call (a /// call that resets written pages costs 30-70 microseconds whatever the @@ -202,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(); @@ -241,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] { @@ -304,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)); @@ -320,7 +256,6 @@ pub(crate) fn ask_once_end() { j.kept = false; j.ahead.clear(); } - j.asked_now.clear(); } /// We wrote title memory `[at, at + len)` while a submission's one asking @@ -328,22 +263,50 @@ pub(crate) fn ask_once_end() { /// as written after that asking, so the refreshes that follow copy them. pub(crate) fn wrote(at: usize, len: usize) { let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); - if len == 0 { + if !j.kept || len == 0 { return; } - // Journal the copy whatever the mode: a scan reused from asked_now - // predates it, and only the journal then says its pages are written - // (the kernel still would — the bits were never reset — so this - // never overstates). The scan stays reusable for the rest of the - // allocation, instead of being dropped whole for a one-page copy. - let (first, last) = (at / PAGE, at.saturating_add(len).div_ceil(PAGE)); j.asked += 1; let now = j.asked; - for page in first..last { + // 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); } } +/// 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`]. @@ -437,68 +400,36 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve .collect(), )); } - // Under Wine a range inside one the kernel already answered this - // submission (a whole allocation asked at once) is answered from the - // journal: the scan cost is per asking, not per byte. A write between - // the two keeps its dirty bit, so the next submission sees it. - if on_wine() && j.asked_now.iter().any(|&(f, l)| f <= first && last <= l) { - j.asked += 1; - return Some(( - j.asked, - j.written - .range(first..last) - .map(|(&p, &w)| (p, w)) - .collect(), - )); - } - // Under Wine: view memory cannot be watched (straight to its guards), - // and watched memory is asked about whole allocations at a time, so the - // other buffers in one are answered from the journal for the rest of - // the submission — one GetWriteWatch costs about 1 ms there whatever - // the range (contention on Wine's virtual-memory lock with the title's - // write faults), and the world's copies ask about the same big buffers - // dozens of times per submission. - let region = if on_wine() { allocation(start) } else { None }; - let mapped = region.is_some_and(|r| r.mapped); - let (kfirst, klast) = match region { - Some(r) if !r.mapped && r.whole && r.first <= first && last <= r.last => (r.first, r.last), - _ => (first, last), - }; + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); - let mut granularity = 0; - let mut ask = |j: &mut Journal, kfirst: usize, klast: usize| -> Option { - let mut count = (klast - kfirst) * PAGE / KERNEL_PAGE; - j.found.resize(count.max(j.found.len()), 0); - // SAFETY: the answer buffer holds `count` entries. - let ok = unsafe { + // 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 = known_view + || unsafe { GetWriteWatch( WRITE_WATCH_FLAG_RESET, - (kfirst * PAGE) as *const _, - (klast - kfirst) * PAGE, + (first * PAGE) as *const _, + (last - first) * PAGE, j.found.as_mut_ptr().cast(), &mut count, &mut granularity, ) - } == 0; - ok.then_some(count) - }; - let mut asked_range = (kfirst, klast); - let mut answer = if mapped { None } else { ask(j, kfirst, klast) }; - if answer.is_none() && !mapped && (kfirst, klast) != (first, last) { - // The allocation was not one watched range after all (or is gone): - // just ours, and look it up again next time. - if let Some(r) = region { - forget_region(r.base); - } - asked_range = (first, last); - answer = ask(j, first, last); - } - let mut count = answer.unwrap_or(0); - let failed = answer.is_none(); - if !failed && on_wine() && j.asked_now.len() < 4096 { - j.asked_now.push(asked_range); - } + } != 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 { @@ -506,7 +437,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve } #[cfg(feature = "diagnostics")] let guarding = std::time::Instant::now(); - let written = guard(first * PAGE, last * PAGE, mapped); + let written = guard(first * PAGE, last * PAGE); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); written? @@ -535,9 +466,64 @@ 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; +/// 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) || (view_known() && g.viewed.contains(&first)) +} + struct Guards { /// Blocks we made read-only. protected: BTreeSet, @@ -546,12 +532,39 @@ 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, + /// 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 { protected: BTreeSet::new(), clean: BTreeSet::new(), absent: BTreeSet::new(), + aliased: BTreeSet::new(), + viewed: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { @@ -561,7 +574,7 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. -fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { +fn guard(start: usize, end: usize) -> Option> { // A range whose first block the guards hold already (read-only by our // hand, or noted absent) is a view: no question to Windows. The // question walks the page tables to the end of the pages that share the @@ -570,12 +583,11 @@ fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { // of the 68 ms a frame of "guards" (run 58). // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); - let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) - && (known_mapped || { - let g = guards(); - let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) - }); + 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) || (view_known() && g.viewed.contains(&first)) + }; if !known && !is_view(start, end) { return None; } @@ -676,8 +688,80 @@ 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); + if view_known() { + g.viewed.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; @@ -694,6 +778,9 @@ fn protect(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); @@ -725,8 +812,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 @@ -750,11 +860,108 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). open(&mut guards(), at, at.saturating_add(len)); - forget_region(at); // A placed texture there changes with no descriptor written. 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 `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("slots") => 2, + Ok("all") => 7, + _ => 1, + }) +} + +/// 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. /// @@ -772,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`]). @@ -808,7 +1026,6 @@ pub fn title_memory_reading_now() -> Option { /// shows is new and read-write, so it is no longer guarded (nor known /// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { - REGIONS.lock().unwrap_or_else(|e| e.into_inner()).clear(); // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); @@ -827,6 +1044,15 @@ 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); + } + // 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 @@ -855,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) { @@ -948,7 +1175,7 @@ mod tests { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize }; assert_ne!(view, 0); - assert!(guard(view, view + 2 * BLOCK, false).is_some()); // now read-only + assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only let mut file = tempfile::tempfile().unwrap(); file.write_all(b"from the disk").unwrap(); // `ReadFile` inside: the kernel writes the view. @@ -968,7 +1195,7 @@ mod tests { let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; assert_eq!(landed, b"from the disk"); assert_eq!( - guard(view, view + 2 * BLOCK, false), + guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); // SAFETY: our view. @@ -1026,7 +1253,7 @@ mod tests { let late = start + 2 * BLOCK + 3 * KERNEL_PAGE; commit(start, BLOCK); commit(early, KERNEL_PAGE); - let refresh = || guard(start, start + SIZE, false).unwrap(); + let refresh = || guard(start, start + SIZE).unwrap(); assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]); // The last block is still entirely reserved. assert!(!refresh().contains(&(late / PAGE))); @@ -1107,15 +1334,15 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); // The range begins in the placeholder, its middle block is a view. assert!(is_view(p, p + 3 * BLOCK)); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(all)); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new()), "nothing written since"); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since"); // SAFETY: inside the mapped middle block. unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); let first = map(0); title_memory_remapped(p, BLOCK); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(0).collect())); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); // Memory of ours that is no view stays none. let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; @@ -1194,16 +1421,16 @@ mod tests { let first = map(0); let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; let all: Vec = (0..3).flat_map(pages).collect(); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); assert_eq!( - guard(p, p + 3 * BLOCK, false), + guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since" ); let second = map(1); title_memory_remapped(p + BLOCK, BLOCK); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(1).collect())); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1216,6 +1443,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..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 { @@ -517,6 +527,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(); @@ -863,8 +880,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 +1068,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 +1097,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 +1131,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 f303f933..501828ae 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-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. 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/lower.rs b/crates/victory-shader/src/emit/lower.rs index f0da5acf..2e8b418c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1106,6 +1106,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 fn host_max_wave() -> u32 { #[cfg(test)] if let Some(lanes) = TEST_HOST_WAVE.get() { @@ -1643,7 +1663,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 { @@ -2260,8 +2282,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; @@ -2295,6 +2318,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); @@ -6002,6 +6080,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 @@ -6112,6 +6202,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; @@ -6179,8 +6272,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)]); @@ -6203,6 +6298,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 { @@ -7512,12 +7668,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)?; @@ -7535,6 +7685,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. @@ -9301,7 +9457,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 { @@ -11705,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); + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 8b7458ac..e1db5764 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -110,7 +110,7 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; -pub use lower::{host_max_wave, set_host_max_wave}; +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; @@ -196,6 +196,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 { @@ -281,6 +308,13 @@ pub struct UserData { /// Translates the vertex, pixel, compute or mesh program of a console /// 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 +/// 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 { translate_with(container, MeshMode::Native) } @@ -288,6 +322,15 @@ pub fn translate(container: &[u8]) -> Result { /// 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, mesh)) + } + other => other, + } +} + +fn translate_plain(container: &[u8], mesh: MeshMode) -> 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 cf3bd0aa..1501bd19 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, @@ -201,6 +211,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