diff --git a/AGENTS.md b/AGENTS.md index 575c2d6bd1..42957cfeef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ Fork: MagiccConch/VIctory, upstream: Marvisak/VIctory. CI: windows-latest only ( - Title run (2026-11-25 ~02:17): title boots deep into init on the 5080, then 0xc0000005 null write (title-image+0x2215c35) amid a flood of "title slot past the host heap index~1179606 count=934464 for_draw=false" (also the title's own Breakpad minidump upload attempt, blocked by net HLE - benign). Root cause: the title requests 0x120000 (1179648) shader-visible slots; HostHeap::new fallback jumped from make(max(count+DYNAMIC, HEAP_VIEWS)=2M) straight to the 1M cap (PORTABLE_VIEWS, NVIDIA), leaving count=934464 and every title slot past it null. Commit 6ac8fbe (CI 45532159717 green): ordered fallbacks - try make(count+DYNAMIC) then make(count+MIN_DYNAMIC) before the PORTABLE_VIEWS cap, so the full console heap fits when the host allows ~1.245M. If the 5080 still caps (log shows host view heap capped at 1000000), real remapping is needed (upstream comment: a title that reaches them needs remapping). Breakpad line = the title's own crash reporter trying submit.backtrace.io, net-blocked, harmless. - Remap sketch (for the 2-heap fix): uniform root layout on ALL hosts - two root SRVs (heap0=title slots [0, 1000000), heap1=title slots [1000000, 1179648) + the DYNAMIC tail) with SPLIT=1000000 fixed in emit (HEAP_VIEWS clamp stays; NULL_BUFFER_VIEW lands in heap0). Heap0 exactly 1000000 slots (NVIDIA max, empirically confirmed), heap1 sized per host. Root signature changes -> pipeline library rebuilds (user re-runs pre-build). Update: emit/shader.rs, pipeline/make.rs root layout, descriptor/host.rs heap manager + GPU_RANGES. -## Upstream sync (2026-11-24/25, merge 42b5c9c) +## Upstream sync (2026-11-24/25, merge 42b5c9c; second sync 971a975 → 67e8ae1 via PR #14) - Reviewed upstream's 291 commits since 70564ae, checked upstream CI (green), merged, resolved 5 conflict files, CI 45536238395 green on windows-latest. - Key upstream fixes now in the fork: copy-back page marks via shader view writes (cd94d35) — touches `crate::memory` copy-back and `emit::HostShader::view_marks` (new `Parts::view_marks`, `Options::view_marks`, `HostShader::view_marks`; test initializers must set it); descriptor cursor range (c6c244d) + dynamic wraparound scan (c1c3281); swap-chain throttle (f096774); TDR log (42961e8, `crate::tdr::log` — called beside our adapter-by-preference in `victory-gpu/src/host.rs`); device-removed reason (13185f5); no-GPU skip for hardware-only shader checks (42363ab/ccfb029: `hardware_adapter` requires DedicatedVideoMemory > 0). @@ -129,3 +129,16 @@ Fork: MagiccConch/VIctory, upstream: Marvisak/VIctory. CI: windows-latest only ( - **#911 ported (same commit):** `tables()` now rolls back the failing stage's just-allocated ranges on `table_failed` — release(first, n), fresh_tables entry removed, self.dynamic entry dropped, made cleared. Safe because those binds were never recorded (the draw drops before its root arguments are set); later draws re-make them. Previous behavior cached them until list reset, amplifying exhaustion exactly as #911 describes. - NOT ported now: #876/#2190 (typeless views — 494-line unmerged rework; our cutscene/UI symptoms were addressed by the twin work), wave64/compute translation (#2176, large), #2189's tier ladder (our ladder already degrades gracefully with the 2^18 port). Re-check #2177/#2185/#2189/#2190 when upstream merges any — all touch descriptor/host.rs + emit/lower.rs, which PR #13 now modifies; expect rebase work then. - Run 8 expectations UPDATED by 3bf9424: capped warn now logs `kept=705085`; `host view heap capped at 1000000` count=934464. The past-cap title range widens (title slots [705,085, 1,179,648) read null) — that is #747's accepted trade (its own tested config mirrored only 672,319 title slots). Watch for "no dynamic slots" drops GONE from the log (was thousands/frame in #747's measurements). + +## Second upstream sync (971a975, PR #14, upstream 67e8ae1; 2026-11-25) + +- Scope: upstream commits 940d32f..67e8ae1 (58 commits). Key fixes: 315cea1 barriers start from the states resources are in (prelude copies from real states; indirect clamp writes clamped records into a list-owned argument buffer - addresses run-9's id=538 vertex-buffer-in-UAV class); 98c654b 16-bit depth w/ stencil is host D32_FLOAT_S8X24 (depth() = f32(u)*0x37800080 - EQUAL-tested depth now exact on AMD/any-float-depth); 4015a18 quad reads reach helpers at edges (helpers at triangle edges exist regardless of discards); 8f2a6f1 texture refresh per-subresource spans + thread-local staging (Buffers reuse); a1a2077 vertex/mesh UAV flag declaration (the 5,046 "Flags must match usage" programs); da82e44/67e8ae1 buffer codes + compute-harness UAV zeroing. +- Conflict resolutions (7 files): + - texture.rs: took UPSTREAM wholesale - the fork's PR #9 splitmix digest (527c237) is superseded by upstream's per-subresource spans + blake3 + Buffers. Do not re-merge digest() by hand. + - twin.rs: kept BOTH - upstream's float depth (depth()/u16()) AND the fork's packed-colour modes 1-3 (up()/down(), B5G6R5/B5G5R5A1/B4G4R4A4 twins from b3a8b22). Doc comment merged. + - emit/shader.rs: tests mod is upstream's #[cfg(all(test, windows))]; kept BOTH fork's heap_handles_stay_inside_the_host_limits AND upstream's uavs_outside_pixel_and_compute_programs_are_declared. + - emit/lower.rs: Parts keeps BOTH heap_props (fork) and heap_handles (upstream, via m.written_calls); dropped the FORK's older helpers_read (quad && pixel && !discards.is_empty()) - upstream's 4015a18 (quad && pixel) is the corrected semantics (helpers at edges regardless of discard). Same dedupe trap as helper_reads_own in 42b5c9c. + - draw.rs/list.rs: fork's twin-redirect plumbing (format-patched tuple desc/view) wins over upstream's plain record.desc() line - the conflict sat INSIDE the fork's rewritten set_targets/clear_rtv. + - host.rs: kept by_preference (fork) + process_memory (upstream diagnostics). +- NOTE: CI does not run on non-main branch pushes (workflow triggers: pull_request, push to main only). Get a run by opening a PR. Run 45655729340 = PR #14. +- Local loader test failures (file_name_is_stable_per_build, patches_own_test_binary, keeps_iat_slots_...) are Linux-exe artifacts (tests parse current_exe() as PE, ELF gives "Unknown file magic"); Windows CI tests them. Not merge-related. diff --git a/README.md b/README.md index 9aa25d3558..3833e8ee76 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands; a device removal names the list it happened in and lists all its commands | -| `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500) | +| `VICTORY_TRACE_SHADERS=,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500, and all of them in listed capture frames); the records of its indirect executions are read back and logged in every frame (records with work, the first four, the frame) | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | | `VICTORY_PIPELINE_LOG=` | a line per title pipeline created (key, shaders, state), first used, and made or loaded (library name); `translate --cache --pipelines` writes the last kind too | | `VICTORY_PREBUILD_KEYS=` | `translate --cache --pipelines` makes nothing and lists each pack record's key, shaders and state (or why it is skipped) | diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index b8ec299324..8ff5e5a604 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -148,6 +148,11 @@ enum Console { SeriesS, } +/// Diagnostics: the heap bytes Rust code holds, for the statistics. +#[cfg(all(windows, feature = "diagnostics"))] +#[global_allocator] +static ALLOC: victory_gpu::CountingAlloc = victory_gpu::CountingAlloc; + fn main() -> Result<()> { victory_core::logging::init("info"); // The audio recorder `run` starts for `VICTORY_AUDIO_CAPTURE`. diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 0cf045c68c..22a72b0e08 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -56,8 +56,9 @@ pub fn run( // Before the import registry is first used: it holds the module only // when the host's FidelityFX serves. victory_hle::modules::fidelityfx::use_host_dir(cfg.fidelityfx_dir.as_deref()); - let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; - let prepared = victory_loader::prepare(&original)?; + let prepared = victory_loader::prepare( + &std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?, + )?; let hash = prepared.original_hash.to_hex(); let title_dir = exe.parent().unwrap_or(Path::new(".")); match victory_game::identify(&hash) { @@ -73,6 +74,8 @@ pub fn run( let images = cfg.cache_subdir("images")?; victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = victory_loader::load(&prepared, &images)?; + // Mapped: the patched bytes (the exe's size, 114 MB) are not needed. + drop(prepared); victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); println!( diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index e4c08be57a..e2033918db 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -26,8 +26,9 @@ enum Seen { /// A title texture (resource object) whose contents the title writes. Texture(usize), /// A view left without a host view (textures the title placed itself), - /// by kind (diagnostics: `KINDS`). - Left(#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] usize), + /// by kind (diagnostics: `KINDS`), with a placed texture's address and + /// console bytes. + Left(#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] (usize, u64, u64)), } /// Kinds of views left without a host view, for the census. @@ -43,17 +44,20 @@ pub(crate) struct Viewed { type Range = (usize, u64, u64, bool); -/// A merged range: copy, start, bytes, unordered access. -type Hull = (Arc, u64, u64, bool); +/// A merged range: copy, start, bytes, unordered access, the copy's bit in +/// the change tracker (`crate::watch::clean_bit`). +type Hull = (Arc, u64, u64, bool, Option); #[derive(Default)] struct Inner { slots: HashMap, ranges: BTreeMap)>, textures: BTreeMap, - /// `ranges` merged per copy and kind ([`Viewed::ranges`]), while no - /// range is added or dropped: every list running heap shaders asks. - hulls: Option>, + /// `ranges` merged per copy and kind ([`Viewed::ranges`]), kept current + /// as ranges come and go (each list running heap shaders asks for all + /// of them; rebuilt whole after every change, they cost 13-27 ms a frame, + /// run perf4). + hulls: HashMap<(usize, bool), Hull>, /// Per copy and kind (unordered access): the copy, and how many ranges /// start and end at each offset, so that the hulls are made from the /// copies, not from every range (the title rewrites slots between most @@ -89,15 +93,24 @@ impl Inner { } // A range came or went: its copy's hull may change. if (was == 0) != (now == 0) { - self.hulls = None; let ends = self .ends .entry((key.0, key.3)) .or_insert_with(|| (shadow.clone(), BTreeMap::new(), BTreeMap::new())); tally(&mut ends.1, key.1, now > 0); tally(&mut ends.2, key.2, now > 0); - if ends.1.is_empty() { - self.ends.remove(&(key.0, key.3)); + let hull = match (ends.1.keys().next(), ends.2.keys().next_back()) { + (Some(&from), Some(&to)) => Some((shadow.clone(), from, to - from, key.3, shadow.dirty_bit())), + _ => None, + }; + match hull { + Some(hull) => { + self.hulls.insert((key.0, key.3), hull); + } + None => { + self.ends.remove(&(key.0, key.3)); + self.hulls.remove(&(key.0, key.3)); + } } } } @@ -130,21 +143,9 @@ impl Viewed { /// The buffer ranges views reach, merged per host copy and kind /// (shader resource, unordered access): copy, start, bytes. + #[cfg(any(test, feature = "diagnostics"))] fn ranges(&self) -> Vec { - let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(hulls) = &inner.hulls { - return hulls.clone(); - } - let hulls: Vec = inner - .ends - .iter() - .filter_map(|(&(_, uav), (shadow, starts, ends))| { - let (&from, &to) = (starts.keys().next()?, ends.keys().next_back()?); - Some((shadow.clone(), from, to - from, uav)) - }) - .collect(); - inner.hulls = Some(hulls.clone()); - hulls + self.inner.lock().unwrap_or_else(|e| e.into_inner()).hulls.values().cloned().collect() } } @@ -153,9 +154,9 @@ fn seen(view: &View) -> Option { let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); if let View::Shader(resource, _) = view - && let Some(texture) = crate::resource::host_resource(*resource as This) + && let Some(texture) = crate::resource::made_copy(*resource as This) { - return crate::texture::title_written(texture).then_some(Seen::Texture(*resource)); + return crate::texture::title_written(&texture.texture).then_some(Seen::Texture(*resource)); } // The copy the host view reads. let (shadow, address, len) = match *view { @@ -173,54 +174,111 @@ fn seen(view: &View) -> Option { Some(Seen::Buffer(shadow, address, len, uav)) } -fn left_kind(view: &View) -> usize { +fn left_kind(view: &View) -> (usize, u64, u64) { match view { - View::Placed(_, resource, _) if resource[0] != 1 => 2, - View::Unordered(..) | View::Placed(true, ..) => 1, - View::Shader(..) | View::Placed(false, ..) | View::Constant(..) => 0, - _ => 3, + View::Placed(_, resource, desc) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + (2, address, crate::resource::placed_size(resource).unwrap_or(0)) + } + View::Unordered(..) | View::Placed(true, ..) => (1, 0, 0), + View::Shader(..) | View::Placed(false, ..) | View::Constant(..) => (0, 0, 0), + _ => (3, 0, 0), } } /// At submission, before anything else of it: the textures the heaps of its -/// heap-indexing lists view are brought up to date, those whose title -/// memory changed copied into their host textures by a list of ours, which -/// the submission runs first (and leaves them readable by shaders). +/// heap-indexing lists view, and `textures` (staging and host texture of +/// those its lists read through tables, `crate::texture::upload`), are +/// brought up to date, those whose title memory changed copied into their +/// host textures by a list of ours, which the submission runs first (and +/// leaves them readable by shaders): each at most once. /// /// shortcut: a title copy into texture memory recorded in the same /// submission shows from the next one on. -pub(crate) fn uploads(heaps: &[Arc]) -> Option { +pub(crate) fn uploads( + heaps: &[Arc], + textures: &[(Arc, Arc)], +) -> Option { static LIST: Mutex = Mutex::new(Holder(None)); - const SHADER_RESOURCE: u32 = 0x40 | 0x80; let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner()); + crate::texture::recycle(); match &guard.0 { // Closed by the last submission, which has run. Some(list) => list.reset(), // Made open. - None => guard.0 = Some(crate::host::host()?.new_list().ok()?), + None => { + let list = crate::host::host()?.new_list().ok()?; + list.set_ours(); + guard.0 = Some(list); + } } let list = guard.0.as_ref()?; - let mut recorded = false; + // What to bring up: the textures lists read through tables, and those + // the heaps view that shaders read lately. Collected under the heaps' + // locks and brought up without them, several at a time: reading title + // memory, detiling and making staging buffers took half the submitting + // thread in a new shot, and title threads setting views waited on the + // lock meanwhile (run evict5). + let mut work: Vec<(Arc, Arc)> = Vec::new(); + let mut staged = std::collections::HashSet::new(); + for (staging, copy) in textures { + // A host copy wrote it in a submission made before this one (it + // was not when the list was recorded). + if copy.host_written.load(Relaxed) { + continue; + } + if staged.insert(Arc::as_ptr(staging)) { + work.push((staging.clone(), copy.clone())); + } + } let mut done = std::collections::HashSet::new(); for viewed in heaps { - // Held while uploading: the title releasing a texture (and its - // memory) waits in `forget`. let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); for &r in inner.textures.keys() { if !done.insert(r) { continue; } - let Some(texture) = crate::resource::host_resource(r as This) else { + // Not made (given up, or never read): nothing to bring up. + let Some(texture) = crate::resource::made_copy(r as This) else { continue; }; - if crate::texture::upload_changed(list, r as This, texture) { - crate::list::ensure_state(list, r as This, SHADER_RESOURCE); - recorded = true; - #[cfg(feature = "diagnostics")] - UPLOADED.fetch_add(1, Relaxed); + // Only what shaders read lately (the eviction pass's stamps): + // the heaps view thousands of textures a frame never reads, and + // bringing each up whenever its pages change re-uploaded about + // 4 GB in 30-46 world frames (runs evict2, noevict1). + // shortcut: a texture read again after a gap is brought up after + // the submission that read it, which can see bytes one refresh + // old (a slot the title rewrites is made fresh anyway); upload on + // the mark itself if that shows. + if !texture.used_recently() { + continue; + } + // Its contents are the host's since a host copy wrote it. + if texture.host_written.load(Relaxed) { + continue; + } + if let Some(staging) = crate::texture::staging(r as This, &texture.texture) + && staged.insert(Arc::as_ptr(&staging)) + { + work.push((staging, texture)); } } } + let mut recorded = false; + // The textures copied into stay alive in `work` until recorded. + let mut readable = Vec::new(); + for ((staging, copy), upload) in work.iter().zip(crate::texture::refresh_all(&work)) { + if let Some(upload) = upload { + readable.extend(crate::texture::record_upload(list, copy, staging, &upload)); + recorded = true; + #[cfg(feature = "diagnostics")] + UPLOADED.fetch_add(1, Relaxed); + } + } + if !readable.is_empty() { + // SAFETY: an open list; the barriers name live textures. + unsafe { list.list.ResourceBarrier(&readable) }; + } list.close(); // A list recording nothing is not run (its reset next time is fine). recorded.then_some(Uploads(guard)) @@ -252,9 +310,15 @@ impl Uploads { /// there. Copying back the whole unordered ranges after every submission /// (about 1 GB of them in the world) cost seconds per frame; the upgrade /// is shaders marking the pages they write (as `crate::memory` does). +/// +/// Copies the title has not written since they took it are passed by: a +/// world submission's heaps reach ~9,000 copies, a few of them written. pub(crate) fn refresh(viewed: &Viewed, mut add: impl FnMut(&Arc, usize, usize)) { - for (shadow, address, len, _) in viewed.ranges() { - add(&shadow, address as usize, len as usize); + let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); + for (shadow, address, len, _, bit) in inner.hulls.values() { + if !crate::watch::clean_bit(*bit) { + add(shadow, *address as usize, *len as usize); + } } } @@ -305,13 +369,22 @@ pub(crate) fn log(frames: f64) { let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner()); let mut left = [0u32; KINDS.len()]; let (mut buffers, mut textures) = (0u32, 0u32); + // Placed textures left null: the largest at each address. + let mut placed = HashMap::new(); for seen in inner.slots.values() { match seen { Seen::Buffer(..) => buffers += 1, Seen::Texture(_) => textures += 1, - Seen::Left(k) => left[*k] += 1, + Seen::Left((k, address, bytes)) => { + left[*k] += 1; + if *k == 2 { + let b = placed.entry(*address).or_insert(0u64); + *b = (*b).max(*bytes); + } + } } } + let placed_mb = placed.values().sum::() as f64 / 1e6; let bytes: u64 = inner.ranges.keys().map(|&(_, a, b, _)| b - a).sum(); drop(inner); let hulls = viewed.ranges(); @@ -330,11 +403,13 @@ pub(crate) fn log(frames: f64) { "heap views: {draws:.0} draws/frame index the heap ({writes:.0} writing through it), \ {uploaded:.0} textures uploaded/frame; slots: {buffers} buffer views ({} ranges, \ {:.1} MB, {copies} copies), {textures} title-written textures ({} distinct); \ - left null: {}; host copies of title memory: {} ({:.1} MB); hulls {:.1} MB, unordered {:.1} MB", + left null: {} (placed textures at {} addresses, {placed_mb:.0} MB); \ + host copies of title memory: {} ({:.1} MB); hulls {:.1} MB, unordered {:.1} MB", inner.ranges.len(), bytes as f64 / 1e6, inner.textures.len(), left.join(", "), + placed.len(), all.len(), all_bytes as f64 / 1e6, all_hulls as f64 / 1e6, diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index cd56afdec0..dad1de03e1 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -423,9 +423,9 @@ fn peek(when: &str) { } } -/// In a listed frame: copies an indirect execution's records (`args`: -/// buffer, offset; in the indirect-argument state) and its count (in the -/// unordered-access state unless in the same buffer) to readback memory, +/// In a listed frame: copies an indirect execution's records (`args`: the +/// list's argument buffer and offset, in the indirect-argument state) and +/// its count (a title buffer's copy) to readback memory, /// logged once the list has run: how many records ask for work, and the /// first ones. pub(crate) fn read_indirect( @@ -434,6 +434,7 @@ pub(crate) fn read_indirect( count: Option<(&ID3D12Resource, u64)>, (kind, stride, max): (u32, u32, u32), name: String, + always: bool, ) { struct Readback(ID3D12Resource); // SAFETY: D3D12 objects are free-threaded. @@ -456,7 +457,6 @@ pub(crate) fn read_indirect( let mut buffer: Option = None; let l = &list.list; use crate::host::transition; - use windows::core::Interface; let (arg_state, copy) = (D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); // SAFETY: plain creation; an open list and live buffers in the states // named, put back after the copies. @@ -472,15 +472,8 @@ pub(crate) fn read_indirect( l.ResourceBarrier(&[transition(args.0, arg_state, copy)]); l.CopyBufferRegion(&buffer, 0, args.0, args.1, len); if let Some((c, at)) = count { - let same = c.as_raw() == args.0.as_raw(); - let state = if same { copy } else { D3D12_RESOURCE_STATE_UNORDERED_ACCESS }; - if !same { - l.ResourceBarrier(&[transition(c, state, copy)]); - } + // A title buffer's copy: never transitioned, the read promotes it. l.CopyBufferRegion(&buffer, len, c, at, 4); - if !same { - l.ResourceBarrier(&[transition(c, copy, state)]); - } } l.ResourceBarrier(&[transition(args.0, copy, arg_state)]); list.keep(&buffer); @@ -488,7 +481,8 @@ pub(crate) fn read_indirect( let counted = count.is_some(); list.defer_after(move || { // Recorded ahead: logged if the frame running it is listed. - if !listed(crate::queue::presented() + 1) { + let frame = crate::queue::presented() + 1; + if !always && !listed(frame) { return; } let mut data = std::ptr::null_mut(); @@ -513,7 +507,7 @@ pub(crate) fn read_indirect( let shown: Vec<&[u32]> = (0..records.min(4)).map(first).collect(); tracing::info!( target: "victory_gpu::trace", - "indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name}" + "indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name} frame {frame}" ); buffer.0.Unmap(0, None); }); @@ -628,12 +622,20 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option type Decode = Box [f32; 3]>; let (n, decode): (usize, Decode) = match format { 27..=32 => { + // The PNG drops alpha: its range and how many texels have each + // channel zero are logged. + let (mut low, mut high, mut zero) = ([255u8; 4], [0u8; 4], [0usize; 4]); for y in 0..h { for x in 0..w { let p = px(x, y, 4); + for c in 0..4 { + (low[c], high[c]) = (low[c].min(p[c]), high[c].max(p[c])); + zero[c] += usize::from(p[c] == 0); + } out.extend([p[0], p[1], p[2], 255]); } } + tracing::info!(format, ?low, ?high, ?zero, texels = w * h, "target values (8-bit, RGBA)"); return Some(out); } // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below). @@ -747,20 +749,29 @@ pub(crate) fn probe( Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; - let mut buffer: Option = None; - // SAFETY: plain creation; an open list; locations naming live resources. - unsafe { - device - .CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut buffer, - ) + // One buffer for every present: each is waited for before the next + // (made and released per present, it cost a kernel call per frame). + static BUFFER: std::sync::OnceLock> = std::sync::OnceLock::new(); + let buffer = BUFFER + .get_or_init(|| { + let mut buffer: Option = None; + // SAFETY: plain creation. + unsafe { + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + } .ok()?; - let buffer = buffer?; + buffer + }) + .clone()?; + // SAFETY: an open list; locations naming live resources. + unsafe { for i in 0..GRID * GRID { let (x, y) = ( (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID), diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 74cd932b65..792d942953 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -94,8 +94,18 @@ pub(crate) enum C { MarkedUs, MarkedKept, SavedPages, + /// Preparing submissions: descriptors the title copied into its heaps + /// as bytes, made on the host first. + SyncHeapsUs, + /// Of those: heap slots looked at (every slot of each page written). + SyncSlots, + /// Time in copies redone piece by piece after meeting an unmapped page. + FallbackUs, + /// Title threads writing a view into a shader-visible heap: time + /// waiting for the heaps' lock (held by heap syncs and other writers). + MirrorWaitUs, } -const COUNTERS: usize = 57; +const COUNTERS: usize = 61; static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -217,14 +227,14 @@ pub(crate) fn log(frames: f64) { "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \ {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ - unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ + unchanged; {:.1} fallbacks ({:.1} ms); {:.0} guard faults; textures {:.1} MB watched and \ changed, {:.1} MB hashed, {:.1} MB of them changed; watch time: kernel {:.1} ms, view queries {:.1} ms, protecting {:.1} ms; copied whole (not tracked) {:.1} MB in {:.1} ms; snapshots {:.1} MB in {:.1} ms; page faults {:.0} preparing, {:.0} copying back; {:.0} tracked pages marked through another mapping; \ guards: {:.2} ms in the handler, {:.0} protect calls for {:.0} pages, {:.0} pages opened; \ {:.0} tracked pages written ({:.0} of them the frame before too); change checks: {:.1} ms \ asking for other mappings, {:.1} ms waiting for the guard lock; preparing: {:.1} ms in \ refresh batches, steps (each with the batch it flushes): refresh {:.1} ms, copy {:.1} ms, \ work {:.1} ms, GPU writes {:.1} ms, textures {:.1} ms, heaps {:.1} ms, title memory {:.1} ms; \ - heap texture uploads {:.1} ms, state preludes {:.1} ms; copying back compared {:.1} MB in {:.1} ms; marked pages: {:.0} compared, {:.1} MB written back in {:.1} ms, {:.0} kept the title's, {:.0} saved; working set {:.0} MB, \ + heap texture uploads {:.1} ms, state preludes {:.1} ms, heap slots the title copied {:.1} ms ({:.0} slots), title threads waiting to write views {:.1} ms; copying back compared {:.1} MB in {:.1} ms; marked pages: {:.0} compared, {:.1} MB written back in {:.1} ms, {:.0} kept the title's, {:.0} saved; working set {:.0} MB, \ {:.0} hard faults", c[C::Submissions as usize], c[C::Copies as usize], @@ -245,6 +255,7 @@ pub(crate) fn log(frames: f64) { mb(c[C::Checked as usize]), mb(c[C::Unchanged as usize]), c[C::Fallbacks as usize], + ms(c[C::FallbackUs as usize]), c[C::GuardFaults as usize], mb(c[C::TexWatched as usize]), mb(c[C::TexHashed as usize]), @@ -277,6 +288,9 @@ pub(crate) fn log(frames: f64) { ms(c[C::StepMemoryUs as usize]), ms(c[C::UploadsUs as usize]), ms(c[C::PreludeUs as usize]), + ms(c[C::SyncHeapsUs as usize]), + c[C::SyncSlots as usize], + ms(c[C::MirrorWaitUs as usize]), mb(c[C::CompareBytes as usize]), ms(c[C::CompareUs as usize]), c[C::MarkedPages as usize], @@ -323,3 +337,83 @@ pub(crate) fn log(frames: f64) { ); } } + +/// A global allocator that counts the bytes Rust code holds (the +/// statistics' "our heap"; the binary installs it in diagnostics builds). +pub struct CountingAlloc; + +/// Bytes [`CountingAlloc`] has handed out and not taken back. +pub(crate) static HEAP_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Allocations of at least this many bytes name their caller, once per +/// power-of-two size class (who holds the big blocks of our heap). +const LARGE: usize = 32 << 20; + +/// Logs the stack of a large allocation of `size` bytes, the first of its +/// size class. +fn note_large(size: usize) { + static SEEN: std::sync::Mutex = std::sync::Mutex::new(0); + std::thread_local!(static INSIDE: std::cell::Cell = const { std::cell::Cell::new(false) }); + let class = 1u64 << size.ilog2().min(63); + if INSIDE.with(|i| i.replace(true)) { + return; + } + let first = { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let first = *seen & class == 0; + *seen |= class; + first + }; + if first { + let trace = std::backtrace::Backtrace::force_capture().to_string(); + let frames: Vec<&str> = trace.lines().filter(|l| l.contains("victory")).take(24).collect(); + tracing::info!(mb = size >> 20, "a large heap allocation (first of its size class): {}", frames.join(" | ")); + } + INSIDE.with(|i| i.set(false)); +} + +// SAFETY: every call goes to the system allocator unchanged; only counted. +unsafe impl std::alloc::GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's layout, passed on. + let p = unsafe { std::alloc::System.alloc(layout) }; + if !p.is_null() { + HEAP_BYTES.fetch_add(layout.size() as u64, Relaxed); + if layout.size() >= LARGE { + note_large(layout.size()); + } + } + p + } + + unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: as above. + let p = unsafe { std::alloc::System.alloc_zeroed(layout) }; + if !p.is_null() { + HEAP_BYTES.fetch_add(layout.size() as u64, Relaxed); + if layout.size() >= LARGE { + note_large(layout.size()); + } + } + p + } + + unsafe fn dealloc(&self, p: *mut u8, layout: std::alloc::Layout) { + HEAP_BYTES.fetch_sub(layout.size() as u64, Relaxed); + // SAFETY: a block this allocator handed out with this layout. + unsafe { std::alloc::System.dealloc(p, layout) } + } + + unsafe fn realloc(&self, p: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + // SAFETY: as above. + let q = unsafe { std::alloc::System.realloc(p, layout, size) }; + if !q.is_null() { + HEAP_BYTES.fetch_sub(layout.size() as u64, Relaxed); + HEAP_BYTES.fetch_add(size as u64, Relaxed); + if size >= LARGE { + note_large(size); + } + } + q + } +} diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 22ea4a7efb..a48e52a933 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -126,7 +126,11 @@ static SHADER_HEAPS: std::sync::Mutex> = std::sync::Mutex /// so `Heap::drop` cannot free the heap concurrently. #[cfg(windows)] fn mirror(handle: u64) { + #[cfg(feature = "diagnostics")] + let waited = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::MirrorWaitUs); let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + drop(waited); let Some(&(_, _, at)) = heaps .iter() .find(|&&(start, end, _)| (start..end).contains(&handle)) @@ -181,14 +185,94 @@ pub(crate) fn sync_heaps() { continue; } let (first, last) = ((page as u64 - start) / step, (end as u64 - start).div_ceil(step)); - for index in first..last.min(u64::from(heap.desc.count)) { - host.mirror(index as u32, start + index * step, false); - } + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::SyncSlots, + last.min(u64::from(heap.desc.count)).saturating_sub(first), + ); + host.sync_slots(first as u32, last.min(u64::from(heap.desc.count)) as u32, start, step); } } } } +/// Makes the views of slots `slots` that were left null (textures the title +/// placed itself, textures given up) in every shader-visible view heap, now +/// that shaders read them (`crate::shadow::take_reads`), and stamps what +/// they view as used (`crate::resource::evict`). +#[cfg(windows)] +pub(crate) fn make_read(slots: &[u32]) { + // The placed textures those slots view are made first, without the + // heaps' lock, which every title thread writing a view waits on (making + // a texture takes up to milliseconds; title threads waited 1-6 s a frame, + // runs evict2, noevict1). They are never released, so they outlive it; + // the lock is held only to look the slots up and to make the views. + let placed: Vec = { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, at)| unsafe { &*(at as *const Heap) }) + .filter(|heap| heap.desc.kind == VIEWS_KIND) + .filter_map(|heap| heap.host.get()?.as_ref().map(|host| (heap, host))) + .flat_map(|(heap, host)| slots.iter().filter(|&&i| i < heap.desc.count).filter_map(|&i| host.unmade_placed(i))) + .collect() + }; + #[cfg(test)] + tests::while_making(slots); + // Several at a time (each a committed texture; hundreds in a new shot, + // 7 % of the submitting thread when made one by one, run evict5). + crate::texture::in_parallel(placed.len(), |i| { + let _ = host::placed_texture(&placed[i]); + }); + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(start, _, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(step)) = (heap.host.get(), increment(heap.desc.kind)) else { + continue; + }; + if heap.desc.kind != VIEWS_KIND { + continue; + } + for &i in slots.iter().filter(|&&i| i < heap.desc.count) { + host.mirror(i, start + u64::from(i) * u64::from(step), true); + host.stamp_read(i); + } + } +} + +/// The host textures (raw pointers) that slots `slots` of the +/// shader-visible view heaps view. +#[cfg(windows)] +pub(crate) fn read_textures(slots: &[u32]) -> std::collections::HashSet { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = std::collections::HashSet::new(); + for &(_, _, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + if let (Some(Some(host)), VIEWS_KIND) = (heap.host.get(), heap.desc.kind) { + textures.extend(host.textures_at(slots)); + } + } + textures +} + +/// Every shader-visible view heap's slots viewing one of the host textures +/// `textures` (raw pointers) are left null, made again when read +/// (`crate::resource::evict` gives those textures up). +#[cfg(windows)] +pub(crate) fn evict(textures: &std::collections::HashSet) { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(_, _, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + if let (Some(Some(host)), VIEWS_KIND) = (heap.host.get(), heap.desc.kind) { + host.evict(textures); + } + } +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] @@ -450,6 +534,18 @@ fn view_at(i: u32, generation: u32) -> Option { (*current == generation).then(|| view.clone()) } +/// For each record (tag, index, generation): whether it names a view that +/// is current, as [`view_at`] would find it (one lock for them all). +fn views_current(records: &[[u32; 3]]) -> Vec { + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + records + .iter() + .map(|&[tag, i, generation]| { + tag == VIEW_TAG && views.list.get(i as usize).is_some_and(|(_, current)| *current == generation) + }) + .collect() +} + /// The view recorded at `handle`, if one is (and its resource is alive). pub(crate) fn view(handle: u64) -> Option { if handle == 0 { @@ -715,7 +811,24 @@ static FUNCTIONS: Table<24> = { }; #[cfg(test)] -mod tests { +pub(crate) mod tests { + /// Work to run while `make_read` makes the textures of a read slot (the + /// slot), outside the heaps' lock. + pub(crate) static WHILE_MAKING: std::sync::Mutex> = std::sync::Mutex::new(None); + + /// The work [`WHILE_MAKING`] runs. + pub(crate) type Work = Box; + + pub(crate) fn while_making(slots: &[u32]) { + let mut hook = WHILE_MAKING.lock().unwrap_or_else(|e| e.into_inner()); + if hook.as_ref().is_some_and(|(slot, _)| slots.contains(slot)) + && let Some((_, work)) = hook.take() + { + drop(hook); + work(); + } + } + use super::*; use crate::object::{S_OK, slot}; diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index c2655e74f4..6505d078c5 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -10,7 +10,7 @@ use std::sync::Mutex; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; -use super::{VIEW_TAG, View, view_at}; +use super::{VIEW_TAG, View, view_at, views_current}; use crate::host::host; pub(crate) struct HostHeap { @@ -51,10 +51,10 @@ pub(crate) struct HostHeap { /// view there, `VIEW_MARK_NONE` for none. Mapped at the address kept /// beside it. marks: Option<(ID3D12Resource, usize)>, - /// Per title slot, the title address of the buffer view it holds, as a - /// buffer descriptor's dwords 0 and 1 (shaders reading a descriptor's - /// address as data, `crate::memory`): the buffer, its mapping and host - /// address, made on first use. + /// Per title slot, the console descriptor's dwords 0-3 as far as the + /// host knows them (shaders reading a descriptor as data, `crate::memory`; + /// [`write_address`]): the buffer, its mapping and host address, made on + /// first use. addresses: std::sync::OnceLock>, /// What the title slots view that title memory feeds (`crate::bindless`). pub(crate) viewed: std::sync::Arc, @@ -574,9 +574,10 @@ impl HostHeap { } /// Enters the byte stride of `view` (0 for none or not a buffer view) - /// for slot `index` in the view-stride table. + /// for slot `index` in the view-stride table, with the integer-format + /// bits of a typed buffer view ([`view_kind`]). fn set_stride(&self, index: u32, view: Option<&View>) { - self.write_stride(index, view.map_or(0, view_stride)); + self.write_stride(index, view.map_or(0, |v| view_stride(v) | view_kind(v))); } fn write_stride(&self, index: u32, stride: u32) { @@ -647,7 +648,7 @@ impl HostHeap { /// on first use from the slots made so far. pub(crate) fn view_addresses(&self) -> Option { let made = self.addresses.get_or_init(|| { - let (buffer, data) = host()?.upload_buffer(u64::from(self.count) * 8)?; + let (buffer, data) = host()?.upload_buffer(u64::from(self.count) * 16)?; crate::host::name(&buffer, || "view addresses".into()); let data = data as usize; let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); @@ -733,6 +734,34 @@ impl HostHeap { } } + /// A heap sync of slots `first..last`, whose records are at `start` + + /// index × `step`: [`HostHeap::mirror`] of each slot whose record + /// differs from what the slot holds, the rest passed by as `mirror` + /// would, with one lock of each kind for them all instead of two per slot + /// (a world frame looks at ~700,000 slots, run perf3: ~75 ms). + pub(crate) fn sync_slots(&self, first: u32, last: u32, start: u64, step: u64) { + let at = |i: u32| start + u64::from(i) * step; + // SAFETY: records in title heap memory the caller found mapped. + let records: Vec<[u32; 3]> = + (first..last).map(|i| unsafe { (at(i) as *const [u32; 3]).read_unaligned() }).collect(); + let current = views_current(&records); + let stale: Vec = { + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + (first..last) + .zip(records.iter().zip(current)) + .filter(|&(i, (&[_, view, generation], current))| match made.get(i as usize) { + Some(&m) if current => m != u64::from(generation) << 32 | u64::from(view), + Some(&m) => m != 0, + None => true, + }) + .map(|(i, _)| i) + .collect() + }; + for i in stale { + self.mirror(i, at(i), false); + } + } + /// 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 @@ -778,17 +807,50 @@ impl HostHeap { } return None; }; - if made[index as usize] != key { + // A placed texture's view left null below is made when a draw reads + // the slot through a table; until then the slot is not made again + // (heap syncs revisit it at every submission). + let lazy = || { + for_draw + && is_texture(&view) + && self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_none() + }; + if made[index as usize] == key && !lazy() { + return Some(view); + } + // Shaders index the heap itself (`crate::bindless`): buffer views + // are made when written. + // shortcut: views of textures the title placed itself are made + // when a draw reads them through a table: a host texture (and a + // staging copy) for each of the ~20,000 the title has views of + // ran the host out of memory (run b2). + let later = !for_draw && is_placed_texture(&view); + if !later { + // What the view needs (the texture it views, the copy of the + // memory) is made without the slot lock, which title threads + // binding and writing views wait on (run evict5). + drop(made); + prepare(&view); + made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + // The title may have written another record there meanwhile (and + // another thread made it): that one is the slot's. + // SAFETY: as above. + if unsafe { (handle as *const [u32; 3]).read_unaligned() } != [tag, i, generation] { + drop(made); + return self.mirror(index, handle, for_draw); + } + if made[index as usize] == key && !lazy() { + return Some(view); + } + } + { self.set_stride(index, Some(&view)); self.note_address(index, Some(&view)); - // Shaders index the heap itself (`crate::bindless`): buffer views - // are made when written. - // shortcut: views of textures the title placed itself are made - // when a draw reads them through a table: a host texture (and a - // staging copy) for each of the ~20,000 the title has views of - // ran the host out of memory (run b2). - let later = !for_draw && is_placed_texture(&view); - made[index as usize] = if later { 0 } else { key }; + if later { + // Made once a shader reads it (`crate::shadow::take_reads`). + crate::shadow::forget_read(index); + } + made[index as usize] = key; let (kept, mark) = if later { (None, None) } else { @@ -827,11 +889,89 @@ impl HostHeap { Some(text) } + /// Slots viewing one of the host textures `textures` (raw pointers), + /// which are given up: each gets a null view of its kind and holds the + /// texture no more (retired until the running submission has run), its + /// record stays noted so heap syncs leave it, and the next draw reading + /// it through a table or shader reading it through the heap (its read + /// mark, cleared) makes it again. + /// The slots are found by a walk of the heap, once per pass that gives + /// textures up: a map of each texture's slots, kept at every slot the + /// title rewrote, cost ~25 us a slot (a texture viewed in thousands of + /// slots had its list searched each time; 62,000 slots a frame, run + /// evict3). + pub(crate) fn evict(&self, textures: &std::collections::HashSet) { + let slots: Vec = { + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + (0..kept.len() as u32) + .filter(|&i| { + kept[i as usize] + .as_ref() + .is_some_and(|k| k.1.is_none() && textures.contains(&(windows::core::Interface::as_raw(&k.0) as usize))) + }) + .collect() + }; + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + for index in slots { + let key = made.get(index as usize).copied().unwrap_or(0); + let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten(); + match &view { + Some(v) => null_for(v, self.cpu(index)), + None => null_view(self.cpu(index)), + } + self.keep(index, None); + if index < self.count { + self.viewed.set(index, view.as_ref(), false); + crate::shadow::forget_read(index); + } + } + } + + /// The host textures (raw pointers) slots `slots` view. + pub(crate) fn textures_at(&self, slots: &[u32]) -> Vec { + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + slots + .iter() + .filter_map(|&i| kept.get(i as usize)?.as_ref().filter(|k| k.1.is_none())) + .map(|k| windows::core::Interface::as_raw(&k.0) as usize) + .collect() + } + + /// The view of slot `index` if it is a placed texture's left without a + /// host view (made when read). + pub(crate) fn unmade_placed(&self, index: u32) -> Option { + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?; + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).is_some_and(Option::is_some); + (is_placed_texture(&view) && !kept).then_some(view) + } + + /// A shader read slot `index` through the heap: the texture it views + /// was used now. + pub(crate) fn stamp_read(&self, index: u32) { + let key = self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).copied().unwrap_or(0); + let Some(view) = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten() else { + return; + }; + let view = placed_texture(&view).unwrap_or(view); + if let View::Shader(r, _) = view + && let Some(t) = crate::resource::made_copy(r as crate::object::This) + { + t.stamp(); + } + } + /// Whether slot `index` was made from a record (tests). #[cfg(test)] pub(crate) fn made(&self, index: u32) -> bool { self.made.lock().unwrap_or_else(|e| e.into_inner())[index as usize] != 0 } + + /// Whether slot `index` holds a host view of a resource (tests). + #[cfg(test)] + pub(crate) fn kept(&self, index: u32) -> bool { + self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_some() + } } /// Logs `what` the first time it happens. @@ -904,6 +1044,51 @@ fn view_stride(view: &View) -> u32 { element.max(1) as u32 } +/// The view-stride table's format-kind bits of a buffer view: a typed view +/// (no structure stride, not raw) of an integer format gets +/// `VIEW_INTEGER`, a signed one also `VIEW_SIGNED`; anything else none. +/// Translated shaders pass 16-bit typed data of such views as bits, not as +/// halves (`victory_shader::emit`, "d16"). +fn view_kind(view: &View) -> u32 { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let (unordered, words): (bool, &[u32; 10]) = match view { + View::Shader(_, Some(desc)) => (false, desc), + View::Unordered(_, _, Some(desc)) => (true, desc), + View::Placed(unordered, resource, desc) if resource[0] == 1 => match desc[..10].try_into() { + Ok(words) => (*unordered, words), + Err(_) => return 0, + }, + _ => return 0, + }; + // Buffer views only (dimension 1); a structured or raw one is no typed view. + let (format, typed) = if unordered { + let desc = uav_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + (desc.Format.0 as u32, b.StructureByteStride == 0 && b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 == 0) + } else { + let desc = srv_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + (desc.Format.0 as u32, b.StructureByteStride == 0 && b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 == 0) + }; + match (words[1] == 1 && typed).then(|| integer_format(format)).flatten() { + Some(true) => VIEW_INTEGER | VIEW_SIGNED, + Some(false) => VIEW_INTEGER, + None => 0, + } +} + +/// Whether a DXGI format is an integer one, and if so whether signed: +/// `Some(false)` for `UINT`, `Some(true)` for `SINT`, `None` otherwise. +fn integer_format(format: u32) -> Option { + match format { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => Some(false), + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => Some(true), + _ => None, + } +} + /// A buffer view of title memory at `address` on its host copy: the first /// element moves by the copy's offset. /// Bytes per element of a buffer view. @@ -919,14 +1104,83 @@ fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 { } } -/// Writes slot `index`'s view address into the view addresses at `data`: -/// a buffer view's title address (dword 0 low, dword 1 bits 0-15 high); -/// zeros for anything else. +/// Writes slot `index`'s words into the view addresses at `data`, 16 bytes +/// a slot: a buffer view's title address (dword 0 low, dword 1 bits 0-15 +/// high), a texture view's size fields ([`texture_words`]), zeros for +/// anything else. fn write_address(data: usize, index: usize, view: Option<&View>) { let address = view.and_then(buffer_range).map_or(0, |(a, _)| a); - let words = [address as u32, (address >> 32) as u32 & 0xFFFF]; - // SAFETY: the mapped view addresses hold 8 bytes per title slot. - unsafe { ((data + 8 * index) as *mut [u32; 2]).write_unaligned(words) }; + let words = match view.and_then(texture_words) { + Some(words) => words, + None => [address as u32, (address >> 32) as u32 & 0xFFFF, 0, 0], + }; + // SAFETY: the mapped view addresses hold 16 bytes per title slot. + unsafe { ((data + 16 * index) as *mut [u32; 4]).write_unaligned(words) }; +} + +/// A texture view's console image descriptor dwords 0-3 as far as its size +/// goes: width - 1 and height - 1 of the resource's level 0 (dword 1 bits +/// 30-31, dword 2 bits 0-13 and 14-29), dword 3 an identity swizzle, the +/// view's first and last level (bits 12-15, 16-19) and the image type (bits +/// 28-31). `None` for buffers and samplers. +// shortcut: the address, format and tiling fields read 0 (no translated +// shader reads them: the shader refuses such reads where it can tell), +// and the swizzle is the identity whatever the view's component mapping. +fn texture_words(view: &View) -> Option<[u32; 4]> { + let (resource, desc, unordered) = match view { + View::Shader(r, desc) => (crate::resource::texture_desc(*r as crate::object::This)?, *desc, false), + View::Unordered(r, _, desc) => (crate::resource::texture_desc(*r as crate::object::This)?, *desc, true), + View::Placed(unordered, resource, desc) if resource[0] != 1 => { + (*resource, desc[..10].try_into().ok(), *unordered) + } + _ => return None, + }; + Some(image_words(&resource, desc.as_ref(), unordered)) +} + +/// [`texture_words`] of a texture of resource description `resource` (as +/// words) through a view of description `desc` (none: the resource's own). +fn image_words(resource: &[u32; 14], desc: Option<&[u32; 10]>, unordered: bool) -> [u32; 4] { + let width = u64::from(resource[4]) | u64::from(resource[5]) << 32; + let height = resource[6]; + let (depth, mips) = (resource[7] & 0xFFFF, resource[7] >> 16); + let (samples, dimension) = (resource[9], resource[0]); + // Mip count 0: the whole chain. + let deepest = if dimension == 4 { depth } else { 1 }; + let chain = 64 - (width.max(u64::from(height)).max(u64::from(deepest)) | 1).leading_zeros(); + let mips = if mips == 0 { chain } else { mips }; + // Image types: 8 1D, 9 2D, 10 3D, 11 cube, 12 1D array, 13 2D array, + // 14 2D MSAA, 15 2D MSAA array. + let (ty, first, count) = match desc { + // Shader and unordered view dimensions number alike up to 3D (8). + Some(d) => { + let ty = [0, 0, 8, 12, 9, 13, 14, 15, 10, 11, 11].get(d[1] as usize).copied().unwrap_or(0); + match (unordered, d[1]) { + (_, 6 | 7) => (ty, 0, 1), + (true, _) => (ty, d[4], 1), + (false, _) => (ty, d[4], if d[5] == u32::MAX { mips.saturating_sub(d[4]) } else { d[5] }), + } + } + None => { + let array = depth > 1; + let ty = match dimension { + 2 if array => 12, + 2 => 8, + 3 if samples > 1 => 14 + u32::from(array), + 3 => 9 + 4 * u32::from(array), + _ => 10, + }; + (ty, 0, if unordered { 1 } else { mips }) + } + }; + let (w, h) = (width.saturating_sub(1) as u32, height.saturating_sub(1)); + let last = first + count.max(1) - 1; + [ + 0, + (w & 3) << 30, + (w >> 2 & 0x3FFF) | (h & 0xFFFF) << 14, + 0xFAC | (first & 0xF) << 12 | (last & 0xF) << 16 | ty << 28, + ] } /// The title memory a buffer shader or unordered access view reads: its @@ -1231,6 +1485,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(copy) = crate::resource::host_copy(resource) { + copy.viewed.store(true, std::sync::atomic::Ordering::Relaxed); let texture = ©.texture; let mut desc = desc.as_ref().map(srv_desc); if desc.is_none() && !default_view(resource) { @@ -1266,6 +1521,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { _ => None, }; }; + copy.viewed.store(true, std::sync::atomic::Ordering::Relaxed); let texture = ©.texture; // A depth texture's unordered views write its twin. // SAFETY: a live resource. @@ -1346,6 +1602,32 @@ fn is_placed_texture(view: &View) -> bool { matches!(view, View::Placed(_, resource, _) if resource[0] != 1) } +/// Makes what a host view of `view` needs, if it is not made yet: the +/// texture it views (made on first use) or the host copy of the buffer +/// memory it views. The slot's view is then quick to make. +fn prepare(view: &View) { + #[cfg(test)] + tests::while_preparing(); + match view { + View::Placed(..) if is_placed_texture(view) => { + let _ = placed_texture(view); + } + View::Shader(r, _) | View::Unordered(r, _, _) if crate::resource::texture_memory(*r as crate::object::This).is_some() => { + let _ = crate::resource::host_resource(*r as crate::object::This); + } + _ => { + let _ = view_copy(view); + } + } +} + +/// Whether `view` is a shader view of a texture (one placed in memory, or a +/// resource object's): such a slot left null is made when read. +fn is_texture(view: &View) -> bool { + is_placed_texture(view) + || matches!(view, View::Shader(r, _) if crate::resource::texture_memory(*r as crate::object::This).is_some()) +} + /// A shader view of a texture the title placed in memory itself, as a view /// of the resource made for that memory (on first use). pub(crate) fn placed_texture(view: &View) -> Option { @@ -1530,6 +1812,268 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// Typed buffer views of integer formats carry their kind in the + /// view-stride table; float, normalized, raw and structured ones none. + #[test] + fn integer_typed_buffer_views_are_marked_in_the_stride_table() { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + // Format, dimension (buffer), first element, count, stride, counter, flags. + let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0])); + assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT"); + assert_eq!(view_kind(&uav(57, 0, 0)), VIEW_INTEGER, "R16_UINT"); + assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT"); + assert_eq!(view_kind(&uav(64, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R8_SINT"); + assert_eq!(view_kind(&uav(10, 0, 0)), 0, "R16G16B16A16_FLOAT"); + assert_eq!(view_kind(&uav(58, 0, 0)), 0, "R16_SNORM"); + assert_eq!(view_kind(&uav(39, 0, 1)), 0, "raw"); + assert_eq!(view_kind(&uav(0, 16, 0)), 0, "structured"); + // Format, dimension, mapping, first element, count, stride, flags. + let srv = View::Shader(0, Some([62, 1, 5768, 0, 0, 0, 64, 0, 0, 0])); + assert_eq!(view_kind(&srv), VIEW_INTEGER, "R8_UINT"); + assert_eq!(view_stride(&uav(12, 0, 0)) | view_kind(&uav(12, 0, 0)), 8 | VIEW_INTEGER); + } + + /// A placed texture's view the title writes into a heap is left null + /// and noted once: heap syncs (every submission) pass it by, a draw + /// reading it through a table makes it. + #[test] + fn a_placed_texture_slot_left_null_is_made_once_a_draw_reads_it() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, title_heap.start); + let host = title_heap.host().expect("a host view heap"); + for _ in 0..2 { + assert!(host.mirror(0, title_heap.start, false).is_some()); + assert!(host.made(0), "the record is noted"); + assert!(!host.kept(0), "no host texture for it yet"); + } + assert!(host.mirror(0, title_heap.start, true).is_some()); + assert!(host.kept(0), "made for the draw"); + } + + /// A slot viewing a texture given up (`crate::resource::evict`) holds it + /// no more: heap syncs pass it by, a draw reading it through a table + /// makes it again. + #[test] + fn a_slot_viewing_a_texture_given_up_is_made_again_when_read() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, title_heap.start); + let host = title_heap.host().expect("a host view heap"); + assert!(host.mirror(0, title_heap.start, true).is_some()); + assert!(host.kept(0), "made for the draw"); + let texture = crate::resource::texture_at(address, &words).expect("its resource"); + assert!(crate::resource::give_up_now(texture)); + assert!(!host.kept(0), "the slot holds it no more"); + assert!(host.made(0), "its record stays noted"); + assert!(host.mirror(0, title_heap.start, false).is_some()); + assert!(!host.kept(0), "heap syncs pass it by"); + assert!(host.mirror(0, title_heap.start, true).is_some()); + assert!(host.kept(0), "made again for the draw"); + assert!(crate::resource::made_copy(texture).is_some(), "with a host texture again"); + } + + /// Work to run while a view's texture is prepared, once (tests). + pub(crate) static WHILE_PREPARING: std::sync::Mutex> = std::sync::Mutex::new(None); + + pub(crate) fn while_preparing() { + let work = WHILE_PREPARING.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(work) = work { + work(); + } + } + + /// A record the title writes into a slot while another thread prepares + /// the slot's old record is the one the slot ends up viewing. + #[test] + fn a_slot_rewritten_while_its_view_is_prepared_views_the_new_record() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 1024, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let s = 960u32; + let at = title_heap.start + u64::from(s) * 32; + let memory = vec![0u8; 1 << 17]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let view_of = |address: u64| { + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + view + }; + let (first, second) = (memory.as_ptr() as u64, memory.as_ptr() as u64 + (1 << 16)); + crate::descriptor::create_placed_srv(null, &words, &view_of(first), at); + let host = title_heap.host().expect("a host view heap"); + let (done, waited) = std::sync::mpsc::channel(); + let second_view = view_of(second); + *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + // The title writes the other record into the slot meanwhile. + std::thread::spawn(move || { + crate::descriptor::create_placed_srv(std::ptr::null(), &words, &second_view, at); + done.send(()).unwrap(); + }); + assert!(waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), "the write waits"); + })); + // A draw reads the slot: its first record is prepared. + assert!(host.mirror(s, at, true).is_some()); + let second_texture = crate::resource::texture_at(second, &words).expect("its resource"); + let raw = windows::core::Interface::as_raw(&crate::resource::made_copy(second_texture).expect("made").texture) as usize; + assert_eq!(host.textures_at(&[s]), [raw], "the slot views the record written last"); + } + + /// What a view needs is made without the slot lock: another thread + /// binding a view of the same heap meanwhile is not held up. + #[test] + fn views_bound_while_another_slot_gets_its_texture_do_not_wait() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 1024, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let (first, second) = (950u32, 951u32); + let memory = vec![0u8; 1 << 17]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let slot = |i: u32| title_heap.start + u64::from(i) * 32; + for (i, at) in [(first, 0u64), (second, 1 << 16)] { + let address = memory.as_ptr() as u64 + at; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, slot(i)); + } + let host = title_heap.host().expect("a host view heap"); + let heap_at = title_heap.start; + let heap = heap as usize; + let (done, waited) = std::sync::mpsc::channel(); + *WHILE_PREPARING.lock().unwrap() = Some(Box::new(move || { + std::thread::spawn(move || { + let h = crate::descriptor::heap(heap as crate::object::This); + h.host().unwrap().mirror(second, heap_at + u64::from(second) * 32, true); + done.send(()).unwrap(); + }); + assert!( + waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), + "a view bound while another slot's texture is made waits" + ); + })); + assert!(host.mirror(first, slot(first), true).is_some()); + assert!(WHILE_PREPARING.lock().unwrap().is_none(), "the prepare ran"); + assert!(host.kept(first) && host.kept(second), "both made"); + } + + /// The textures of slots shaders read are made without the heaps' lock: + /// a title thread writing a view meanwhile is not held up by the make. + #[test] + fn views_written_while_read_slots_get_their_textures_do_not_wait() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 1024, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let (read, written) = (900u32, 901u32); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + let slot = |i: u32| title_heap.start + u64::from(i) * 32; + crate::descriptor::create_placed_srv(null, &words, &view, slot(read)); + let host = title_heap.host().expect("a host view heap"); + assert!(!host.kept(read), "left null until read"); + let (done, waited) = std::sync::mpsc::channel(); + let at = slot(written); + *crate::descriptor::tests::WHILE_MAKING.lock().unwrap() = Some(( + read, + Box::new(move || { + std::thread::spawn(move || { + crate::descriptor::create_placed_srv(std::ptr::null(), &words, &view, at); + done.send(()).unwrap(); + }); + assert!( + waited.recv_timeout(std::time::Duration::from_secs(5)).is_ok(), + "a view written while a read slot's texture is made waits" + ); + }), + )); + crate::descriptor::make_read(&[read]); + assert!(crate::descriptor::tests::WHILE_MAKING.lock().unwrap().is_none(), "the make ran"); + assert!(host.kept(read), "made for the read"); + } + + /// A heap sync makes the slots whose records the title changed as bytes + /// (a copy of another slot's record, a record cleared) and passes the + /// others by. + #[test] + fn heap_syncs_make_the_slots_whose_records_changed() { + if host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let start = title_heap.start; + // A view of no memory: a view of the test's own heap memory would get + // a host copy whose 4 MiB window the guards may cover (the process + // heap guarded read-only hung the suite). + crate::descriptor::create_cbv(null, &[0, 0, 256, 0], start); + let host = title_heap.host().expect("a host view heap"); + // SAFETY: slots 0 and 1 of the heap's memory, 32 bytes each. + unsafe { std::ptr::copy_nonoverlapping(start as *const u8, (start + 32) as *mut u8, 32) }; + assert!(!host.made(1), "copied as bytes: not seen yet"); + host.sync_slots(0, 4, start, 32); + assert!(host.made(0) && host.made(1) && !host.made(2)); + // SAFETY: as above. + unsafe { std::ptr::write_bytes((start + 32) as *mut u8, 0, 32) }; + host.sync_slots(0, 4, start, 32); + assert!(host.made(0) && !host.made(1), "a cleared record leaves its slot"); + } + /// The world's 16-byte view of 0 elements removed the device. #[test] fn empty_and_overlong_buffer_views_are_refused() { @@ -1662,6 +2206,11 @@ mod tests { heap.make_null(slot); assert!(references(&buffer) >= 2, "the slot's, retired"); crate::host::release_retired(); + // Released on a thread of its own. + let since = std::time::Instant::now(); + while references(&buffer) > 1 && since.elapsed() < std::time::Duration::from_secs(5) { + std::thread::yield_now(); + } assert_eq!(references(&buffer), 1, "ours"); } let a = heap.dynamic(heap.dynamic - 100).unwrap(); @@ -1700,4 +2249,30 @@ mod tests { heap.release(last, 1); assert_eq!(heap.dynamic(2), None); } + + /// A texture view's size words are the console image descriptor's + /// fields: level 0's size of the resource, the view's levels, its type. + #[test] + fn a_texture_view_gives_its_image_descriptor_size_fields() { + // A 1000x600 2D texture of 10 levels, then an array of 6 with the + // whole chain (mip count 0, 1024 wide: 11 levels). + let mut texture = [0u32; 14]; + (texture[0], texture[4], texture[6], texture[7], texture[9]) = (3, 1000, 600, 1 | 10 << 16, 1); + let mut array = texture; + (array[4], array[7]) = (1024, 6); + let mut view = [0u32; 10]; + // Levels 2-4 of the texture: width - 1 = 999 (0b11_1110_0111). + (view[1], view[4], view[5]) = (4, 2, 3); + let words = image_words(&texture, Some(&view), false); + assert_eq!(words, [0, 3 << 30, 249 | 599 << 14, 0xFAC | 2 << 12 | 4 << 16 | 9 << 28]); + // Its whole chain from level 1. + (view[4], view[5]) = (1, u32::MAX); + assert_eq!(image_words(&texture, Some(&view), false)[3], 0xFAC | 1 << 12 | 9 << 16 | 9 << 28); + // An unordered view of level 3: that level alone. + let uav = [0, 4, 0, 0, 3, 0, 0, 0, 0, 0]; + assert_eq!(image_words(&texture, Some(&uav), true)[3], 0xFAC | 3 << 12 | 3 << 16 | 9 << 28); + // The array's own view: a 2D array, levels 0-10. + let words = image_words(&array, None, false); + assert_eq!(words[1..], [3 << 30, 255 | 599 << 14, 0xFAC | 10 << 16 | 13 << 28]); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index afeba2dca6..124e454664 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -89,6 +89,21 @@ pub(crate) struct State { /// slot, end): taken [`ROOT_VIEW_RUN`] at a time, so that single slots /// do not break up the runs fresh tables need. root_run: (usize, u32, u32), + /// What was set straight onto the host list, for the next segment of + /// the list ([`State::cut`]). + fixed: Fixed, +} + +/// Fixed-function state the title set, as it set it. +#[derive(Default)] +struct Fixed { + viewports: Option>, + scissors: Option>, + blend_factor: Option>, + stencil_ref: Option, + /// Render target and depth view handles. + targets: Option<(Vec, u64)>, + topology: bool, } impl Drop for State { @@ -153,7 +168,7 @@ fn dropped(list: &HostList, pipeline: usize, kind: &str) { if why.is_empty() || crate::pipeline::host_pipeline(pipeline as This).is_none() { crate::pipeline::note_drop(pipeline as This); } else { - crate::pipeline::note_why(format!("{kind}: {why}")); + crate::pipeline::note_why(format!("{kind}: {why} {}", crate::pipeline::shaders_of(pipeline as This))); } list.note_op(|| format!("DROPPED {kind} ({why}) {}", crate::pipeline::shaders_of(pipeline as This))); if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() { @@ -233,6 +248,7 @@ impl State { /// [`crate::primitive`]). pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; + self.fixed.topology = true; let host = match topology { RECTANGLES => 4, TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { @@ -252,6 +268,73 @@ impl State { self.pipeline = pipeline as usize; } + /// Fixed-function state, straight onto the host list (and kept for the + /// list's next segment). + pub(crate) fn viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + self.fixed.viewports = Some(viewports.to_vec()); + // SAFETY: an open list. + unsafe { list.list.RSSetViewports(viewports) }; + } + + pub(crate) fn scissors(&mut self, list: &HostList, rects: &[RECT]) { + self.fixed.scissors = Some(rects.to_vec()); + // SAFETY: an open list. + unsafe { list.list.RSSetScissorRects(rects) }; + } + + pub(crate) fn blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) { + self.fixed.blend_factor = Some(factor.copied()); + // SAFETY: an open list. + unsafe { list.list.OMSetBlendFactor(factor) }; + } + + pub(crate) fn stencil_ref(&mut self, list: &HostList, reference: u32) { + self.fixed.stencil_ref = Some(reference); + // SAFETY: an open list. + unsafe { list.list.OMSetStencilRef(reference) }; + } + + /// The title list goes on in a fresh host list (a segment after a wait, + /// `crate::list`): the state it set is given to `list` again. + /// + /// Replayed: topology, viewports, scissors, blend factor, stencil + /// reference, render targets and depth (set at once); heaps, root + /// signatures, pipelines, root arguments, vertex and index buffers are + /// set by the next draw or dispatch from what this state holds (the + /// host caches are cleared). Made again in the new segment, so their + /// submission-time work (refreshes, uploads) runs with it: fresh tables, + /// root views and the title-memory page table. Not replayed, as nothing + /// of it is on the host list: depth bounds and shading rate (ignored), + /// queries (resolved with plain values), the 0x4a0 upload memory (the + /// title list's own), texture states and twins (each segment has its + /// own, made from the real states at its submission). Clears and copies + /// are commands, recorded once in the segment they belong to. + pub(crate) fn cut(&mut self, list: &HostList) { + self.host_state_lost(); + self.fresh_tables.clear(); + self.root_slots.clear(); + self.memory = None; + let fixed = std::mem::take(&mut self.fixed); + if fixed.topology { + self.set_topology(list, self.topology); + } + if let Some(v) = &fixed.viewports { + self.viewports(list, v); + } + if let Some(r) = &fixed.scissors { + self.scissors(list, r); + } + if let Some(f) = fixed.blend_factor { + self.blend_factor(list, f.as_ref()); + } + if let Some(s) = fixed.stencil_ref { + self.stencil_ref(list, s); + } + if let Some((targets, depth)) = &fixed.targets { + self.set_targets(list, targets, *depth); + } + } + /// Others recorded into the host list (`crate::external`): its heaps, /// root signatures and pipeline are set again before the next draw or /// dispatch. @@ -321,6 +404,7 @@ impl State { /// Render targets and depth, set on the host list at once. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { + self.fixed.targets = Some((handles.to_vec(), depth)); let Some(host) = crate::host::host() else { return; }; @@ -371,7 +455,7 @@ impl State { self.depth = record.resource as usize; #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); - Some(host.dsv(texture, record.depth_desc().as_ref())) + Some(host.dsv(&texture, record.depth_desc().as_ref())) }); // SAFETY: an open list; the views were just made. unsafe { @@ -535,6 +619,9 @@ impl State { /// False if the draw or dispatch must not run: a table it reads could /// not be made. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + // What its shaders write is withheld only if the program uses title + // memory and a list using it misses (`crate::memory::withholding`). + let _writer = list.writer_uses_memory(p.stages.iter().any(|s| s.memory.is_some())); let l = &list.list; // A depth copy of ours (`crate::twin`) since the last one ran a // compute pipeline. @@ -580,7 +667,10 @@ impl State { 0 => crate::memory::heap(), h => crate::descriptor::heap(h as This).host(), }; - let (Some(table), Some(bitmap)) = (heap.and_then(|h| h.marks()), crate::shadow::view_writes()) else { + // Shaders using title memory mark in a bitmap of their own, held + // back while their results are (`crate::memory::withholding`). + let memory = p.stages.iter().any(|s| s.memory.is_some()); + let (Some(table), Some(bitmap)) = (heap.and_then(|h| h.marks()), crate::shadow::view_writes(memory)) else { once!("a shader marking its writes without a view heap: dropped"); not_run("write marks without a view heap"); return false; @@ -675,7 +765,10 @@ impl State { }; match offset { Some(offset) => offset, - None => return false, + None => { + not_run("a root view's offset: no root view, or outside title buffers"); + return false; + } } } None if is_root_view(u) => { @@ -817,10 +910,17 @@ impl State { fn root_view(&mut self, list: &HostList, compute: bool, slot: u8, uav: bool) -> Option<(u32, u32)> { let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set: dropped"); + not_run("a root view the title did not set"); + return None; + }; + let Some(shadow) = crate::shadow::find(address, 1) else { + not_run("a root view outside title buffers"); + return None; + }; + let Some(offset) = u32::try_from(shadow.offset(address)).ok() else { + not_run("a root view 4 GiB or more into its copy"); return None; }; - let shadow = crate::shadow::find(address, 1)?; - let offset = u32::try_from(shadow.offset(address)).ok()?; shadow.refresh(list, address, shadow.left(address)); if uav { // Writes through the view are marked wherever they land in the @@ -829,12 +929,16 @@ impl State { shadow.gpu_writes(list, address, len, true); } let (key, host) = match self.heaps[0] { - 0 => (MEMORY_HEAP, crate::memory::heap()?), + 0 => (MEMORY_HEAP, crate::memory::heap()), h => ( std::ptr::from_ref(crate::descriptor::heap(h as This)) as usize, - crate::descriptor::heap(h as This).host()?, + crate::descriptor::heap(h as This).host(), ), }; + let Some(host) = host else { + not_run("a root view without a host view heap"); + return None; + }; let copy = std::sync::Arc::as_ptr(&shadow) as usize; if let Some(&index) = self.root_slots.get(&(key, copy, uav)) { return Some((index, offset)); @@ -843,6 +947,7 @@ impl State { if run_heap != key || next >= end { let Some(first) = host.dynamic(ROOT_VIEW_RUN) else { once!("no dynamic slots for root views: dropped"); + not_run("no dynamic slots for root views"); return None; }; self.dynamic.push((key, first, ROOT_VIEW_RUN)); @@ -1375,7 +1480,7 @@ impl State { // SAFETY: an open list. unsafe { list.list.ResourceBarrier(&[all]) }; crate::list::ensure_state(list, r as This, COPY_SOURCE); - let read = crate::capture::read_back(&host.device, &list.list, t); + let read = crate::capture::read_back(&host.device, &list.list, &t); crate::list::ensure_state(list, r as This, UNORDERED); let Some((buffer, f)) = read else { continue }; list.keep(&buffer); @@ -1664,10 +1769,10 @@ impl State { s.refresh(list, *at, 4); } // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { + let Some(clamped) = crate::indirect::bound(list, args.gpu(arguments), (kind, stride, max)) else { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; - } + }; self.host_pipeline = 0; self.host_roots[1] = 0; let ran = match kind { @@ -1685,7 +1790,7 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &args.buffer); + crate::indirect::done(list, &clamped); #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => { @@ -1711,20 +1816,25 @@ impl State { list.list.ExecuteIndirect( &signature, max, - &args.buffer, - args.offset(arguments), + &clamped, + 0, counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - // A listed frame: what the records held (after the clamp). + // A listed frame, or any frame for a traced shader: what the records + // held (after the clamp). #[cfg(feature = "diagnostics")] - if crate::capture::dump_on() { - let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); - let name = crate::pipeline::shaders_of(pipeline); - crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name); + { + let always = !crate::host::traced_shaders().is_empty() + && crate::host::is_traced(&crate::pipeline::shaders_of(pipeline)); + if always || crate::capture::dump_on() { + let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + let name = crate::pipeline::shaders_of(pipeline); + crate::capture::read_indirect(list, (&clamped, 0), count, (kind, stride, max), name, always); + } } - crate::indirect::done(list, &args.buffer); + crate::indirect::done(list, &clamped); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { @@ -1810,9 +1920,9 @@ fn readable(list: &HostList, u: &UsedResource, view: &View, marked: bool) { match (view, u.kind) { (View::Shader(resource, _), ResourceType::Srv) => { if let Some(t) = crate::resource::host_resource(*resource as This) - && crate::texture::title_written(t) + && crate::texture::title_written(&t) { - crate::texture::upload(list, *resource as This, t); + crate::texture::upload(list, *resource as This, &t); } crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE); #[cfg(feature = "diagnostics")] @@ -1916,27 +2026,6 @@ const LINE_LOOP: u32 = 18; const QUADS: u32 = 19; const QUAD_STRIP: u32 = 20; -/// Fixed-function state, straight onto the host list. -pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { - // SAFETY: an open list. - unsafe { list.list.RSSetViewports(viewports) }; -} - -pub(crate) fn scissors(list: &HostList, rects: &[RECT]) { - // SAFETY: an open list. - unsafe { list.list.RSSetScissorRects(rects) }; -} - -pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { - // SAFETY: an open list. - unsafe { list.list.OMSetBlendFactor(factor) }; -} - -pub(crate) fn stencil_ref(list: &HostList, reference: u32) { - // SAFETY: an open list. - unsafe { list.list.OMSetStencilRef(reference) }; -} - #[cfg(test)] mod tests { use super::*; @@ -2006,6 +2095,128 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// Which pixels of a 64x64 host D32S8 `texture` (title texture `depth`) + /// pass an EQUAL depth test against a square (two triangles, as the + /// title's rectangles become) drawn over pixel `k - 1` (row by row) with + /// z = k times the title's 1/65535 (`0x37800080`), the depth + /// `VS_TiledLighting` gives draw k: entry `k - 1`. + fn equal_test_passes(depth: This, texture: &ID3D12Resource) -> Vec { + use windows::Win32::Graphics::Dxgi::Common::*; + const SOURCE: &str = r#" +#define RS "RootFlags(0)" +static const float2 CORNERS[6] = { float2(0, 0), float2(1, 0), float2(0, 1), float2(1, 0), float2(1, 1), float2(0, 1) }; +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID) : SV_Position { + uint i = v / 6; + float2 p = float2(i % 64, i / 64) + CORNERS[v % 6]; + return float4(p.x / 32.0 - 1.0, 1.0 - p.y / 32.0, (float)(i + 1) * asfloat(0x37800080), 1.0); +} +uint ps() : SV_Target { return 1; } +"#; + let host = crate::host::host().unwrap(); + let blob = |entry: windows::core::PCSTR, target: windows::core::PCSTR| { + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("equal"), None, None, entry, target, 0, 0, &mut code, None) }.unwrap(); + code.unwrap() + }; + let (vs, ps) = (blob(s!("vs"), s!("vs_5_1")), blob(s!("ps"), s!("ps_5_1"))); + // SAFETY: the blobs' own bytes. + let bytes = |b: &ID3DBlob| unsafe { D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), BytecodeLength: b.GetBufferSize() } }; + // SAFETY: a compiled shader with its root signature inside. + let root: ID3D12RootSignature = unsafe { + host.device.CreateRootSignature(0, std::slice::from_raw_parts(vs.GetBufferPointer().cast::(), vs.GetBufferSize())) + } + .unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed for the call. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: bytes(&vs), + PS: bytes(&ps), + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + DSVFormat: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R32_UINT; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = true.into(); + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL; + // SAFETY: a complete description. + let pso: ID3D12PipelineState = unsafe { host.device.CreateGraphicsPipelineState(&desc) }.unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut target: Option = None; + // SAFETY: plain creation. + unsafe { + host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut target) + } + .unwrap(); + let target = target.unwrap(); + let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + // SAFETY: outputs for one subresource. + unsafe { host.device.GetCopyableFootprints(&target_desc, 0, 1, 0, Some(&mut f), None, None, Some(&mut total)) }; + let (raw, data) = host.shared_buffer(total).unwrap(); + let list = host.new_list().unwrap(); + crate::list::ensure_state(&list, depth, 0x10); + let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let (rtv, dsv) = (host.rtv(&target, None), host.dsv(texture, Some(&dsv))); + // SAFETY: an open list; the target in the render target state, the + // depth texture in the depth write state; copies into our buffer. + unsafe { + let l = &list.list; + l.ClearRenderTargetView(rtv, &[0.0; 4], None); + l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + l.RSSetViewports(&[D3D12_VIEWPORT { Width: 64.0, Height: 64.0, MaxDepth: 1.0, ..Default::default() }]); + l.RSSetScissorRects(&[windows::Win32::Foundation::RECT { right: 64, bottom: 64, ..Default::default() }]); + l.SetGraphicsRootSignature(&root); + l.SetPipelineState(&pso); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.DrawInstanced(64 * 64 * 6, 1, 0, 0); + l.ResourceBarrier(&[crate::host::transition(&target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&raw), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + list.close(); + host.execute(&[&list]); + (0..64 * 64) + .map(|i| { + // SAFETY: inside the mapped buffer, by the footprint. + unsafe { (data.add(f.Offset as usize + (i / 64) * f.Footprint.RowPitch as usize + (i % 64) * 4) as *const u32).read() == 1 } + }) + .collect() + } + /// A title buffer of `bytes` in memory of its own. fn buffer(bytes: u64) -> This { let desc: [u32; 14] = [1, 0, 0, 0, bytes as u32, (bytes >> 32) as u32, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; @@ -2283,12 +2494,273 @@ void main(uint3 id : SV_DispatchThreadID) { } } + /// A texture the title wrote, read through tables by two lists of one + /// submission, is uploaded once; the next submission uploads it again + /// only after the title writes it (run perf7 uploaded the same textures + /// up to 24 times a frame). + #[test] + fn a_texture_is_uploaded_once_per_submission_and_only_when_written() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // Runtime memory the change journal follows; RGBA8 64x64, linear. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let submit = |byte: Option| { + if let Some(byte) = byte { + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, byte, 64 * 64 * 4) }; + } + let lists = [host.new_list().unwrap(), host.new_list().unwrap()]; + for list in &lists { + readable(list, &used(ResourceType::Srv), &view, false); + run(list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + } + let before = crate::texture::uploads(object); + host.execute(&[&lists[0], &lists[1]]); + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::uploads(object) - before, texel[0]) + }; + let (n, x) = submit(Some(0x40)); + assert_eq!(n, 1, "one upload for two lists"); + assert!((x - 64.0 / 255.0).abs() < 1e-6); + assert_eq!(submit(None).0, 0, "not written: not uploaded"); + let (n, x) = submit(Some(0x80)); + assert_eq!(n, 1, "written: uploaded again"); + assert!((x - 128.0 / 255.0).abs() < 1e-6); + assert_eq!(submit(Some(0x80)).0, 0, "the same bytes in a shared page: not uploaded"); + } + + /// A list recorded before another whose host copy writes a texture it + /// reads, but run after it, reads the host's texels: whether its upload + /// from title memory is still due is decided when its submission is + /// made, after the writing list's (`texture::host_writes`), not when it + /// was recorded. + #[test] + fn a_list_run_after_a_host_write_keeps_the_host_texels() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // Runtime memory the change journal follows; RGBA8 64x64, linear. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let reading = || { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + list + }; + // SAFETY: inside the mapped output. + let texel = || unsafe { (data as *const [f32; 4]).read() }[0]; + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + let write = |byte: u8| unsafe { std::ptr::write_bytes(address as *mut u8, byte, 64 * 64 * 4) }; + write(0x40); + host.execute(&[&reading()]); + assert!((texel() - 64.0 / 255.0).abs() < 1e-6, "uploaded: {}", texel()); + // The title writes the memory again and a list reading the texture + // is recorded: its upload is due. + write(0x80); + let late = reading(); + // A list recorded after it, holding a host copy into the texture + // (its mark; what it copies is the host's business), runs first. + let copying = host.new_list().unwrap(); + crate::texture::host_writes(©ing, object); + copying.close(); + host.execute(&[©ing]); + host.execute(&[&late]); + assert!( + (texel() - 64.0 / 255.0).abs() < 1e-6, + "the host's texels kept, not title memory uploaded over them: {}", + texel() + ); + } + + /// A texture fed from title memory given up (`resource::evict`) while a + /// recorded list names it: the list still reads it, and the next use + /// makes it again with its bytes from title memory. + #[test] + fn a_texture_given_up_is_made_again_with_its_bytes_and_recorded_lists_keep_it() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, 64 * 64 * 4) }; + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + let record = || { + slots.make(0, &view); + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + list + }; + // SAFETY: inside the mapped output. + let texel = || unsafe { (data as *const [f32; 4]).read() }[0]; + let list = record(); + assert!(crate::resource::give_up_now(object), "fed from title memory"); + assert!(crate::resource::made_copy(object).is_none(), "its title texture let go"); + host.execute(&[&list]); + assert!((texel() - 64.0 / 255.0).abs() < 1e-6, "the recorded list read it"); + // SAFETY: inside the mapped output. + unsafe { std::ptr::write_bytes(data, 0, 16) }; + let list = record(); + host.execute(&[&list]); + assert!((texel() - 64.0 / 255.0).abs() < 1e-6, "made again with its bytes"); + assert_eq!(crate::texture::uploads(object), 1, "uploaded into the new one"); + } + + /// Textures brought up in one submission share staging space (parts + /// of one upload buffer): each reads its own bytes. + #[test] + fn textures_uploaded_together_each_read_their_own_bytes() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let outs: Vec<_> = (0..2).map(|_| host.shared_buffer(64 * 64 * 16).unwrap()).collect(); + let pool = crate::watch::tests::pool(2); + let views: Vec = (0..2usize) + .map(|k| { + let address = (pool + k * crate::watch::PAGE) as u64; + // SAFETY: the texture's memory in our pool, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40 * (k as u8 + 1), 64 * 64 * 4) }; + let object = texture_at_address(address, &texture_words(64, 64, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + View::Shader(object as usize, Some(desc)) + }) + .collect(); + let lists: Vec<_> = (0..2usize) + .map(|k| { + slots.make(k as u32, &views[k]); + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &views[k], false); + run(&list, &slots, &read, k as u32, Some(&outs[k].0), (8, 8)); + list.close(); + list + }) + .collect(); + host.execute(&[&lists[0], &lists[1]]); + for (k, (_, data)) in outs.iter().enumerate() { + // SAFETY: inside the mapped output. + let texel = unsafe { (*data as *const [f32; 4]).read() }; + assert!((texel[0] - (0x40 * (k + 1)) as f32 / 255.0).abs() < 1e-6, "texture {k}: {}", texel[0]); + } + } + + /// A texture written in a page that holds only its own bytes is uploaded + /// without hashing them (a movie frame rewritten every frame), so even + /// the same bytes again are uploaded. + #[test] + fn a_texture_owning_its_pages_is_uploaded_on_any_write() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // RGBA8 128x128, linear: one whole 64 KiB page. + let address = crate::watch::tests::pool(1) as u64; + let object = texture_at_address(address, &texture_words(128, 128, 28, 0x100, 0)); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let view = View::Shader(object as usize, Some(desc)); + slots.make(0, &view); + let submit = |byte: u8| { + // SAFETY: the texture's memory, one page. + unsafe { std::ptr::write_bytes(address as *mut u8, byte, crate::watch::PAGE) }; + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + let before = crate::texture::uploads(object); + host.execute(&[&list]); + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::uploads(object) - before, texel[0]) + }; + assert_eq!(submit(0x40).0, 1); + assert_eq!(submit(0x40).0, 1, "its own page written: uploaded"); + let (n, x) = submit(0x80); + assert_eq!(n, 1); + assert!((x - 128.0 / 255.0).abs() < 1e-6, "a reused staging buffer carries the new bytes: {x}"); + } + + /// A title write into one mip of a texture uploads that mip alone (the + /// pages of the others did not change), and the others keep their + /// contents. + #[test] + fn a_write_into_one_mip_uploads_that_mip_alone() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let slots = Slots::new(2); + let read = compile_cs(READ); + let (out, data) = host.shared_buffer(64 * 64 * 16).unwrap(); + // RGBA8 512x512 with two mips, linear, in memory the journal follows. + let address = crate::watch::tests::pool(32) as u64; + let mut words = texture_words(512, 512, 28, 0x100, 0); + words[7] = 1 | 2 << 16; + let object = texture_at_address(address, &words); + let (_, desc) = crate::resource::texture_memory(object).unwrap(); + let layout = crate::resource::texture_layout(&desc).unwrap().planes[0].layout.clone(); + let mip1 = layout.mips[1].offset as usize; + // SAFETY: the texture's memory (its layout's size). + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, layout.size as usize) }; + let mut view = [0u32; 10]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 2]); + let view = View::Shader(object as usize, Some(view)); + slots.make(0, &view); + let submit = || { + let list = host.new_list().unwrap(); + readable(&list, &used(ResourceType::Srv), &view, false); + run(&list, &slots, &read, 0, Some(&out), (8, 8)); + list.close(); + let before = crate::texture::copied(object); + host.execute(&[&list]); + // SAFETY: inside the mapped output. + let texel = unsafe { (data as *const [f32; 4]).read() }; + (crate::texture::copied(object) - before, texel[0]) + }; + assert_eq!(submit().0, 2, "both mips at first"); + // SAFETY: mip 1's bytes (256x256 texels of 4 bytes). + unsafe { std::ptr::write_bytes((address as usize + mip1) as *mut u8, 0x80, 256 * 256 * 4) }; + let (n, x) = submit(); + assert_eq!(n, 1, "mip 1 alone"); + assert!((x - 64.0 / 255.0).abs() < 1e-6, "mip 0 kept: {x}"); + } + /// A depth texture with stencil (the console's 16-bit depth, the - /// host's 24-bit) written through unordered views of its planes, then - /// read as depth and stencil: the 16-bit depth arrives in 24 bits as - /// the host converts the same value, the stencil as written. Rendered - /// as depth (a clear), then used through the unordered view: back in - /// 16 bits. + /// host's 32-bit float) written through unordered views of its planes, + /// then read as depth and stencil: the 16-bit depth arrives as the + /// float the title's shaders compute for it, the stencil as written, + /// and a draw at that depth passes an EQUAL test. Rendered as depth (a + /// clear), then used through the unordered view: back in 16 bits. #[test] fn a_depth_texture_written_through_unordered_views_reads_as_depth() { let Some(host) = crate::host::host() else { @@ -2375,7 +2847,8 @@ void main(uint3 id : SV_DispatchThreadID) { } list.close(); host.execute(&[&list]); - let d24 = |u: u32| u * 256 + (u * 255 + 32767) / 65535; + // The title's float for 16-bit value u (its 1/65535 is 0x37800080). + let float = |u: u32| (u as f32 * f32::from_bits(0x3780_0080)).to_bits(); for (x, y) in [(0usize, 0usize), (5, 0), (63, 2), (17, 40), (63, 63)] { let k = (1 + x + 64 * y) as u32; // SAFETY: inside the mapped buffers. @@ -2390,15 +2863,22 @@ void main(uint3 id : SV_DispatchThreadID) { raw_data.add(f[1].Offset as usize + y * f[1].Footprint.RowPitch as usize + x).read(), ) }; - assert_eq!(word & 0xff_ffff, d24(k), "24-bit depth at {x},{y}"); + assert_eq!(word, float(k), "depth at {x},{y}"); assert_eq!(u32::from(byte), ((x ^ y) & 0xff) as u32); } + // Tested EQUAL against a point at the depth the title's tiled + // lighting gives value k (k times its 1/65535), as the console's + // 16-bit depth passes it for every k. In 24-bit depth on the RX 6700 + // XT only k = 258 of 1..=4096 passed. + let passed = equal_test_passes(depth, ©.texture); + let failed: Vec = (1..=4096).filter(|&k| !passed[k as usize - 1]).collect(); + assert!(failed.is_empty(), "EQUAL fails at {failed:?}"); // Rendered as depth (a clear of both planes), then used through // the unordered view: copied to the twin, converted back. list.reset(); crate::list::ensure_state(&list, depth, 0x10); let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D24_UNORM_S8_UINT, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT_S8X24_UINT, ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; @@ -2540,7 +3020,7 @@ void main(uint3 id : SV_DispatchThreadID) { unsafe { made.GetDesc() }.Width }; assert_eq!(width(start + 456), 1 << 16, "on an element: the buffer's copy"); - assert_eq!(width(start + 100), (4 * 456u64).next_multiple_of(256), "off: its own bytes"); + assert_ne!(width(start + 100), 1 << 16, "off: a copy of its own bytes (in a shared buffer)"); let (copy, address, len) = crate::descriptor::host::view_copy(&view(start + 100)).unwrap(); assert_eq!((copy.range(), address, len), ((start + 100, 4 * 456), start + 100, 4 * 456)); drop(copy); diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 64f9de41ee..00325b17f9 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -1,5 +1,5 @@ -//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a -//! GPU yet, so only signals (the title's, later our queues') move one. +//! Fences: a 64-bit value and the events waiting for it, moved by the +//! title's Signals and its queues' (once the work before them has run). #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::c_void; @@ -35,8 +35,9 @@ struct Fence { /// address. value: AtomicU64, flags: u32, - /// Events to set once the value reaches theirs (handles as integers). - waiters: Mutex>, + /// Events to set once the value reaches theirs (handles as integers), + /// and since when. + waiters: Mutex>, } fn fence<'a>(this: This) -> &'a Fence { @@ -83,9 +84,12 @@ extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } extern "system" fn completed(this: This) -> u64 { + // A title polling for a value: held work that may run now does first. + crate::queue::pump_held_if_free(crate::queue::Why::Fence); fence(this).value.load(Ordering::Acquire) } extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { + crate::queue::pump_held_if_free(crate::queue::Why::Fence); let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); if fence.value.load(Ordering::Acquire) >= value { @@ -100,23 +104,60 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c tracing::warn!(value, "blocking fence wait not implemented"); return E_NOTIMPL; } - waiters.push((value, event as usize)); + waiters.push((value, event as usize, std::time::Instant::now())); S_OK } -pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { +/// The title's Signal from the CPU: what queues hold behind a Wait for it +/// may run now (`crate::hold`). +extern "system" fn signal(this: This, value: u64) -> HRESULT { + let hr = set(this, value); + crate::queue::pump_held(crate::queue::Why::Fence); + hr +} + +/// Moves a fence to `value` and wakes the events waiting for it (a queue's +/// Signal, when the work before it has run). +pub(crate) fn set(this: This, value: u64) -> HRESULT { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); - waiters.retain(|&(wanted, event)| { + waiters.retain(|&(wanted, event, since)| { let reached = wanted <= value; if reached { set_event(event); + WAITED.0.fetch_add(1, Ordering::Relaxed); + WAITED.1.fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed); } !reached }); S_OK } +/// Events the title waited on for a fence value, and their summed waits in +/// microseconds (the held-work frame line: work held back shows here as the +/// title's own waits). +static WAITED: (AtomicU64, AtomicU64) = (AtomicU64::new(0), AtomicU64::new(0)); + +/// Events set since the last call and how long they waited, summed. +pub(crate) fn take_waited() -> (u64, std::time::Duration) { + let n = WAITED.0.swap(0, Ordering::Relaxed); + (n, std::time::Duration::from_micros(WAITED.1.swap(0, Ordering::Relaxed))) +} + +/// A fence's value. +pub(crate) fn value(this: This) -> u64 { + fence(this).value.load(Ordering::Acquire) +} + +/// Keeps a fence alive while a queue holds a Signal of it, until +/// [`let_go`]. +pub(crate) fn keep(this: This) { + object::add_ref(this); +} +pub(crate) fn let_go(this: This) { + release(this); +} + extern "system" fn creation_flags(this: This) -> u32 { fence(this).flags } diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index c87cff85b1..4a68b3533f 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -92,11 +92,17 @@ fn last(kind: u32) -> &'static AtomicU64 { &LAST[(kind as usize).min(LAST.len() - 1)] } -/// The next tick after now and after the last one a wait for `kind` took -/// (an event happens once per tick: a wait woken a little early must not -/// let the next one end on the same tick), and how long until it. A wait -/// that comes within `limit` takes the tick here, under the clock's lock, -/// so two threads waiting for one kind never take the same tick. +/// The tick a wait for `kind` ends on, and how long until it: the first +/// one after the last a wait for `kind` took (an event happens once per +/// tick: a wait woken a little early must not let the next one end on the +/// same tick), the latest one passed if that is later. A wait begun after +/// its tick passed (a frame slower than the interval) so ends at once, as +/// an event signalled at the tick and left signalled until a wait takes it +/// would (assumed: nothing we have says what a late wait does); waiting for +/// the next tick instead cost the cutscene's frames 0-33 ms each (4 % of +/// the frame thread, run perf3). A wait that +/// comes within `limit` takes the tick here, under the clock's lock, so two +/// threads waiting for one kind never take the same tick. fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { @@ -106,8 +112,7 @@ fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { }); let elapsed = c.start.elapsed().as_nanos(); let interval = c.interval.as_nanos().max(1); - let tick = - (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); + let tick = (c.first + (elapsed / interval) as u64).max(last(kind).load(Ordering::Relaxed) + 1); let at = u128::from(tick - c.first) * interval; let wait = Duration::from_nanos(at.saturating_sub(elapsed) as u64); if wait <= limit { @@ -140,6 +145,13 @@ pub(crate) extern "system" fn wait( std::thread::sleep(wait); S_OK }; + #[cfg(feature = "diagnostics")] + { + WAITS[0].fetch_add(1, Ordering::Relaxed); + if hr == S_OK && wait.is_zero() { + WAITS[1].fetch_add(1, Ordering::Relaxed); + } + } // A frame begun on a time-out takes no tick: its flip still does. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { // Tokens count frames (consecutive), not ticks. @@ -163,6 +175,29 @@ pub(crate) extern "system" fn wait( hr } +/// Diagnostics: frame waits, and those that ended at once (their tick had +/// passed); presents whose flip tick was the previous present's. +#[cfg(feature = "diagnostics")] +static WAITS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +#[cfg(feature = "diagnostics")] +static PRESENT_TICK: AtomicU64 = AtomicU64::new(0); + +/// Diagnostics: a frame was presented (counts presents sharing a flip tick). +#[cfg(feature = "diagnostics")] +pub(crate) fn presented() { + let flip = LAST[2].load(Ordering::Relaxed); + if flip != 0 && PRESENT_TICK.swap(flip, Ordering::Relaxed) == flip { + WAITS[2].fetch_add(1, Ordering::Relaxed); + } +} + +/// Diagnostics: logs [`WAITS`] since the last call. +#[cfg(feature = "diagnostics")] +pub(crate) fn log() { + let [waits, at_once, shared] = [0, 1, 2].map(|i| WAITS[i].swap(0, Ordering::Relaxed)); + tracing::info!("frame waits: {waits}, {at_once} of them ended at once; presents sharing a flip tick: {shared}"); +} + /// Device method: no statistics are kept, so none are returned. pub(crate) extern "system" fn statistics( _: This, @@ -228,6 +263,16 @@ mod tests { // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP, Duration::ZERO); assert!(tick > flips[3]); + // A flip wait begun after its tick passed (two ticks missed) ends at + // once, on the latest tick passed; the next one waits for the next. + std::thread::sleep(Duration::from_millis(110)); + let before = Instant::now(); + assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK); + assert!(before.elapsed() < Duration::from_millis(10), "{:?}", before.elapsed()); + let late = LAST[2].load(Ordering::Relaxed); + assert!(late >= flips[3] + 2, "{late} after {}", flips[3]); + assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK); + assert_eq!(LAST[2].load(Ordering::Relaxed), late + 1); } /// Two waits for one kind that begin together (two threads) take two diff --git a/crates/victory-gpu/src/hold.rs b/crates/victory-gpu/src/hold.rs new file mode 100644 index 0000000000..efe249c737 --- /dev/null +++ b/crates/victory-gpu/src/hold.rs @@ -0,0 +1,442 @@ +//! Work a queue holds back (decision 0007, "Queues wait on memory values"). +//! +//! The console's lists wait on memory values (`Wait32BitValueX`, +//! `Wait64BitValueX`) that lists on other queues write at their end +//! (`Write32/64BitValueBottomOfPipeX`): Grand Theft Auto VI's four compute +//! queues start each list with a wait for the frame's value of a word that +//! a graphics list writes, and some lists wait again after their first +//! commands. Our submissions run to completion when the title makes them, +//! so a queue here is a FIFO of what the title submitted to it: segments of +//! lists (a list is cut where it waits after commands, `crate::list`), its +//! Signals and its fence Waits, in their order. The head of a queue runs +//! once its waits hold; consecutive heads that may run go to the host GPU +//! together (a piece); after every piece the heads of all queues are tested +//! again until none can move. Order within a queue never changes, only the +//! interleaving across queues. + +use std::collections::VecDeque; +use std::time::{Duration, Instant}; + +/// A wait for a memory value, as a list records it: the value at `address` +/// (`bytes` 4 or 8, the 32-bit form masked) compared with `reference` by a +/// D3D12 comparison function. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ValueWait { + pub(crate) address: u64, + pub(crate) bytes: u8, + pub(crate) comparison: u32, + pub(crate) reference: u64, + pub(crate) mask: u64, +} + +/// D3D12 comparison functions (`D3D12_COMPARISON_FUNC`). +const NEVER: u32 = 1; +const LESS: u32 = 2; +const EQUAL: u32 = 3; +const LESS_EQUAL: u32 = 4; +const GREATER: u32 = 5; +const NOT_EQUAL: u32 = 6; +const GREATER_EQUAL: u32 = 7; +const ALWAYS: u32 = 8; + +impl ValueWait { + /// Whether it holds with `read` giving the memory's value: `None` for a + /// comparison we do not know (counted by the caller, taken as holding) + /// and for memory that cannot be read (taken as not holding). + pub(crate) fn holds(&self, read: &dyn Fn(u64, u8) -> Option) -> Option { + if !(NEVER..=ALWAYS).contains(&self.comparison) { + return None; + } + let value = read(self.address, self.bytes)? & self.mask; + let reference = self.reference; + Some(match self.comparison { + NEVER => false, + LESS => value < reference, + EQUAL => value == reference, + LESS_EQUAL => value <= reference, + GREATER => value > reference, + NOT_EQUAL => value != reference, + GREATER_EQUAL => value >= reference, + _ => true, + }) + } +} + +/// What a queue holds, in its order. +pub(crate) enum Item { + /// A list segment and the waits at its start. + Segment(S, Vec), + /// A fence Signal: the fence and its value. + Signal(usize, u64), + /// A fence Wait: until the fence reaches the value. + FenceWait(usize, u64), +} + +/// What a pump did, for the frame's accounting. +#[derive(Default, Debug, PartialEq, Eq)] +pub(crate) struct Pumped { + /// Pieces given to the host GPU, and the segments in them. + pub(crate) pieces: u32, + pub(crate) segments: u32, + /// Of those, segments that had waited (not run when submitted): their + /// queue and how long. + pub(crate) waited: Vec<(usize, Duration)>, + /// Waits with a comparison we do not know (taken as holding). + pub(crate) unknown: u32, +} + +/// Every queue's held work. +pub(crate) struct Held { + queues: Vec<(usize, Fifo)>, +} + +/// A queue's items, each with when it was pushed and whether it is fresh +/// (not yet found waiting). +type Fifo = VecDeque<(Item, Instant, bool)>; + +impl Default for Held { + fn default() -> Self { + Self::new() + } +} + +impl Held { + pub(crate) const fn new() -> Self { + Held { queues: Vec::new() } + } +} + +/// What the pump needs from the outside world. +pub(crate) struct World<'a, S> { + /// A memory value (address, bytes). + pub(crate) read: &'a dyn Fn(u64, u8) -> Option, + /// A fence's value. + pub(crate) fence: &'a dyn Fn(usize) -> u64, + /// Runs a piece (a queue, its segments in order) to completion, the + /// bottom-of-pipe writes included. + pub(crate) run: &'a mut dyn FnMut(usize, Vec), + /// Signals a fence. + pub(crate) signal: &'a mut dyn FnMut(usize, u64), +} + +impl Held { + /// Appends `item` to `queue`'s FIFO, marked fresh: whether it waited is + /// decided by its first test. + pub(crate) fn push(&mut self, queue: usize, item: Item) { + let now = Instant::now(); + match self.queues.iter_mut().find(|(q, _)| *q == queue) { + Some((_, items)) => items.push_back((item, now, true)), + None => self.queues.push((queue, VecDeque::from([(item, now, true)]))), + } + } + + /// Runs every queue's heads that may run, until none can. + pub(crate) fn pump(&mut self, w: &mut World) -> Pumped { + let mut done = Pumped::default(); + loop { + let mut moved = false; + for (queue, items) in &mut self.queues { + let mut piece = Vec::new(); + loop { + let ready = match items.front_mut() { + None => false, + Some((Item::Segment(_, waits), since, fresh)) => { + let mut ok = true; + for wait in waits.iter() { + match wait.holds(w.read) { + Some(true) => {} + Some(false) => ok = false, + None => done.unknown += 1, + } + } + if !ok { + *fresh = false; + } else if !*fresh { + done.waited.push((*queue, since.elapsed())); + } + ok + } + // A Signal or Wait keeps its place: the piece before + // it runs first. + Some((Item::Signal(..), ..)) => { + if !piece.is_empty() { + (w.run)(*queue, std::mem::take(&mut piece)); + done.pieces += 1; + } + true + } + Some((Item::FenceWait(fence, value), _, fresh)) => { + let ok = (w.fence)(*fence) >= *value; + if !ok { + *fresh = false; + } + ok + } + }; + if !ready { + break; + } + moved = true; + match items.pop_front().map(|(item, ..)| item) { + Some(Item::Segment(s, _)) => { + piece.push(s); + done.segments += 1; + } + Some(Item::Signal(fence, value)) => (w.signal)(fence, value), + Some(Item::FenceWait(..)) | None => {} + } + } + if !piece.is_empty() { + (w.run)(*queue, piece); + done.pieces += 1; + } + } + if !moved { + break; + } + } + self.queues.retain(|(_, items)| !items.is_empty()); + done + } + + /// The queues still holding work: (queue, items, how long the head + /// waited, the head's waits that do not hold). + pub(crate) fn blocked(&self, read: &dyn Fn(u64, u8) -> Option) -> Vec<(usize, usize, Duration, Vec)> { + self.queues + .iter() + .filter_map(|(q, items)| { + let (head, since, _) = items.front()?; + let unmet = match head { + Item::Segment(_, waits) => waits.iter().filter(|w| w.holds(read) == Some(false)).copied().collect(), + _ => Vec::new(), + }; + Some((*q, items.len(), since.elapsed(), unmet)) + }) + .collect() + } + + /// Whether no queue holds anything. + pub(crate) fn is_empty(&self) -> bool { + self.queues.is_empty() + } + + /// Whether `queue` holds anything. + pub(crate) fn holds_work(&self, queue: usize) -> bool { + self.queues.iter().any(|(q, items)| *q == queue && !items.is_empty()) + } + + /// Releases work held longer than `limit` at the heads of blocked + /// queues, as if its waits held: the count of segments forced. + // shortcut: a safety valve against waits nothing will satisfy (a write + // we do not emulate), which would hold the title's fences back until + // its 30 s watchdog ends the run; remove once runs show it never fires. + pub(crate) fn force_older_than(&mut self, limit: Duration) -> Vec<(usize, Vec)> { + let mut forced = Vec::new(); + for (q, items) in &mut self.queues { + if let Some((Item::Segment(_, waits), since, _)) = items.front_mut() + && since.elapsed() >= limit + { + forced.push((*q, std::mem::take(waits))); + } + } + forced + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::collections::HashMap; + + /// Memory, fences and a log of what ran, for a recording executor. + #[derive(Default)] + struct Fake { + memory: HashMap, + fences: HashMap, + log: Vec, + /// Bottom-of-pipe writes of each segment: (address, value). + writes: HashMap<&'static str, Vec<(u64, u64)>>, + } + + fn ge(address: u64, reference: u64) -> ValueWait { + ValueWait { address, bytes: 8, comparison: GREATER_EQUAL, reference, mask: u64::MAX } + } + + fn pump(held: &mut Held<&'static str>, fake: &RefCell) -> Pumped { + let read = |a: u64, _| Some(*fake.borrow().memory.get(&a).unwrap_or(&0)); + let fence = |f: usize| *fake.borrow().fences.get(&f).unwrap_or(&0); + let mut run = |q: usize, segments: Vec<&'static str>| { + let mut f = fake.borrow_mut(); + for s in &segments { + for (a, v) in f.writes.get(s).cloned().unwrap_or_default() { + f.memory.insert(a, v); + } + } + f.log.push(format!("q{q}: {}", segments.join(" "))); + }; + let mut signal = |fence: usize, value: u64| { + let mut f = fake.borrow_mut(); + f.fences.insert(fence, value); + f.log.push(format!("signal {fence} {value}")); + }; + held.pump(&mut World { read: &read, fence: &fence, run: &mut run, signal: &mut signal }) + } + + #[test] + fn comparisons_test_the_masked_value() { + let read = |_, _| Some(0x1_0000_0005); + let w = |comparison, reference| ValueWait { address: 8, bytes: 4, comparison, reference, mask: 0xffff_ffff }; + let expect = [(NEVER, false), (LESS, false), (EQUAL, true), (LESS_EQUAL, true), (GREATER, false), (NOT_EQUAL, false), (GREATER_EQUAL, true), (ALWAYS, true)]; + for (cmp, holds) in expect { + assert_eq!(w(cmp, 5).holds(&read), Some(holds), "comparison {cmp}"); + } + assert_eq!(w(LESS, 6).holds(&read), Some(true)); + assert_eq!(w(GREATER, 4).holds(&read), Some(true)); + assert_eq!(w(0, 5).holds(&read), None, "unknown comparison"); + assert_eq!(w(9, 5).holds(&read), None); + assert_eq!(w(EQUAL, 5).holds(&|_, _| None), None, "unreadable memory"); + } + + /// The compute queue's list waits for a value the graphics queue's list + /// writes at its end: it runs after it. + #[test] + fn a_list_waits_for_another_queues_write() { + let fake = RefCell::new(Fake::default()); + fake.borrow_mut().writes.insert("draw", vec![(0x100, 7)]); + let mut held = Held::default(); + held.push(2, Item::Segment("depth", vec![ge(0x100, 7)])); + let p = pump(&mut held, &fake); + assert_eq!((p.pieces, p.segments), (0, 0), "held: the value is not there"); + assert!(held.holds_work(2)); + held.push(1, Item::Segment("draw", vec![])); + let p = pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q1: draw", "q2: depth"]); + assert_eq!((p.pieces, p.segments, p.waited.len()), (2, 2, 1)); + assert_eq!(p.waited[0].0, 2); + assert!(!held.holds_work(2)); + } + + #[test] + fn a_wait_that_holds_defers_nothing() { + let fake = RefCell::new(Fake::default()); + fake.borrow_mut().memory.insert(0x100, 9); + let mut held = Held::default(); + held.push(2, Item::Segment("a", vec![ge(0x100, 7)])); + held.push(2, Item::Segment("b", vec![])); + let p = pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: a b"], "one piece"); + assert_eq!((p.pieces, p.waited.len()), (1, 0)); + } + + /// A list's second segment waits for a value the other queue writes + /// after reading what the first segment wrote: the cut is what lets + /// both make progress. + #[test] + fn chained_waits_across_two_queues() { + let fake = RefCell::new(Fake::default()); + { + let mut f = fake.borrow_mut(); + f.writes.insert("c1", vec![(0x10, 1)]); + f.writes.insert("g1", vec![(0x20, 1)]); + f.writes.insert("c2", vec![(0x30, 1)]); + } + let mut held = Held::default(); + // Compute: [wait 0x08][c1, writes 0x10][wait 0x20][c2, writes 0x30]. + held.push(2, Item::Segment("c1", vec![ge(0x08, 1)])); + held.push(2, Item::Segment("c2", vec![ge(0x20, 1)])); + // Graphics: [g0, writes 0x08], [wait 0x10][g1, writes 0x20], [wait 0x30][g2]. + held.push(1, Item::Segment("g0", vec![])); + fake.borrow_mut().writes.insert("g0", vec![(0x08, 1)]); + held.push(1, Item::Segment("g1", vec![ge(0x10, 1)])); + held.push(1, Item::Segment("g2", vec![ge(0x30, 1)])); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q1: g0", "q2: c1", "q1: g1", "q2: c2", "q1: g2"]); + assert!(held.blocked(&|_, _| Some(0)).is_empty()); + } + + /// Order within a queue never changes: a later segment whose waits hold + /// does not pass a held one. + #[test] + fn a_queue_keeps_its_order() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("first", vec![ge(0x100, 1)])); + held.push(2, Item::Segment("second", vec![])); + pump(&mut held, &fake); + assert!(fake.borrow().log.is_empty()); + fake.borrow_mut().memory.insert(0x100, 1); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: first second"]); + } + + /// A Signal behind held work is delivered after it: the title's fence + /// (and its memory) does not move before the work ran. + #[test] + fn a_signal_waits_for_the_work_before_it() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("work", vec![ge(0x100, 1)])); + held.push(2, Item::Signal(5, 3)); + held.push(2, Item::Segment("after", vec![])); + pump(&mut held, &fake); + assert_eq!(fake.borrow().fences.get(&5), None, "not signalled yet"); + fake.borrow_mut().memory.insert(0x100, 1); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: work", "signal 5 3", "q2: after"]); + } + + #[test] + fn a_fence_wait_holds_its_queue() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::FenceWait(5, 2)); + held.push(2, Item::Segment("after", vec![])); + pump(&mut held, &fake); + assert!(fake.borrow().log.is_empty()); + held.push(1, Item::Signal(5, 2)); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["signal 5 2", "q2: after"]); + } + + /// The frame ends with work held: it stays held (and is reported), and + /// the next frame's write releases it. + #[test] + fn work_held_at_the_frames_end_stays_held() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("late", vec![ge(0x100, 2)])); + held.push(2, Item::Signal(5, 1)); + pump(&mut held, &fake); + let read = |a: u64, _| Some(*fake.borrow().memory.get(&a).unwrap_or(&0)); + let blocked = held.blocked(&read); + assert_eq!(blocked.len(), 1); + assert_eq!((blocked[0].0, blocked[0].1, blocked[0].3.clone()), (2, 2, vec![ge(0x100, 2)])); + fake.borrow_mut().memory.insert(0x100, 2); + let p = pump(&mut held, &fake); + assert_eq!(p.waited.len(), 1); + assert_eq!(fake.borrow().log, ["q2: late", "signal 5 1"]); + } + + #[test] + fn unknown_comparisons_are_counted_and_do_not_hold_work() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + let odd = ValueWait { address: 0x100, bytes: 4, comparison: 12, reference: 1, mask: 0xffff_ffff }; + held.push(2, Item::Segment("odd", vec![odd])); + let p = pump(&mut held, &fake); + assert_eq!((p.segments, p.unknown), (1, 1)); + } + + #[test] + fn the_valve_releases_only_old_heads() { + let fake = RefCell::new(Fake::default()); + let mut held = Held::default(); + held.push(2, Item::Segment("stuck", vec![ge(0x100, 1)])); + assert!(held.force_older_than(Duration::from_secs(60)).is_empty()); + let forced = held.force_older_than(Duration::ZERO); + assert_eq!(forced, [(2, vec![ge(0x100, 1)])]); + pump(&mut held, &fake); + assert_eq!(fake.borrow().log, ["q2: stuck"]); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4a522031f5..4829b5ee6b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -316,6 +316,20 @@ fn by_preference() -> windows::core::Result> { } } +/// Diagnostics: our process's private commit and working set, bytes. +#[cfg(feature = "diagnostics")] +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + (c.PagefileUsage as u64, c.WorkingSetSize as u64) +} + /// 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 { @@ -338,8 +352,109 @@ fn warp_adapter() -> windows::core::Result { } } +/// Diagnostics, `VICTORY_GPU_TIMING`: GPU time per kind of command and +/// pipeline (ms, commands) and lists' wall time against the sum of their +/// commands' (ms), since the last frame-rate line. +#[cfg(feature = "diagnostics")] +type GpuTimes = (std::collections::HashMap, f64, f64); +#[cfg(feature = "diagnostics")] +static GPU_TIMES: Mutex> = Mutex::new(None); + +/// Adds a timed list's commands (from [`HostList::slowest`]) to [`GPU_TIMES`], +/// by the command's kind and pipeline: its note before the first ` | `, +/// without counts and addresses. +#[cfg(feature = "diagnostics")] +fn gpu_times(wall: Duration, commands: &[(f64, String)]) { + let mut times = GPU_TIMES.lock().unwrap_or_else(|e| e.into_inner()); + let (by, wall_ms, sum) = times.get_or_insert_with(Default::default); + *wall_ms += wall.as_secs_f64() * 1e3; + for (ms, note) in commands { + // "draw 3x1 [mesh 1f.., pixel 2e..] | ...": the kind and the pipeline. + let head = note.split(" | ").next().unwrap_or_default(); + let kind = head.split(' ').next().unwrap_or_default(); + let key = match head.find('[') { + Some(at) => format!("{kind} {}", &head[at..]), + None => kind.to_owned(), + }; + let e = by.entry(key).or_default(); + (e.0, e.1) = (e.0 + ms, e.1 + 1); + *sum += ms; + } +} + +/// Logs [`GPU_TIMES`] per frame over `frames` frames: the 25 costliest. +#[cfg(feature = "diagnostics")] +fn log_gpu_times(frames: f64) { + let Some((by, wall, sum)) = GPU_TIMES.lock().unwrap_or_else(|e| e.into_inner()).take() else { + return; + }; + tracing::info!( + "GPU timing: lists {:.1} ms/frame of wall time, their commands {:.1} ms/frame", + wall / frames, + sum / frames + ); + let mut by: Vec<_> = by.into_iter().collect(); + by.sort_by(|a, b| b.1.0.total_cmp(&a.1.0)); + for (key, (ms, n)) in by.iter().take(25) { + tracing::info!(" GPU {:.2} ms/frame in {:.1} commands/frame: {key}", ms / frames, *n as f64 / frames); + } +} + +/// Diagnostics: the host device's video memory use and budget, in MB, local +/// (on the card) and non-local (system memory the GPU reads), as the +/// system's memory manager sees them: use over budget makes it page +/// allocations at submissions. +pub(crate) fn video_memory() -> Option<[(f64, f64); 2]> { + static ADAPTER: OnceLock> = OnceLock::new(); + let adapter = ADAPTER + .get_or_init(|| { + let device = &host()?.device; + // SAFETY: plain device and DXGI queries. + unsafe { + let luid = device.GetAdapterLuid(); + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + factory.EnumAdapterByLuid(luid).ok() + } + }) + .as_ref()?; + let info = |group| { + let mut info = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: a valid out pointer. + unsafe { adapter.QueryVideoMemoryInfo(0, group, &mut info) }.ok()?; + Some((info.CurrentUsage as f64 / 1e6, info.Budget as f64 / 1e6)) + }; + Some([info(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?, info(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)?]) +} + #[cfg(test)] -mod tests { +pub(crate) mod tests { + thread_local! { + /// Every transition barrier built on this thread (resource, before, + /// after), in order. + pub(crate) static ISSUED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// The barriers built on this thread since the last call. + pub(crate) fn issued() -> Vec<(usize, u32, u32)> { + ISSUED.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + + /// Replays transitions in the order the GPU runs them from the states + /// in `states` (resources not in it are not checked), by the debug + /// layer's rule: each barrier's before-state is the resource's current + /// one. The first that is not, else the states after. + pub(crate) fn replay(issued: &[(usize, u32, u32)], states: &mut std::collections::HashMap) -> Result<(), String> { + for (k, &(resource, before, after)) in issued.iter().enumerate() { + if let Some(state) = states.get_mut(&resource) { + if *state != before { + return Err(format!("barrier {k} on {resource:#x}: before {before:#x}, but the resource is in {state:#x}")); + } + *state = after; + } + } + Ok(()) + } + #[test] fn swap_chain_failures_retry_once_per_second_and_success_clears_the_wait() { use super::{Duration, Instant, SwapChainRetry}; @@ -362,6 +477,192 @@ mod tests { use super::*; + /// Shaders that use title memory mark their reads in their own bitmap: + /// read marks of both bitmaps are taken, each slot once until it is + /// forgotten, and a forgotten slot's next read is taken again. + #[test] + fn read_marks_of_both_bitmaps_are_taken() { + let Some(host) = host() else { return }; + // No submission takes the marks meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let (plain, memory) = (victory_shader::emit::HEAP_VIEWS - 2, victory_shader::emit::HEAP_VIEWS - 1); + crate::shadow::tests::mark_read(false, plain); + crate::shadow::tests::mark_read(true, memory); + let taken = crate::shadow::take_reads(); + assert!(taken.contains(&plain), "a plain shader's read"); + assert!(taken.contains(&memory), "a read by a shader that uses title memory"); + let again = crate::shadow::take_reads(); + assert!(!again.contains(&plain) && !again.contains(&memory), "each once"); + crate::shadow::forget_read(memory); + assert!(!crate::shadow::take_reads().contains(&memory), "forgotten: its mark cleared"); + crate::shadow::tests::mark_read(true, memory); + assert!(crate::shadow::take_reads().contains(&memory), "read again after it was forgotten"); + } + + /// The textures shaders read through the heap since the last eviction + /// pass are named again at each pass (a slot's read is reported as new + /// only once), and the marks are cleared for the next. + #[test] + fn heap_reads_since_the_last_pass_name_their_textures() { + let Some(host) = host() else { return }; + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 4, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + // A 4x1 RGBA8 texture, linear, in memory of its own, and a 2D view. + let memory = vec![0u8; 1 << 16]; + let address = memory.as_ptr() as u64; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + crate::descriptor::create_placed_srv(null, &words, &view, title_heap.start); + let heap_host = title_heap.host().expect("a host view heap"); + assert!(heap_host.mirror(0, title_heap.start, true).is_some()); + let texture = crate::resource::texture_at(address, &words).expect("its resource"); + let raw = windows::core::Interface::as_raw(&crate::resource::made_copy(texture).unwrap().texture) as usize; + // No submission takes the marks meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + for _ in 0..2 { + crate::shadow::tests::mark_read(false, 0); + let slots = crate::shadow::reads_since(); + assert!(slots.contains(&0), "the slot read"); + assert!(crate::descriptor::read_textures(&slots).contains(&raw), "its texture named"); + assert!(!crate::shadow::reads_since().contains(&0), "the marks cleared"); + } + } + + /// The idle rule against the heap reads that thrashed (run evict1): a + /// texture shaders read through the heap in every frame stays over more + /// frames and time than the idle limits; one read once is given up. A + /// list of the title's naming a texture (a table read, a copy) stamps it + /// as used; a list of ours (uploads) does not. + #[test] + fn textures_read_every_frame_stay_and_title_lists_stamp_theirs() { + let Some(host) = host() else { return }; + let null = std::ptr::null(); + let heap_desc: [u32; 8] = [0, 8, 1, 0, 0, 0, 0, 0]; + let mut heap = null; + let iid = crate::object::guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + assert_eq!(crate::descriptor::create_heap(null, heap_desc.as_ptr().cast(), &iid, &mut heap), 0); + let title_heap = crate::descriptor::heap(heap); + let step = 32; + // Two 4x1 RGBA8 textures, linear, in memory of their own, viewed at + // slots 5 and 6. + let memory = vec![0u8; 1 << 17]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let heap_host = title_heap.host().expect("a host view heap"); + let textures: Vec = [5u32, 6] + .iter() + .map(|&slot| { + let address = memory.as_ptr() as u64 + u64::from(slot) * (1 << 13); + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + let at = title_heap.start + u64::from(slot) * step; + crate::descriptor::create_placed_srv(null, &words, &view, at); + assert!(heap_host.mirror(slot, at, true).is_some()); + crate::resource::texture_at(address, &words).expect("its resource") + }) + .collect(); + let owned: Vec<_> = textures.iter().map(|&t| crate::resource::owned(t).expect("may be given up")).collect(); + let (idle_frames, idle_ms) = (crate::resource::IDLE_FRAMES, crate::resource::IDLE_MS); + { + // No submission takes the marks meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Passes a third of the idle limits apart, over three times them. + for k in 0..10 { + crate::shadow::tests::mark_read(false, 5); + if k == 0 { + crate::shadow::tests::mark_read(false, 6); + } + let read = crate::descriptor::read_textures(&crate::shadow::reads_since()); + crate::resource::evict_among(&owned, &read, 1000 + k * idle_frames / 3, 1_000_000 + k * idle_ms / 3, 0); + assert!(crate::resource::made_copy(textures[0]).is_some(), "read every frame: stays (frame {k})"); + } + } + assert!(crate::resource::made_copy(textures[1]).is_none(), "read once: given up"); + drop(owned); + // A title list naming the texture stamps it, an upload list does not. + let copy = crate::resource::host_copy(textures[0]).unwrap(); + for (ours, stamped) in [(true, false), (false, true)] { + copy.unstamp(); + let list = host.new_list().unwrap(); + if ours { + list.set_ours(); + } + let _ = list.transition(textures[0], 0x40); + assert_eq!(copy.last_used().0 != u64::MAX, stamped, "ours: {ours}"); + } + } + + /// Textures the heaps view are brought up to date only if the title used + /// them lately: one whose pages changed but that no shader read is not + /// uploaded; read in the last pass, it is. + #[test] + fn heap_textures_unread_lately_are_not_brought_up() { + let Some(host) = host() else { return }; + let address = crate::watch::tests::pool(1) as u64; + let words: [u32; 14] = [3, 0, 0, 0, 64, 0, 64, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let iid = crate::object::guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]); + let mut object = std::ptr::null(); + let null = std::ptr::null(); + assert_eq!(crate::resource::create_at_address(null, address, words.as_ptr().cast(), 0, std::ptr::null(), &iid, &mut object), 0); + let copy = crate::resource::host_copy(object).expect("a host texture"); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + let viewed = std::sync::Arc::new(crate::bindless::Viewed::default()); + viewed.set(0, Some(&crate::descriptor::View::Shader(object as usize, Some(desc))), true); + // No submission uploads meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: the texture's memory, 256-byte rows of 64 texels. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x40, 64 * 64 * 4) }; + copy.unstamp(); + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + assert_eq!(crate::texture::uploads(object), 0, "not read lately: not brought up"); + copy.stamp(); + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + assert_eq!(crate::texture::uploads(object), 1, "read in the last pass: brought up"); + } + + /// Heap textures brought up in one submission are refreshed side by + /// side, each into its own staging and its own upload. + #[test] + fn heap_textures_brought_up_together_each_get_their_upload() { + let Some(host) = host() else { return }; + let iid = crate::object::guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]); + let pool = crate::watch::tests::pool(6); + let viewed = std::sync::Arc::new(crate::bindless::Viewed::default()); + let objects: Vec = (0..6u32) + .map(|k| { + // RGBA8 128x128 (one page each), linear, each its own bytes. + let address = (pool + k as usize * crate::watch::PAGE) as u64; + // SAFETY: the texture's own page of the pool. + unsafe { std::ptr::write_bytes(address as *mut u8, 0x10 * k as u8, crate::watch::PAGE) }; + let words: [u32; 14] = [3, 0, 0, 0, 128, 0, 128, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let mut object = std::ptr::null(); + assert_eq!(crate::resource::create_at_address(std::ptr::null(), address, words.as_ptr().cast(), 0, std::ptr::null(), &iid, &mut object), 0); + crate::resource::host_copy(object).expect("a host texture").stamp(); + let mut desc = [0u32; 10]; + desc[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + viewed.set(k, Some(&crate::descriptor::View::Shader(object as usize, Some(desc))), true); + object + }) + .collect(); + // No submission uploads meanwhile. + let _one = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + for &object in &objects { + assert_eq!(crate::texture::uploads(object), 1, "each brought up once"); + } + let _ = crate::bindless::uploads(std::slice::from_ref(&viewed), &[]); + for &object in &objects { + assert_eq!(crate::texture::uploads(object), 1, "unchanged: not again"); + } + } + #[test] fn list_scratch_grows_to_fit_and_reuses_fenced_chunks() { let Some(host) = host() else { return }; @@ -540,6 +841,12 @@ pub(crate) struct HostList { /// A copy of ours replaced the list's compute root signature and /// pipeline: draws and dispatches set theirs again. rebind: std::sync::atomic::AtomicBool, + /// A list of ours (uploads), whose uses are no use of the title's + /// (`crate::resource::evict`). + ours: std::sync::atomic::AtomicBool, + /// The draw or dispatch being recorded runs a program using title + /// memory ([`HostList::writer_uses_memory`]). + memory_writer: std::sync::atomic::AtomicBool, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. @@ -550,6 +857,9 @@ pub(crate) struct HostList { /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + /// Clamped indirect arguments (`crate::indirect`), reused by each + /// execution in turn; replaced by a bigger one when too small. + arguments: Mutex>, /// 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")] @@ -564,6 +874,13 @@ pub(crate) struct HostList { stamps: OnceLock>, } +// SAFETY: D3D12 objects are free-threaded; a host list is recorded by the +// title list's one recording thread, then run by one submission at a time +// (the queues hold it between, `crate::hold`). +unsafe impl Send for HostList {} +// SAFETY: as above. +unsafe impl Sync for HostList {} + /// Timestamps per list (diagnostics); commands past them are not timed. #[cfg(feature = "diagnostics")] const STAMPS: u32 = 4096; @@ -694,11 +1011,13 @@ enum Step { /// Work that writes host memory only. Host(Box), /// Shaders write a range (address, bytes) of a buffer's host copy; - /// whether they mark the pages they write (no snapshot then). - GpuWrite(std::sync::Arc, usize, usize, bool), + /// whether they mark the pages they write (no snapshot then), and + /// whether their program uses title memory (then the range is withheld + /// when such a list misses, `crate::memory::withholding`). + GpuWrite(std::sync::Arc, usize, usize, bool, bool), /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. - Texture(std::sync::Arc), + Texture(std::sync::Arc, std::sync::Arc), /// Brings every buffer range a view heap's views reach up to date /// (`crate::bindless`). Heap(std::sync::Arc), @@ -728,6 +1047,10 @@ struct Deferred { /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, + /// The memory values the list waits for before it starts (a list the + /// title records with a wait after commands is cut there, + /// `crate::list`). + waits: Vec, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, /// Work done once the list has run, before the bottom-of-pipe writes @@ -841,10 +1164,13 @@ impl Host { states: Mutex::default(), twins: Mutex::default(), rebind: false.into(), + ours: false.into(), + memory_writer: false.into(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), id, budget: OnceLock::new(), + arguments: Mutex::new(None), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -865,9 +1191,16 @@ impl Host { let faults = crate::copystat::page_faults(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); + // Host textures the title has not used for a while (or past the + // card's budget) are given up first: the last submission has run. + crate::resource::evict_unused(); // Descriptors the title copied into its heaps itself, before the // heaps' views are brought up to date below. + #[cfg(feature = "diagnostics")] + let syncing = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SyncHeapsUs); crate::descriptor::sync_heaps(); + #[cfg(feature = "diagnostics")] + drop(syncing); // Textures heap-indexing shaders may read, uploaded first by a list // of ours where their title memory changed. let heaps: Vec> = runs @@ -883,10 +1216,24 @@ impl Host { .collect::>() }) .collect(); + // And textures read through tables, uploaded by the same list. + let textures: Vec<_> = runs + .iter() + .flat_map(|l| { + l.deferred() + .copies + .iter() + .filter_map(|s| match s { + Step::Texture(staging, copy) => Some((staging.clone(), copy.clone())), + _ => None, + }) + .collect::>() + }) + .collect(); #[cfg(feature = "diagnostics")] let uploading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::UploadsUs); - let uploads = (!heaps.is_empty()) - .then(|| crate::bindless::uploads(&heaps)) + let uploads = (!heaps.is_empty() || !textures.is_empty()) + .then(|| crate::bindless::uploads(&heaps, &textures)) .flatten(); #[cfg(feature = "diagnostics")] drop(uploading); @@ -970,6 +1317,12 @@ impl Host { #[cfg(feature = "diagnostics")] crate::resource::life::note(0, crate::resource::life::RAN, *submitted, 0); #[cfg(feature = "diagnostics")] + if groups.len() > 1 { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + gpu_times(started.elapsed(), &runs[i].slowest(frequency, usize::MAX)); + } + #[cfg(feature = "diagnostics")] if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); @@ -1017,25 +1370,51 @@ impl Host { // One list's lock at a time: a submission may name a list twice. let mut back: Vec<(std::sync::Arc, usize, usize, bool)> = Vec::new(); let mut index: std::collections::HashMap<(usize, usize, usize), usize> = std::collections::HashMap::new(); - for list in runs { + // Shaders that read memory with no copy computed something else than + // the console's: it stays out of title memory, where it broke the + // title's own data (runs c1, c4), and so does what every program + // using title memory wrote while any misses + // (`crate::memory::withholding`). Only lists with such programs have + // checks; all are asked before anything goes back. Other programs in + // those lists write through bounded views from their own inputs: + // their ranges go back (the imposter transforms beside the BVH + // builder in one list, run light13). + let missed: Vec = runs + .iter() + .map(|list| list.deferred().missed.iter().any(|check| check())) + .collect(); + crate::memory::note_submission(missed.contains(&true)); + let withholding = crate::memory::withholding(); + for (list, &missed) in runs.iter().zip(&missed) { let deferred = list.deferred(); - // Shaders that read memory with no copy computed something else - // than the console's: it stays out of title memory, where it broke - // the title's own data (runs c1, c4). - let missed = deferred.missed.iter().any(|check| check()); + let missed = missed || withholding && !deferred.missed.is_empty(); for step in &deferred.copies { - if let Step::GpuWrite(shadow, address, len, _) = step { + if let Step::GpuWrite(shadow, address, len, _, memory) = step { let key = (std::sync::Arc::as_ptr(shadow) as usize, *address, *len); + // A range both kinds declare is withheld whole. + let goes_back = !(missed && *memory); match index.get(&key) { - Some(&i) => back[i].3 &= !missed, + Some(&i) => back[i].3 &= goes_back, None => { index.insert(key, back.len()); - back.push((shadow.clone(), *address, *len, !missed)); + back.push((shadow.clone(), *address, *len, goes_back)); } } } } } + // A range overlapping a withheld one of the same copy is withheld + // too: its copy-back would take the other's bytes along (pages a + // program using title memory and another both wrote). + let held: Vec<(usize, usize, usize)> = back + .iter() + .filter(|b| !b.3) + .map(|(s, a, n, _)| (std::sync::Arc::as_ptr(s) as usize, *a, *n)) + .collect(); + for b in back.iter_mut().filter(|b| b.3) { + let copy = std::sync::Arc::as_ptr(&b.0) as usize; + b.3 = !held.iter().any(|&(c, a, n)| c == copy && a < b.1 + b.2 && b.1 < a + n); + } // Pages shaders marked first: the copy-backs below end what the // copies keep for them. let withheld: Vec<(std::sync::Arc, usize, usize)> = back @@ -1043,7 +1422,12 @@ impl Host { .filter(|b| !b.3) .map(|(s, a, n, _)| (s.clone(), *a, *n)) .collect(); - crate::shadow::copy_back_marks(&withheld); + crate::shadow::copy_back_marks(&withheld, withholding); + // Texture views left null that shaders read: made for what follows. + let read = crate::shadow::take_reads(); + if !read.is_empty() { + crate::descriptor::make_read(&read); + } for (shadow, address, len, goes_back) in &back { let (address, len) = (*address, *len); if *goes_back { @@ -1052,6 +1436,7 @@ impl Host { } else { shadow.keep_writes(address, len); crate::memory::note_withheld(len as u64); + crate::memory::drop_withheld(address, len); } } for list in runs { @@ -1067,8 +1452,10 @@ impl Host { what.write(at as *mut u8, bytes); } } - // The submission has run and the next waits for our lock. + // The submission has run and the next waits for our lock. Host + // copies the title gave up meanwhile may have their last holder here. release_retired(); + release_later(Box::new((batch, back, withheld, heaps))); self.log_messages(); // A listed frame: what this submission's lists drew, as it is now // (the dumps submit lists of their own). @@ -1457,15 +1844,17 @@ impl HostList { &self, resource: crate::object::This, wanted: u32, - ) -> Option<(&'static ID3D12Resource, u32)> { - let texture = crate::resource::host_resource(resource)?; + ) -> Option<(ID3D12Resource, u32)> { + // One host texture for the whole move (`crate::resource::evict` may + // give it up meanwhile; this list then holds it). let copy = crate::resource::host_copy(resource)?; + let texture = copy.texture.clone(); if let Some(Some(twin)) = copy.twin.get() && crate::twin::route(self, ©, twin, wanted) { return None; } - let wanted = legal_state(texture, wanted); + let wanted = legal_state(&texture, wanted); self.track(©, wanted).map(|before| (texture, before)) } @@ -1477,6 +1866,9 @@ impl HostList { match states.entry(std::sync::Arc::as_ptr(copy) as usize) { std::collections::hash_map::Entry::Vacant(v) => { copy.note_used(); + if !self.ours.load(Ordering::Relaxed) { + copy.stamp(); + } v.insert((wanted, wanted, copy.clone())); None } @@ -1523,6 +1915,25 @@ impl HostList { } } + /// The list is one of ours (uploads): what it uses is no use of the + /// title's. + pub(crate) fn set_ours(&self) { + self.ours.store(true, Ordering::Relaxed); + } + + /// What the list's shaders write from now until the guard goes is + /// written by a program using title memory (`uses`) or not. + pub(crate) fn writer_uses_memory(&self, uses: bool) -> impl Drop + '_ { + struct Reset<'a>(&'a std::sync::atomic::AtomicBool); + impl Drop for Reset<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Relaxed); + } + } + self.memory_writer.store(uses, Ordering::Relaxed); + Reset(&self.memory_writer) + } + /// A copy of ours replaced the compute root signature and pipeline. pub(crate) fn need_rebind(&self) { self.rebind.store(true, Ordering::Relaxed); @@ -1544,20 +1955,26 @@ impl HostList { let copies = crate::twin::at_submission(twins.values()); drop(twins); let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec = states - .values() - .filter_map(|(first, last, copy)| { - let real = copy.state.swap(*last, Ordering::Relaxed); - (real != *first).then(|| { - transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - ) + // The copies start from the real states, then the list's moves from + // them; only after both do they become the states the list leaves. + let moves = || -> Vec { + states + .values() + .filter_map(|(first, _, copy)| { + let real = copy.state.load(Ordering::Relaxed); + (real != *first).then(|| { + transition(©.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(*first as i32)) + }) }) - }) - .collect(); - if barriers.is_empty() && copies.is_empty() { + .collect() + }; + let left = || { + for (_, last, copy) in states.values() { + copy.state.store(*last, Ordering::Relaxed); + } + }; + if copies.is_empty() && states.values().all(|(first, _, copy)| copy.state.load(Ordering::Relaxed) == *first) { + left(); return None; } let (allocator, list) = &self.prelude; @@ -1574,24 +1991,27 @@ impl HostList { let real = t.state.load(Ordering::Relaxed); let wanted = legal_state(&t.texture, wanted); (real != wanted).then(|| { + let there = transition(&t.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(wanted as i32)); back.push(transition( &t.texture, D3D12_RESOURCE_STATES(wanted as i32), D3D12_RESOURCE_STATES(real as i32), )); - transition(&t.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(wanted as i32)) + there }) }); if !back.is_empty() { list.ResourceBarrier(&back); } } + let barriers = moves(); if !barriers.is_empty() { list.ResourceBarrier(&barriers); } list.Close() }) }; + left(); if let Err(e) = recorded { fail(format_args!("a host state prelude did not record ({e})")); } @@ -1703,9 +2123,10 @@ impl HostList { len: usize, marked: bool, ) { + let memory = self.memory_writer.load(Ordering::Relaxed); self.deferred() .copies - .push(Step::GpuWrite(shadow.clone(), address, len, marked)); + .push(Step::GpuWrite(shadow.clone(), address, len, marked, memory)); } /// Shaders of the list take views from the heap itself @@ -1742,6 +2163,30 @@ impl HostList { self.deferred().writes.push((dst as usize, what, bytes)); } + /// A memory value the list waits for before it starts. + pub(crate) fn defer_wait(&self, wait: crate::hold::ValueWait) { + self.deferred().waits.push(wait); + } + + /// The memory values the list waits for before it starts. + pub(crate) fn waits(&self) -> Vec { + self.deferred().waits.clone() + } + + /// Whether nothing has been recorded since the list was made or reset + /// that a wait recorded now would have to follow: no work, texture + /// use, bottom-of-pipe write or pipeline (state settings alone carry + /// over). + pub(crate) fn is_empty(&self) -> bool { + let d = self.deferred(); + let deferred_empty = d.copies.is_empty() && d.uploads.is_empty() && d.writes.is_empty() && d.after.is_empty() && d.missed.is_empty(); + drop(d); + deferred_empty + && self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + /// A mapped upload buffer of `size` bytes, alive until the list is /// reset. /// @@ -1753,6 +2198,15 @@ impl HostList { Some((buffer, data)) } + /// A mapped readback buffer of `size` bytes, alive until the list is + /// reset. + pub(crate) fn readback(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let (buffer, data) = host.mapped_buffer(size, true)?; + name(&buffer, || format!("list readback {size:#x}")); + self.deferred().uploads.push(buffer.clone()); + Some((buffer, data)) + } + /// `len` bytes of upload memory (256-byte aligned) until the list is /// reset: the host GPU address and the CPU pointer. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { @@ -1816,6 +2270,23 @@ impl HostList { Some(unsafe { buffer.GetGPUVirtualAddress() }) } + /// The list's argument buffer, at least `bytes` long, common between + /// its uses (`crate::indirect`). + pub(crate) fn arguments(&self, bytes: u64) -> Option { + let mut arguments = self.arguments.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a plain query on a live buffer. + if let Some(b) = arguments.as_ref().filter(|b| unsafe { b.GetDesc() }.Width >= bytes) { + return Some(b.clone()); + } + let (made, _) = host()?.shared_buffer(bytes.next_power_of_two().max(1 << 16))?; + name(&made, || "indirect arguments".into()); + // Commands recorded earlier may still name the smaller one. + if let Some(old) = arguments.replace(made.clone()) { + self.keep(&old); + } + Some(made) + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { @@ -1841,10 +2312,15 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } - /// Brings a texture's staging buffer up to date when the list is - /// submitted, keeping it alive until the list is reset. - pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { - self.deferred().copies.push(Step::Texture(staging)); + /// Brings a texture's staging buffer and host texture `copy` up to date + /// when the list is submitted (`crate::bindless::uploads`), keeping + /// both alive until the list is reset. + pub(crate) fn defer_texture( + &self, + staging: std::sync::Arc, + copy: std::sync::Arc, + ) { + self.deferred().copies.push(Step::Texture(staging, copy)); } /// Runs the list's submission-time steps; refreshes go into `batch` @@ -1863,7 +2339,7 @@ impl HostList { Step::Copy(..) | Step::Fill(..) => C::StepCopyUs, Step::Run(_) | Step::Host(_) => C::StepWorkUs, Step::GpuWrite(..) => C::StepGpuWriteUs, - Step::Texture(_) => C::StepTextureUs, + Step::Texture(..) => C::StepTextureUs, Step::Heap(_) => C::StepHeapUs, Step::Memory(_) => C::StepMemoryUs, }, @@ -1909,7 +2385,7 @@ impl HostList { } continue; } - Step::GpuWrite(shadow, address, len, marked) => { + Step::GpuWrite(shadow, address, len, marked, _) => { // The shaders start from the title's data, which a // snapshot must hold (marked ranges keep none). if !marked { @@ -1918,12 +2394,8 @@ impl HostList { shadow.writing(*address, *len, *marked); continue; } - Step::Texture(staging) => { - if batch.texture_due(staging) { - staging.refresh(); - } - continue; - } + // Brought up to date before the submission's lists were made. + Step::Texture(..) => continue, Step::Heap(viewed) => { crate::bindless::refresh(viewed, |s, a, l| batch.add(s, a, l)); continue; @@ -1961,12 +2433,15 @@ struct Batch { /// The range of each copy brought up to date since the last title /// write, by copy (held, so that its address names no other). current: std::collections::HashMap, usize, usize)>, - /// Staging buffers (by address) refreshed since the last title write. - textures: std::collections::HashSet, } impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { + // Nothing to copy: a world submission asks for every copy its heaps' + // views and page tables reach (~9,000), a few of them written. + if shadow.clean() { + return; + } let (key, end) = (std::sync::Arc::as_ptr(shadow) as usize, address + len); if self.current.get(&key).is_some_and(|&(_, a, b)| a <= address && end <= b) { return; @@ -1983,17 +2458,10 @@ impl Batch { } } - /// Whether `staging` is still to be refreshed in this submission (and - /// notes it refreshed). - fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { - self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) - } - /// Before a step that writes title memory: pending refreshes are done /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); - self.textures.clear(); self.current.clear(); } @@ -2071,6 +2539,8 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); + #[cfg(feature = "diagnostics")] + let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::FallbackUs); // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece // that fails), zeros for what cannot be read. for_pieces(src as usize, len, 64 << 10, |at, n| { @@ -2271,8 +2741,14 @@ impl Host { } pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.mapped_buffer(size, false) + } + + /// A mapped buffer of `size` bytes: upload memory, or (`readback`) + /// readback memory in the copy-destination state. + fn mapped_buffer(&self, size: u64, readback: bool) -> Option<(ID3D12Resource, *mut u8)> { let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_UPLOAD, + Type: if readback { D3D12_HEAP_TYPE_READBACK } else { D3D12_HEAP_TYPE_UPLOAD }, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -2297,7 +2773,7 @@ impl Host { &heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, + if readback { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_GENERIC_READ }, None, &mut buffer, ) @@ -2309,7 +2785,7 @@ impl Host { match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { - tracing::warn!(error = %e, size, "no upload buffer"); + tracing::warn!(error = %e, size, readback, "no mapped buffer"); None } } @@ -2445,21 +2921,55 @@ impl Meter { making = crate::pipeline::making() ); let (textures, bytes, used, shared, saved, replaced) = crate::resource::texture_counts(); + let (heaps, heap_used, heap_free) = crate::placement::stats(); tracing::info!( "host textures: {textures} ({:.0} MB, {:.0} MB of them used by lists), title textures sharing one {shared} (saving {:.0} MB), replacing one {replaced}; \ + heaps of textures {heaps} ({:.0} MB used, {:.0} MB free); \ copies between textures of one memory {:.1}/frame, depth twin copies {:.1}/frame", bytes as f64 / 1e6, used as f64 / 1e6, saved as f64 / 1e6, + heap_used as f64 / 1e6, + heap_free as f64 / 1e6, crate::texture::ALIAS_COPIES.swap(0, Ordering::Relaxed) as f64 / frames, crate::twin::COPIES.swap(0, Ordering::Relaxed) as f64 / frames, ); #[cfg(feature = "diagnostics")] { + if let Some([(local, budget), (system, system_budget)]) = video_memory() { + let (commit, working_set) = process_memory(); + tracing::info!( + "video memory: {local:.0} MB of a {budget:.0} MB budget on the card, \ + {system:.0} MB of {system_budget:.0} MB in system memory; process commit {:.0} MB, \ + working set {:.0} MB; Rust heap {:.0} MB; placed textures made {:.0} MB; list upload memory {} blocks {:.0} MB", + commit as f64 / 1e6, + working_set as f64 / 1e6, + crate::copystat::HEAP_BYTES.load(Ordering::Relaxed) as f64 / 1e6, + crate::resource::PLACED_BYTES.load(Ordering::Relaxed) as f64 / 1e6, + crate::list::UPLOADS[0].load(Ordering::Relaxed), + crate::list::UPLOADS[1].load(Ordering::Relaxed) as f64 / 1e6, + ); + } + let [gpu, title] = crate::resource::texture_census().map(|r| r.map(|b| b as f64 / 1e6)); + tracing::info!( + "host texture MB (used by lists, viewed by heap slots only, neither): GPU-written {:.0} {:.0} {:.0}, \ + from title memory {:.0} {:.0} {:.0}", + gpu[0], gpu[1], gpu[2], title[0], title[1], title[2] + ); let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64; + crate::frame::log(); + log_gpu_times(copy_frames); crate::copystat::log(copy_frames); crate::bindless::log(copy_frames); crate::shadow::log_views(copy_frames); + let [n, bytes] = [0, 1].map(|i| crate::list::READ_BACKS[i].swap(0, Ordering::Relaxed)); + if n > 0 { + tracing::info!( + "texture read backs: {:.1}/frame, {:.1} KB/frame", + n as f64 / frames, + bytes as f64 / frames / 1e3 + ); + } for (why, n) in drops.iter().take(40) { tracing::info!( "dropped {:.1}/frame without a host pipeline: {why}", @@ -2696,6 +3206,34 @@ pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { } impl Host { + /// Diagnostics, `VICTORY_COPIES_IN_VIDEO_MEMORY`: [`Host::shared_buffer`]s + /// (host copies of title memory among them) in video memory the CPU maps + /// (a GPU upload heap, where the host has one), to measure how much of + /// the GPU's time is shaders reading the copies over the bus. CPU reads + /// of them (snapshots, copy-backs) become slow: for that measurement only. + #[cfg(feature = "diagnostics")] + fn copies_in_video_memory(&self) -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + if !crate::switch::on("VICTORY_COPIES_IN_VIDEO_MEMORY") { + return false; + } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + // SAFETY: the query writes its own structure of the given size. + let ok = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS16, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.GPUUploadHeapSupported.as_bool(); + tracing::warn!(on = ok, "host copies of title memory in video memory (diagnostics)"); + ok + }) + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in @@ -2707,6 +3245,12 @@ impl Host { MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + #[cfg(feature = "diagnostics")] + let heap = if self.copies_in_video_memory() { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, ..Default::default() } + } else { + heap + }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: size.max(1), @@ -2764,25 +3308,59 @@ pub(crate) fn retire(resource: ID3D12Resource) { /// After a submission has run, with none running: the retired resources go. pub(crate) fn release_retired() { let retired = std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())); - drop(retired); + if !retired.is_empty() { + release_later(Box::new(retired)); + } +} + +/// Drops `what` on a thread of its own: releasing a D3D12 resource is a +/// kernel call (~5 % of a world frame on the title's submitting thread, +/// run perf1). Only for objects no GPU work in flight uses. +fn release_later(what: Box) { + type Release = std::sync::mpsc::Sender>; + static RELEASE: OnceLock = OnceLock::new(); + let release = RELEASE.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::>(); + // Without the thread the receiver is gone: sends fail and drop here. + let _ = std::thread::Builder::new() + .name("victory-release".into()) + .spawn(move || rx.into_iter().for_each(drop)); + tx + }); + let _ = release.send(what); } /// Diagnostics: a noted command running a shader `VICTORY_TRACE_SHADERS` -/// names (hashes, comma-separated) is logged with what it binds, the first -/// 500. +/// names (hashes, comma-separated) is logged with what it binds: all of +/// them in listed capture frames, the first 500 elsewhere. #[cfg(feature = "diagnostics")] fn traced(what: &str) { - static HASHES: OnceLock> = OnceLock::new(); static LOGGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let hashes = HASHES.get_or_init(|| { - let v = std::env::var("VICTORY_TRACE_SHADERS").unwrap_or_default(); - v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned).collect() - }); - if hashes.iter().any(|h| what.contains(h.as_str())) && LOGGED.fetch_add(1, Ordering::Relaxed) < 500 { + if is_traced(what) + && (crate::capture::listed(crate::queue::presented() + 1) + || LOGGED.fetch_add(1, Ordering::Relaxed) < 500) + { tracing::info!("traced command: {what}"); } } +/// The shader hashes `VICTORY_TRACE_SHADERS` lists (comma-separated; +/// diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) fn traced_shaders() -> &'static [String] { + static HASHES: OnceLock> = OnceLock::new(); + HASHES.get_or_init(|| { + let v = std::env::var("VICTORY_TRACE_SHADERS").unwrap_or_default(); + v.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_owned).collect() + }) +} + +/// Whether `what` names a shader [`traced_shaders`] lists. +#[cfg(feature = "diagnostics")] +pub(crate) fn is_traced(what: &str) -> bool { + traced_shaders().iter().any(|h| what.contains(h.as_str())) +} + /// Diagnostics, `VICTORY_GPU_TIMING`: every command of the list during /// whose run (each list alone) the device was found removed. fn removed_during(runs: &[&HostList], list: Option) -> String { @@ -2870,6 +3448,8 @@ pub(crate) fn transition( before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES, ) -> D3D12_RESOURCE_BARRIER { + #[cfg(test)] + tests::ISSUED.with(|l| l.borrow_mut().push((resource.as_raw() as usize, before.0 as u32, after.0 as u32))); D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -2965,38 +3545,8 @@ fn pump() { } #[cfg(test)] -mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file +mod batch { // `mod tests` is already taken at the top of this file use super::Batch; - use std::sync::Arc; - - #[test] - fn a_texture_is_checked_once_per_submission() { - let mut batch = Batch::default(); - let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); - // The first list sampling each texture checks it ... - assert!(batch.texture_due(&a)); - assert!(batch.texture_due(&b)); - // ... later lists of the same submission do not. - assert!(!batch.texture_due(&a)); - assert!(!batch.texture_due(&a.clone())); - assert!(!batch.texture_due(&b)); - } - - #[test] - fn title_writes_make_textures_due_again() { - let mut batch = Batch::default(); - let a = Arc::new(1u32); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A copy into title memory or work that may write it may have - // changed the texture's memory. - batch.title_written(); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A fresh submission starts over. - let mut next = Batch::default(); - assert!(next.texture_due(&a)); - } /// A host copy of tracked title memory: a submission whose lists all ask /// for it whole copies the one page the title wrote, once, and again @@ -3033,43 +3583,58 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at drop(copy); crate::watch::tests::free(p); } +} - /// The hashing a submission does for textures in physical-page memory, - /// with every list checking the textures it samples (before) and with - /// each checked once (after). Run with - /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`. + +#[cfg(test)] +mod withholding { + /// A list in which a program using title memory missed memory: what + /// that program wrote is withheld from title memory and leaves the + /// copies at once; what an ordinary program wrote in the same list goes + /// back and stays in its copy (run light13: the imposter transforms in + /// the BVH builder's list); an ordinary range overlapping a withheld one + /// is withheld with it, since its copy-back would take the other's bytes + /// along. #[test] - #[ignore = "benchmark"] - fn texture_checks_per_submission() { - const TEXTURES: usize = 48; - const SIZE: usize = 4 << 20; - const LISTS: usize = 12; - let textures: Vec>> = (0..TEXTURES) - .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) - .collect(); - let submit = |dedupe: bool| { - let mut batch = Batch::default(); - let mut hashed = 0usize; - let started = std::time::Instant::now(); - for _ in 0..LISTS { - for t in &textures { - if !dedupe || batch.texture_due(t) { - std::hint::black_box(blake3::hash(t)); - hashed += 1; - } - } - } - (started.elapsed(), hashed) + fn only_programs_using_title_memory_are_withheld() { + use crate::watch::PAGE; + let Some(host) = super::host() else { + return; // no host GPU here }; - submit(false); // warm up - let (before, n_before) = submit(false); - let (after, n_after) = submit(true); - assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); - println!( - "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ - before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", - SIZE >> 20, - before.as_secs_f64() / after.as_secs_f64() - ); + let pools = [crate::watch::tests::pool(1), crate::watch::tests::pool(1)]; + for &p in &pools { + // SAFETY: our pool, not guarded yet. + unsafe { ((p + 16) as *mut u8).write_volatile(0x11) }; + crate::shadow::register(p, p as u64, PAGE as u64); + } + let copies: Vec<_> = pools.iter().map(|&p| crate::shadow::find(p as u64, PAGE as u64).unwrap()).collect(); + let list = host.new_list().unwrap(); + // (copy, start, bytes, the writer uses title memory, byte written at +0 and +16) + let writes = [(0, 0, 32, false, 0x22), (1, 16, 16, true, 0x33), (1, 0, 32, false, 0x44)]; + for &(k, at, len, memory, value) in &writes { + let _writer = list.writer_uses_memory(memory); + let (copy, address) = (copies[k].clone(), (pools[k] + at) as u64); + copy.refresh(&list, address, len); + copy.gpu_writes(&list, address, len, false); + // The shader's write, after the step that keeps the range's bytes. + list.defer_host(move || copy.write_host(address, &[value])); + } + list.defer_missed(|| true); + list.close(); + host.execute(&[&list]); + // SAFETY: bytes of our pools. + let title = |k: usize, at: usize| unsafe { ((pools[k] + at) as *const u8).read_volatile() }; + let copy = |k: usize, at: usize| { + copies[k].update(pools[k], PAGE); + copies[k].read_host((pools[k] + at) as u64, 1)[0] & 0xff + }; + assert_eq!((title(0, 0), copy(0, 0)), (0x22, 0x22), "an ordinary program's write goes back and stays"); + assert_eq!((title(1, 16), copy(1, 16)), (0x11, 0x11), "withheld, then dropped from the copy"); + assert_eq!((title(1, 0), copy(1, 0)), (0, 0), "overlapping a withheld range: withheld with it"); + for (&p, copy) in pools.iter().zip(copies) { + crate::shadow::unregister(p, p as u64); + drop(copy); + crate::watch::tests::free(p); + } } } diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7cde54b444..0960ed91e1 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -24,16 +24,18 @@ use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" +#define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u1), UAV(u0)" cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); +// The title's records, read only; the clamped ones go to the list's own. +ByteAddressBuffer args : register(t0); +RWByteAddressBuffer dest : 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; -// Clamps the record at `at` in place; its cost. +// Clamps the record at `at` into `dest`; its cost. uint clamped(uint at) { uint cost; if (kind <= 1) { @@ -41,7 +43,14 @@ uint clamped(uint at) { uint count = min(args.Load(at), 1u << 24); uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + dest.Store2(at, uint2(count, instances)); + // The rest of the record as it is: first vertex and instance (4 words + // in all), or first index, base vertex and first instance (5). + if (kind == 1) { + dest.Store3(at + 8, args.Load3(at + 8)); + } else { + dest.Store2(at + 8, args.Load2(at + 8)); + } } else if (kind == 2) { uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); // x * y fits 32 bits; the whole count may not. @@ -49,13 +58,13 @@ uint clamped(uint at) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64; - args.Store3(at, g); + dest.Store3(at, g); } else { // Mesh dispatches: the console's are one-dimensional. uint3 g = args.Load3(at); g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); cost = g.x * g.y * g.z * 128; - args.Store3(at, g); + dest.Store3(at, g); } return cost; } @@ -97,7 +106,7 @@ void main(uint lane : SV_GroupIndex) { GroupMemoryBarrierWithGroupSync(); if (costs[lane] == PAST) { // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + dest.Store(at, 0); } } if (lane == 0) { @@ -177,57 +186,65 @@ fn make() -> windows::core::Result { } /// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. -pub(crate) fn bound( - list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, - (kind, stride, records): (u32, u32, u32), -) -> bool { +/// argument numbering) `stride` bytes apart at host address `gpu` (a title +/// buffer's copy, only read) into the list's own argument buffer, left +/// ready to be read as arguments: that buffer, for [`done`] after the +/// execution. Replaces the list's compute root signature and pipeline +/// (callers bind theirs after). `None` if the clamp is not available. +/// +/// Title buffers' copies are never transitioned: they are common between +/// submissions and every use promotes them (shader and root views, the +/// input assembler, these reads), with unordered-access barriers for order. +/// Only the list's argument buffer moves, common, unordered access, +/// indirect argument, common: its states are known whatever order lists +/// run in. +// shortcut: a buffer a shader writes through an unordered view and the +// input assembler then reads in one submission is, by the letter of D3D12, +// promoted to a write state the input assembler may not use (the debug +// layer cannot see view accesses; GPU-based validation might); upgrade to +// per-list tracked buffer states if a driver or that validation minds. +pub(crate) fn bound(list: &HostList, gpu: u64, (kind, stride, records): (u32, u32, u32)) -> Option { let (Some(c), Some(budget)) = (clamp(), list.budget()) else { - return false; + return None; }; if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { - return false; + return None; } + let out = list.arguments(u64::from(stride) * u64::from(records.max(1)))?; let l = &list.list; let constants = [kind, stride, records, 0]; - // SAFETY: an open list; our root signature, pipeline and a live buffer - // the caller's list holds. + // SAFETY: an open list; our root signature, pipeline and buffers, and + // a title buffer's copy the caller's list holds. unsafe { // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); + l.ResourceBarrier(&[ + uav_barrier(), + transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); l.SetComputeRootSignature(&c.root); l.SetPipelineState(&c.pso); l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); + l.SetComputeRootShaderResourceView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); + l.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); // One group walks every record. l.Dispatch(records.min(1), 1, 1); l.ResourceBarrier(&[ uav_barrier(), - transition( - buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - ), + transition(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), ]); } - true + Some(out) } -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. -pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { +/// After the execution: the list's argument buffer back to common. +pub(crate) fn done(list: &HostList, arguments: &ID3D12Resource) { // SAFETY: an open list and a live buffer. unsafe { list.list.ResourceBarrier(&[transition( - buffer, + arguments, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, )]) }; } @@ -254,9 +271,10 @@ mod tests { } /// Clamps `records` records of `kind`, filled by repeating `words`, - /// `calls` times in one list: each record's first word after (zero when - /// it runs empty). One record more follows them and must stay as - /// written. `None` without a host GPU. + /// `calls` times in one list: each record's first word in the list's + /// argument buffer after (zero when it runs empty). The title's copy, + /// one record more included, stays as written. `None` without a host + /// GPU. fn clamped(kind: u32, words: &[u32], records: u32, calls: u32) -> Option> { let host = super::host()?; // Words in a record of `kind`. @@ -277,16 +295,20 @@ mod tests { data.add(at).write_volatile(words[at % words.len()]); } let gpu = buffer.GetGPUVirtualAddress(); + let mut out = None; for _ in 0..calls { - assert!(super::bound(&list, &buffer, gpu, spec)); - super::done(&list, &buffer); + let clamped = super::bound(&list, gpu, spec).unwrap(); + super::done(&list, &clamped); + out = Some(clamped); } list.close(); host.execute(&[&list]); - for at in all - per..all { - assert_eq!(data.add(at).read_volatile(), words[at % words.len()]); + for at in 0..all { + assert_eq!(data.add(at).read_volatile(), words[at % words.len()], "the title's copy as written"); } - let first = |i: usize| data.add(i * per).read_volatile(); + let mut out_data = std::ptr::null_mut(); + out?.Map(0, None, Some(&mut out_data)).unwrap(); + let first = |i: usize| out_data.cast::().add(i * per).read_volatile(); Some((0..records as usize).map(first).collect()) } } @@ -332,6 +354,60 @@ mod tests { assert_eq!(ran, [true, true, false, false, false, false, false, false]); } + /// Two lists clamping into their own argument buffers, run in either + /// order: every barrier starts from the buffer's current state (the + /// debug layer's rule; runs light19 and light21 had the title's GPU + /// heap moved to unordered access under the input assembler), the + /// title's copy is never transitioned, and all end common. + #[test] + fn argument_buffers_move_from_their_current_states() { + use crate::host::tests::{issued, replay}; + use windows::core::Interface; + let Some(host) = super::host() else { + return; // no host GPU here + }; + let (title, data) = host.shared_buffer(1 << 16).unwrap(); + // SAFETY: our mapped buffer; a live buffer. + let gpu = unsafe { + data.cast::<[u32; 3]>().write_volatile([70_000, 1, 1]); + title.GetGPUVirtualAddress() + }; + let key = |r: &super::ID3D12Resource| r.as_raw() as usize; + for a_first in [true, false] { + let lists = [host.new_list().unwrap(), host.new_list().unwrap()]; + issued(); + let recorded: Vec<_> = lists + .iter() + .map(|l| { + let out = super::bound(l, gpu, (2, 12, 1)).unwrap(); + super::done(l, &out); + l.close(); + (out, issued()) + }) + .collect(); + let order = if a_first { [0, 1] } else { [1, 0] }; + host.execute(&[&lists[order[0]], &lists[order[1]]]); + let mut run = issued(); + run.extend(order.iter().flat_map(|&i| recorded[i].1.clone())); + let mut states: std::collections::HashMap = + [key(&title), key(&recorded[0].0), key(&recorded[1].0)].into_iter().map(|k| (k, 0)).collect(); + replay(&run, &mut states).unwrap(); + assert!(run.iter().all(|t| t.0 != key(&title)), "the title's copy is never transitioned"); + assert!(states.values().all(|&s| s == 0), "all common again"); + for (out, _) in &recorded { + let mut p = std::ptr::null_mut(); + // SAFETY: a mapped buffer of ours, the lists have run. + let clamped = unsafe { + out.Map(0, None, Some(&mut p)).unwrap(); + p.cast::<[u32; 3]>().read_volatile() + }; + assert_eq!(clamped, [65_535, 1, 1]); + } + // SAFETY: as above. + assert_eq!(unsafe { data.cast::<[u32; 3]>().read_volatile() }, [70_000, 1, 1], "the title's copy as written"); + } + } + /// The budget is the list's: a second execution of the same records /// finds it spent, and they all run empty. #[test] diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index a392bd369a..9e88db5c40 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -32,6 +32,7 @@ pub mod dxgi; pub mod external; pub mod fence; pub mod frame; +mod hold; #[cfg(windows)] mod host; #[cfg(windows)] @@ -42,6 +43,8 @@ mod memory; pub mod object; pub mod pipeline; #[cfg(windows)] +mod placement; +#[cfg(windows)] mod primitive; pub mod query; pub mod queue; @@ -64,6 +67,8 @@ mod twin; #[cfg(windows)] mod watch; +#[cfg(all(windows, feature = "diagnostics"))] +pub use copystat::CountingAlloc; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index d48f48c6aa..0d3aaf38d4 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -115,8 +115,15 @@ struct List { /// [`allocate_upload`], kept until the list is reset; the host list the /// calls record into (decision 0007), and the draw state the title set. uploads: std::sync::Mutex>, + /// The host lists the calls record into, in order: one, and one more + /// for every wait the title records after commands ([`wait`]). Shared + /// with the queues that hold them until their waits hold + /// (`crate::hold`), so they outlive a list the title releases first. #[cfg(windows)] - host: Option, + hosts: std::sync::Mutex>>, + /// Which of them the calls record into. + #[cfg(windows)] + segment: std::sync::atomic::AtomicUsize, #[cfg(windows)] state: std::sync::Mutex, } @@ -133,14 +140,167 @@ pub(crate) fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); } -/// The host list behind a title list, if there is a host GPU. +/// The host list a title list's calls record into (its current segment), +/// if there is a host GPU. #[cfg(windows)] pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { if this.is_null() { return None; } // SAFETY: the title passes one of our lists. - unsafe { (*this.cast::()).host.as_ref() } + let list = unsafe { &*this.cast::() }; + let k = list.segment.load(std::sync::atomic::Ordering::Relaxed); + let hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + let current: *const crate::host::HostList = std::sync::Arc::as_ptr(hosts.get(k)?); + // SAFETY: the list holds this host list until it is reset or released + // (an `Arc` does not move it), and the title records into a list from + // one thread at a time. + Some(unsafe { &*current }) +} + +/// A title list's host lists, in order: what a submission of it runs. +#[cfg(windows)] +pub(crate) fn segments(this: This) -> Vec> { + if this.is_null() { + return Vec::new(); + } + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let k = list.segment.load(std::sync::atomic::Ordering::Relaxed); + let hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + hosts.iter().take(k + 1).cloned().collect() +} + +/// Waits recorded after commands: the title list goes on in a new host +/// list, which runs once the wait holds. +static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Lists reset or released while a queue still held some of their host +/// lists: D3D12 lets a list be reset as soon as it is submitted (Grand +/// Theft Auto VI does, 0-21 times a world frame). +static EARLY_RESETS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Cuts and early resets since the last call (the frame line). +pub(crate) fn take_cuts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (CUTS.swap(0, Relaxed), EARLY_RESETS.swap(0, Relaxed)) +} + +/// `Wait32BitValueX(address, comparison, reference, mask, flags)` and +/// `Wait64BitValueX(address, comparison, reference, flags)`: the GPU waits +/// until the value compares true. Recorded at the start of the current host +/// list, or, after commands, at the start of a new one the rest of the +/// title list records into (the queue runs each once its waits hold, +/// `crate::hold`); bottom-of-pipe writes recorded before it land when the +/// part before it has run. +extern "system" fn wait32(this: This, address: u64, comparison: u32, reference: u32, mask: u32, _flags: u32) { + wait(this, crate::hold::ValueWait { address, bytes: 4, comparison, reference: u64::from(reference), mask: u64::from(mask) }); +} +pub(crate) extern "system" fn wait64(this: This, address: u64, comparison: u32, reference: u64, _flags: u32) { + wait(this, crate::hold::ValueWait { address, bytes: 8, comparison, reference, mask: u64::MAX }); +} + +fn wait(this: This, wait: crate::hold::ValueWait) { + #[cfg(windows)] + { + let Some(current) = host_list(this) else { return }; + if !current.is_empty() { + let Some(next) = next_segment(this) else { return }; + CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + current.close(); + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + list.state.lock().unwrap_or_else(|e| e.into_inner()).cut(next); + next.defer_wait(wait); + return; + } + current.defer_wait(wait); + } + #[cfg(not(windows))] + let _ = (this, wait); +} + +/// Moves a title list's recording on to its next host list (made, or one +/// it held since an earlier recording, reset then): that host list. +#[cfg(windows)] +fn next_segment<'a>(this: This) -> Option<&'a crate::host::HostList> { + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let k = list.segment.load(std::sync::atomic::Ordering::Relaxed) + 1; + let mut hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + if hosts.len() <= k { + let made = crate::host::host()?.new_list().ok()?; + hosts.push(std::sync::Arc::new(made)); + } + list.segment.store(k, std::sync::atomic::Ordering::Relaxed); + let next: *const crate::host::HostList = std::sync::Arc::as_ptr(&hosts[k]); + drop(hosts); + // SAFETY: as in `host_list`. + Some(unsafe { &*next }) +} + +/// After the title list's last submission: its host lists start again, +/// and a host list a queue still holds (`crate::hold`) is left to the +/// queue and replaced. The last one left so, which should keep what the +/// title list owned. +#[cfg(windows)] +fn restart(this: This) -> Option> { + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let used = list.segment.swap(0, std::sync::atomic::Ordering::Relaxed); + let mut hosts = list.hosts.lock().unwrap_or_else(|e| e.into_inner()); + let mut left = None; + for (k, h) in hosts.iter_mut().enumerate() { + if std::sync::Arc::strong_count(h) > 1 { + EARLY_RESETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tracing::debug!(segment = k, "a list reset while a queue still holds part of it: that part keeps its own host list"); + let spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()).pop(); + match spare.map(Ok).or_else(|| crate::host::host().map(|host| host.new_list())) { + Some(Ok(fresh)) => left = Some(std::mem::replace(h, std::sync::Arc::new(fresh))), + _ => continue, + } + } else if k <= used { + h.reset(); + } + } + left +} + +/// Host lists [`restart`] left to a queue, back once they ran: the next +/// ones it hands out (a host list and its allocators are not free to make; +/// Grand Theft Auto VI resets up to 21 lists a frame while they are held). +#[cfg(windows)] +static SPARE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// A host list a queue has run: one no title list holds any more is reset +/// and kept for [`restart`]. +#[cfg(windows)] +pub(crate) fn recycle(list: std::sync::Arc) { + const KEPT: usize = 64; + if let Ok(list) = std::sync::Arc::try_unwrap(list) { + list.reset(); + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if spare.len() < KEPT { + spare.push(list); + } + } +} + +/// What a title list owned that the host list a queue still holds, if any, +/// may read: its upload memory (list 0x4a0) and its draw state's dynamic +/// descriptor slots and title-memory page table. Freed once that host list +/// (the list's last held one, so the last to run) is gone. +#[cfg(windows)] +fn leave(to: Option>, uploads: Vec, state: crate::draw::State) { + struct Kept(#[allow(dead_code)] Vec, #[allow(dead_code)] crate::draw::State); + // SAFETY: only dropped, with the host list, after it has run. + unsafe impl Send for Kept {} + if let Some(held) = to { + let kept = Kept(uploads, state); + held.defer_after(move || { + let _ = &kept; + }); + } } pub(crate) extern "system" fn create_allocator( @@ -222,13 +382,20 @@ fn new_list( newer: [0; 256], uploads: Default::default(), #[cfg(windows)] - host: crate::host::host().and_then(|h| match h.new_list() { - Ok(list) => Some(list), - Err(e) => { - tracing::warn!(error = %e, "no host command list"); - None - } - }), + hosts: std::sync::Mutex::new( + crate::host::host() + .and_then(|h| match h.new_list() { + Ok(list) => Some(std::sync::Arc::new(list)), + Err(e) => { + tracing::warn!(error = %e, "no host command list"); + None + } + }) + .into_iter() + .collect(), + ), + #[cfg(windows)] + segment: Default::default(), #[cfg(windows)] state: { let mut state = crate::draw::State::default(); @@ -259,6 +426,21 @@ extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HR object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out) } extern "system" fn list_release(this: This) -> u32 { + // A queue may still hold some of its host lists; they are its own, and + // the last of them takes what the list owned. + #[cfg(windows)] + if !this.is_null() && object::refs(this) == 1 { + // SAFETY: the title passes one of our lists. + let list = unsafe { &*this.cast::() }; + let held = list.hosts.lock().unwrap_or_else(|e| e.into_inner()).iter().rfind(|h| std::sync::Arc::strong_count(h) > 1).cloned(); + if held.is_some() { + EARLY_RESETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + tracing::debug!("a list released while a queue still holds part of it: that part runs on its own"); + let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner())); + leave(held, uploads, state); + } + } object::release_boxed::(this) } extern "system" fn list_type(this: This) -> u32 { @@ -276,15 +458,22 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT if allocator.is_null() { return E_INVALIDARG; } - // Every submission of the list has run (submissions are waited for). + // A queue may still hold what the list recorded (`restart`, `leave`). // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; - uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); + let uploads = std::mem::take(&mut *uploads.lock().unwrap_or_else(|e| e.into_inner())); #[cfg(windows)] - with_state(this, |host, state| { - host.reset(); + { + let held = restart(this); + // SAFETY: the title passes one of our lists. + let mut state = unsafe { &(*this.cast::()).state }.lock().unwrap_or_else(|e| e.into_inner()); + let old = std::mem::take(&mut *state); state.reset(pipeline); - }); + drop(state); + leave(held, uploads, old); + } + #[cfg(not(windows))] + drop(uploads); crate::pipeline::bound(pipeline); #[cfg(not(windows))] let _ = this; @@ -326,7 +515,7 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { flags: 0, first: texture.as_raw().cast_const().cast(), second: 0xffff_ffff | (u64::from(before) << 32), - last: u64::from(crate::host::legal_state(texture, wanted)), + last: u64::from(crate::host::legal_state(&texture, wanted)), }) } 1 => Some(Barrier { @@ -372,6 +561,8 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> { // SAFETY: the title passes `count` barriers. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("barrier kinds {:?}", barriers.iter().map(|b| b.kind).collect::>())); let mut host: Vec = barriers .iter() .filter_map(|b| host_barrier(list, b)) @@ -406,8 +597,8 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; if let Some((texture, before)) = list.transition(resource, state) { - let state = crate::host::legal_state(texture, state); - let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); + let state = crate::host::legal_state(&texture, state); + let barrier = crate::host::transition(&texture, State(before as i32), State(state as i32)); // SAFETY: an open list and a live texture. unsafe { list.list.ResourceBarrier(&[barrier]) }; } @@ -461,16 +652,16 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { - if crate::texture::title_written(from) { - crate::texture::upload(list, src, from); + if crate::texture::title_written(&from) { + crate::texture::upload(list, src, &from); } ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); - crate::texture::host_written(dst); + crate::texture::host_writes(list, dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. - unsafe { list.list.CopyResource(to, from) }; + unsafe { list.list.CopyResource(&to, &from) }; } else if let (Some((to, a)), Some((from, b))) = ( crate::resource::buffer_bytes(dst), crate::resource::buffer_bytes(src), @@ -497,8 +688,8 @@ pub(crate) struct CopyLocation { } /// Texture to texture on the GPU; buffer to texture through an upload -/// buffer filled at submission. Texture to buffer (read back) is not done -/// yet. +/// buffer filled at submission; texture to buffer through readback memory +/// ([`read_back`]). extern "system" fn copy_texture_region( this: This, dst: *const CopyLocation, @@ -522,8 +713,9 @@ extern "system" fn copy_texture_region( return; }; let Some(to) = crate::resource::host_resource(dst.resource) else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented")); + if dst.kind == FOOTPRINT && src.kind != FOOTPRINT { + read_back(list, &dst, [x, y, z], &src, source_box); + } return; }; let mut from = src; @@ -555,14 +747,14 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; - if crate::texture::title_written(texture) { - crate::texture::upload(list, src.resource, texture); + if crate::texture::title_written(&texture) { + crate::texture::upload(list, src.resource, &texture); } ensure_state(list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } ensure_state(list, dst.resource, COPY_DEST); - crate::texture::host_written(dst.resource); + crate::texture::host_writes(list, dst.resource); 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::()); @@ -607,6 +799,118 @@ extern "system" fn copy_texture_region( let _ = (this, dst, x, y, z, src, source_box); } +/// Texture read backs since the last frame-rate line: how many, bytes +/// (diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) static READ_BACKS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// (texture, buffer) pairs read back so far, each logged once (diagnostics). +#[cfg(feature = "diagnostics")] +static READ_BACK_PAIRS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Texture to buffer (a read back): the region is copied on the host into +/// readback memory laid out as the title's footprint, and once the list has +/// run its rows go into the title's buffer (the title reads them on the CPU +/// after its fence). +#[cfg(windows)] +fn read_back(list: &crate::host::HostList, dst: &CopyLocation, at: [u32; 3], src: &CopyLocation, source_box: *const [u32; 6]) { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_BOX, D3D12_RESOURCE_DIMENSION_TEXTURE3D, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + }; + use windows::core::Interface; + macro_rules! refused { + ($why:literal) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(concat!("texture to buffer copy refused: ", $why))); + return; + }}; + } + let (Some(host), Some(texture)) = (crate::host::host(), crate::resource::host_resource(src.resource)) else { + refused!("no host texture"); + }; + // SAFETY: the title's box (same layout as the host's) or null; a live texture. + let (b, desc) = unsafe { (source_box.cast::().as_ref(), texture.GetDesc()) }; + let size = match b { + Some(b) => [b.right.saturating_sub(b.left), b.bottom.saturating_sub(b.top), b.back.saturating_sub(b.front)], + None => { + // A subresource index shares the footprint's first dword. + let mip = src.footprint.offset as u32 % u32::from(desc.MipLevels.max(1)); + let depth = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { u32::from(desc.DepthOrArraySize) } else { 1 }; + [((desc.Width >> mip) as u32).max(1), (desc.Height >> mip).max(1), (depth >> mip).max(1)] + } + }; + // The host takes footprints of 256-byte pitches only (as the console). + if !dst.footprint.row_pitch.is_multiple_of(256) { + refused!("a row pitch not a multiple of 256"); + } + // shortcut: depth and stencil planes copy out in typeless formats of + // their own; refused until a title is seen reading one back. + if desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 { + refused!("a depth or stencil texture"); + } + // The host copies into a footprint only within a buffer that holds all + // of it, so readback memory spans the footprint, not just the region. + let (Some(rows), Some(len)) = (dst.footprint.rows(at, size), dst.footprint.bytes()) else { + refused!("a region outside its footprint"); + }; + let (Some(title), Some((buffer, data))) = (buffer_range(dst.resource, dst.footprint.offset, len), list.readback(host, len)) else { + return; + }; + if crate::texture::title_written(&texture) { + crate::texture::upload(list, src.resource, &texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let (mut to, mut from) = (*dst, *src); + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint.offset = 0; + from.resource = texture.as_raw().cast_const().cast(); + #[cfg(feature = "diagnostics")] + { + let text = || { + let mem = crate::resource::texture_memory(src.resource).map_or(0, |(at, _)| at as usize); + format!( + "read back {:?} (mem {mem:#x}, {}x{} f{} sub {}) {size:?} at {at:?} into {:?}+{:#x}, {len} bytes", + src.resource, + desc.Width, + desc.Height, + desc.Format.0, + src.footprint.offset as u32, + dst.resource, + dst.footprint.offset + ) + }; + READ_BACKS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + READ_BACKS[1].fetch_add(len, std::sync::atomic::Ordering::Relaxed); + let pair = (src.resource as usize, dst.resource as usize); + let mut seen = READ_BACK_PAIRS.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&pair) { + seen.push(pair); + tracing::info!("a texture read back (first of this pair): {}", text()); + } + list.note_op(text); + } + // SAFETY: an open list; both locations in the host's layout, naming live + // resources; the region lies in the footprint (checked). + unsafe { + list.list.CopyTextureRegion( + (&raw const to).cast(), + at[0], + at[1], + at[2], + (&raw const from).cast(), + b.map(std::ptr::from_ref), + ) + }; + let (data, title) = (data as usize, title as usize); + list.defer_after(move || { + for &(at, n) in &rows { + let (at, n) = (at as usize, n as usize); + let _writing = crate::watch::writing(title + at, n); + crate::host::write_mapped((title + at) as *mut u8, (data + at) as *const u8, n); + } + }); +} + #[allow(clippy::too_many_arguments)] // the method's own arguments extern "system" fn copy_texture_region_x( this: This, @@ -646,7 +950,7 @@ extern "system" fn resolve( const RESOLVE_SOURCE: u32 = 0x2000; ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); - crate::texture::host_written(dst); + crate::texture::host_writes(list, dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); // SAFETY: an open list and live textures; the region is inside both. @@ -655,7 +959,7 @@ extern "system" fn resolve( let format = DXGI_FORMAT(format as i32); if (a.Width, a.Height) == (b.Width, b.Height) { list.list - .ResolveSubresource(to, dst_sub, from, src_sub, format); + .ResolveSubresource(&to, dst_sub, &from, src_sub, format); } else if let Ok(list1) = list.list.cast::() { // The console clips a larger source to the destination. let rect = RECT { @@ -665,11 +969,11 @@ extern "system" fn resolve( bottom: a.Height.min(b.Height) as i32, }; list1.ResolveSubresourceRegion( - to, + &to, dst_sub, 0, 0, - from, + &from, src_sub, Some(&rect), format, @@ -797,7 +1101,7 @@ extern "system" fn clear_dsv( }); const DEPTH_WRITE: u32 = 0x10; ensure_state(list, record.resource, DEPTH_WRITE); - let dsv = host.dsv(texture, record.depth_desc().as_ref()); + let dsv = host.dsv(&texture, record.depth_desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { list.list @@ -1002,6 +1306,8 @@ impl Upload { return None; } crate::shadow::register(at, at as u64, len as u64); + UPLOADS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + UPLOADS[1].fetch_add(len as u64, std::sync::atomic::Ordering::Relaxed); Some(Upload { at, len }) } @@ -1025,6 +1331,8 @@ impl Drop for Upload { fn drop(&mut self) { use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; crate::shadow::unregister(self.at, self.at as u64); + UPLOADS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + UPLOADS[1].fetch_sub(self.len as u64, std::sync::atomic::Ordering::Relaxed); // Not guarded any more: memory allocated here next is new. crate::watch::title_memory_remapped(self.at, self.len); // SAFETY: our allocation; lists that still use its copy hold that. @@ -1036,6 +1344,11 @@ impl Drop for Upload { #[cfg(windows)] unsafe impl Send for Upload {} +/// Live list upload blocks and their bytes (the statistics). +#[cfg(windows)] +pub(crate) static UPLOADS: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + /// Draw state the host has no use for (root signatures: ours come with /// the pipeline; depth bounds, depth order and shading rate hints): any /// arguments, nothing returned. @@ -1045,7 +1358,7 @@ extern "system" fn ignored_state(_: This) {} /// set on the host list at once. Without a host GPU these do nothing. #[cfg(windows)] mod state { - use super::{This, host_list, with_state}; + use super::{This, with_state}; use crate::draw::{IndexView, VertexView}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; @@ -1067,25 +1380,17 @@ mod state { count: u32, viewports: *const D3D12_VIEWPORT, ) { - if let Some(list) = host_list(this) { - crate::draw::viewports(list, items(viewports, count)); - } + with_state(this, |list, s| s.viewports(list, items(viewports, count))); } pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { - if let Some(list) = host_list(this) { - crate::draw::scissors(list, items(rects, count)); - } + with_state(this, |list, s| s.scissors(list, items(rects, count))); } pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { - if let Some(list) = host_list(this) { - // SAFETY: the title passes four floats or null. - crate::draw::blend_factor(list, unsafe { factor.as_ref() }); - } + // SAFETY: the title passes four floats or null. + with_state(this, |list, s| s.blend_factor(list, unsafe { factor.as_ref() })); } pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { - if let Some(list) = host_list(this) { - crate::draw::stencil_ref(list, reference); - } + with_state(this, |list, s| s.stencil_ref(list, reference)); } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); @@ -1392,10 +1697,6 @@ pub(crate) fn take_counts() -> (u64, u64) { (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) } -/// A GPU wait for a memory value `(address, comparison, reference, ...)`. -/// Lists run one after another and to completion, so a value another queue -/// or the CPU has to write first cannot be waited for; nothing to do. -extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {} /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a @@ -1408,6 +1709,13 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { && let Some(list) = host_list(this) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // Which kinds of barriers (0 global, 1 texture, 2 buffer) and how many. + #[cfg(feature = "diagnostics")] + if !_groups.is_null() { + // SAFETY: the title passes `count` groups of 16 bytes: kind, count, pointer. + let groups = unsafe { std::slice::from_raw_parts(_groups.cast::<[u32; 4]>(), count as usize) }; + list.note_op(|| format!("barrier groups {:?}", groups.iter().map(|g| (g[0], g[1])).collect::>())); + } // SAFETY: the same layout; no resource named. let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. @@ -1423,7 +1731,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { defer_write(this, address, Written::Value(u64::from(value)), 4); } -extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { +pub(crate) extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { const GPU_TIMESTAMP: u32 = 1; const SYSTEM_TIMESTAMP: u32 = 2; let what = match flags { @@ -1498,8 +1806,8 @@ const METHODS: [(usize, *const ()); 52] = [ (68, ignored_state as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 - (71, wait_value as *const ()), // 0x238, 32 bits - (72, wait_value as *const ()), // 0x240, 64 bits + (71, wait32 as *const ()), // 0x238 (newer 0x248) + (72, wait64 as *const ()), // 0x240 (newer 0x250) (73, ignored_state as *const ()), // 0x248 pixel shader depth order (83, copy_texture_region_x as *const ()), // 0x298 (84, copy_resource_x as *const ()), // 0x2a0 diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 8700ca4e93..c2ad88da9f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -84,6 +84,8 @@ impl Map { #[derive(Default)] struct Layout { copies: Vec>, + /// Each copy's bit in the change tracker (`crate::watch::clean_bit`). + bits: Vec>, blocks: Vec, owner: Vec>, } @@ -161,9 +163,79 @@ pub(crate) fn note_use(pipeline: &str) { stats(|s| *s.uses.entry(pipeline.to_owned()).or_default() += 1); } +/// Frames presented, and the last one in which a list using title memory +/// read or wrote memory with no copy ([`MISS_NEVER`] if none has). +static FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static MISSED_IN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(MISS_NEVER); +const MISS_NEVER: u64 = u64::MAX; + +/// Whether a list using title memory in the submission being completed +/// read or wrote memory with no copy (completions run one at a time). +static SUBMISSION_MISSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A submission's lists ran: whether one using title memory read or wrote +/// memory with no copy. +pub(crate) fn note_submission(missed: bool) { + use std::sync::atomic::Ordering::Relaxed; + SUBMISSION_MISSED.store(missed, Relaxed); + if missed { + MISSED_IN.store(FRAMES.load(Relaxed), Relaxed); + } +} + +/// Whether what lists using title memory wrote stays out of title memory +/// (in the host copies, for the GPU): some such list missed memory this +/// frame or the one before. A list that missed computed from zeros, and +/// the lists after it compute from its results in the host copies, the +/// BVH builder's write addresses among them, so withholding only the lists +/// that missed broke the title's own data (run drops1: an AABB's +inf/-inf +/// in a pointer the title followed). The frame before counts too: its +/// lists' results are read in this one, before this frame's first miss. +pub(crate) fn withholding() -> bool { + use std::sync::atomic::Ordering::Relaxed; + withheld_in(FRAMES.load(Relaxed), MISSED_IN.load(Relaxed)) +} + +fn withheld_in(frame: u64, missed: u64) -> bool { + missed != MISS_NEVER && frame <= missed.saturating_add(1) +} + +/// Title memory whose host copies hold what shaders wrote this frame and +/// the frame withheld ([`withholding`]; ranges). +static DROPPED: Mutex> = Mutex::new(Vec::new()); + +/// Shaders wrote `[address, address + len)` of title memory in host copies +/// and the submission withheld it: the copies take title memory's bytes +/// again at their next refresh, from right after the submission if a list +/// of it missed (its results would feed the frame's later submissions: +/// garbage BVH nodes over meshlet buffers, run shards20), else from the +/// frame's end ([`retake_dropped`]). +pub(crate) fn drop_withheld(address: usize, len: usize) { + if SUBMISSION_MISSED.load(std::sync::atomic::Ordering::Relaxed) { + crate::watch::retake(address, len); + } else { + DROPPED.lock().unwrap_or_else(|e| e.into_inner()).push((address, len)); + } +} + +/// At a frame's end: what the frame withheld leaves the host copies, so +/// that results computed from memory with no copy (garbage record arrays +/// and node pointers of the BVH builder) do not feed later frames whose +/// writes go back (a box16 node's f16 bounds over a title object, run +/// textures9). Each copy holding such memory takes it from title memory at +/// its next refresh, through its tracker. +fn retake_dropped() { + let dropped = std::mem::take(&mut *DROPPED.lock().unwrap_or_else(|e| e.into_inner())); + for (address, len) in dropped { + crate::watch::retake(address, len); + } +} + /// Logs what title memory did since the last call, if anything: a line per /// presented frame while shaders use it. pub(crate) fn log_frame() { + FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + retake_dropped(); let s = stats(std::mem::take); if s.uses.is_empty() && s.written + s.withheld + s.withheld_bytes + s.missed_pages + s.missed_regions == 0 { return; @@ -313,6 +385,7 @@ impl Shared { unsafe { std::ptr::copy_nonoverlapping(dwords.as_ptr(), self.data as *mut u32, dwords.len()) }; tracing::debug!(copies = ranges.len(), blocks = blocks.len() - 1, "title memory page table"); self.layout = Arc::new(Layout { + bits: named.iter().map(|c| c.dirty_bit()).collect(), copies: named, blocks, owner, @@ -348,9 +421,15 @@ pub(crate) fn prepare(key: usize, mut add: impl FnMut(&Arc, usize, usize Some(s.layout.clone()) }) .flatten(); - for c in layout.iter().flat_map(|l| &l.copies) { - let (start, len) = c.range(); - add(c, start as usize, len as usize); + // Copies the title has not written since they took it are passed by + // without touching them (the table names every copy, ~4,700 in the world). + for l in layout.iter() { + for (c, bit) in l.copies.iter().zip(&l.bits) { + if !crate::watch::clean_bit(*bit) { + let (start, len) = c.range(); + add(c, start as usize, len as usize); + } + } } } @@ -400,7 +479,7 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { }) }); list.defer_after(move || { - let Layout { copies, blocks, owner } = &*layout(key); + let Layout { copies, blocks, owner, .. } = &*layout(key); let precise = byte_for_byte.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: the bitmap is mapped and the list's run is over. let marks = unsafe { std::slice::from_raw_parts_mut(data as *mut u32, words) }; @@ -431,10 +510,14 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { } // What shaders computed from memory with no copy (read as zeros) is // not the console's: it does not go into title memory, where it broke - // the title's own data (garbage pointers in title threads, run c1). - // shortcut: root UAV writes of such a list still go back (their - // bytes, `Shadow::gpu_writes`). - let withheld = if pages + regions > 0 { writes.len() as u64 } else { 0 }; + // the title's own data (garbage pointers in title threads, run c1), + // nor while any list using title memory misses ([`withholding`]). + let withheld = if pages + regions > 0 || withholding() { writes.len() as u64 } else { 0 }; + if withheld > 0 { + for &(_, at) in &writes { + drop_withheld(at as usize, 1 << 16); + } + } let mut written = 0; for &(k, at) in writes.iter().take_while(|_| withheld == 0) { let n = copies[k].copy_back_page(at as usize); @@ -466,6 +549,17 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option { mod tests { use super::*; + /// Writes of lists using title memory are held back from a frame with a + /// miss through the next one, then go back again. + #[test] + fn a_miss_holds_back_its_frame_and_the_next() { + assert!(!withheld_in(0, MISS_NEVER)); + assert!(!withheld_in(u64::MAX, MISS_NEVER)); + assert!(withheld_in(7, 7)); + assert!(withheld_in(8, 7), "the next frame reads this one's results"); + assert!(!withheld_in(9, 7)); + } + /// The shader's lookup (`victory_shader` lowering) over a table's /// dwords: the view index and the byte offset in that view. fn look_up(dwords: &[u32], address: u64) -> (u32, u32) { @@ -541,7 +635,7 @@ void main(uint3 id : SV_DispatchThreadID) { } "#; - fn pipeline() -> ( + fn pipeline(source: &str) -> ( windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, windows::Win32::Graphics::Direct3D12::ID3D12PipelineState, ) { @@ -554,8 +648,8 @@ void main(uint3 id : SV_DispatchThreadID) { // SAFETY: the source and names outlive the call; the errors are text. unsafe { let made = D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), + source.as_ptr().cast(), + source.len(), s!("memory"), None, None, @@ -609,7 +703,7 @@ void main(uint3 id : SV_DispatchThreadID) { let (Some(host), Some(views)) = (crate::host::host(), heap()) else { return; // no host GPU here }; - let (root, pso) = pipeline(); + let (root, pso) = pipeline(SOURCE); let (out, at) = host.shared_buffer(256).unwrap(); // SAFETY: a live buffer. let out_gpu = unsafe { out.GetGPUVirtualAddress() }; @@ -688,4 +782,118 @@ void main(uint3 id : SV_DispatchThreadID) { drop(copy); } } + + /// Writes `value` at (`lo`, `hi`) through the page table, marking its + /// page as translated shaders do, and with `missing_hi` non-zero reads + /// (`missing_lo`, `missing_hi`), marking it if no copy holds it. + const WRITE: &str = r#" +#define RS "DescriptorTable(UAV(u0, numDescriptors=unbounded)), SRV(t0, space=2), UAV(u0, space=2), RootConstants(num32BitConstants=5, b0)" +RWByteAddressBuffer views[] : register(u0); +ByteAddressBuffer table : register(t0, space2); +RWByteAddressBuffer dirty : register(u0, space2); +cbuffer c : register(b0) { uint lo; uint hi; uint value; uint missing_lo; uint missing_hi; } +void access(uint a, uint h, bool write) { + bool inside = h < 256; + uint l1 = inside ? (h << 4 | a >> 28) : 0; + uint block = inside ? table.Load(l1 * 4) : 0; + uint entry = block << 12 | (a >> 16 & 0xFFF); + uint2 e = table.Load2((4096 + 2 * entry) * 4); + bool miss = e.x == table.Load(4096 * 4); + uint n = miss && block == 0 ? l1 : entry; + if (write || miss) { + dirty.InterlockedOr(n >> 5 << 2, 1u << (n & 31)); + } + if (write && !miss) { + views[NonUniformResourceIndex(e.x + 1)].Store(a - e.y, value); + } +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + access(lo, hi, true); + if (missing_hi != 0) { + access(missing_lo, missing_hi, false); + } +} +"#; + + /// What a submission that missed memory wrote through the page table + /// leaves the host copies right after it, so the next submission reads + /// title memory's bytes (run shards20: garbage BVH nodes over meshlet + /// buffers until the frame's end); one that missed nothing leaves its + /// writes in the copies. + #[test] + fn a_submission_that_missed_leaves_the_copies_at_once() { + use crate::watch::PAGE; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let (Some(host), Some(views)) = (crate::host::host(), heap()) else { + return; // no host GPU here + }; + let ((write_root, writer), (read_root, reader)) = (pipeline(WRITE), pipeline(SOURCE)); + let (out, out_cpu) = host.shared_buffer(256).unwrap(); + // SAFETY: a live buffer. + let out_gpu = unsafe { out.GetGPUVirtualAddress() }; + // A page of title memory below 2^40, write-watched as the pools. + let p = (0..256u64) + .map(|k| 0x50_0000_0000 + (k << 28)) + // SAFETY: a fresh allocation where nothing is mapped, or none. + .map(|hint| unsafe { VirtualAlloc(hint as *const _, PAGE, MEM_RESERVE | MEM_COMMIT | crate::watch::tests::MEM_WRITE_WATCH, PAGE_READWRITE) } as usize) + .find(|&p| p != 0) + .expect("memory below 2^40"); + let at = p + 16; + // SAFETY: our pool, not guarded yet. + unsafe { (at as *mut u32).write_volatile(0x11) }; + crate::shadow::register(p, p as u64, PAGE as u64); + let copy = crate::shadow::find(p as u64, PAGE as u64).unwrap(); + let list = host.new_list().unwrap(); + // One submission of one dispatch; the list is open again after it. + let submit = |root: &windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, + pso: &windows::Win32::Graphics::Direct3D12::ID3D12PipelineState, + uav: Option, + constants: &[u32]| { + let map = bind(&list, OURS).expect("a page table"); + // SAFETY: an open list, live objects of ours. + unsafe { + list.list.SetDescriptorHeaps(&[Some(views.heap.clone())]); + list.list.SetComputeRootSignature(root); + list.list.SetComputeRootDescriptorTable(0, views.gpu(0)); + list.list.SetComputeRootShaderResourceView(1, map.table); + list.list.SetComputeRootUnorderedAccessView(2, uav.unwrap_or(map.dirty)); + list.list.SetComputeRoot32BitConstants(3, constants.len() as u32, constants.as_ptr().cast(), 0); + list.list.SetPipelineState(pso); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + list.reset(); + }; + let write = |value: u32, miss: bool| { + // Memory no copy holds, in a 256 MiB region with no block. + let missing: u64 = if miss { 0xff_f000_0000 } else { 0 }; + let constants = [at as u32, (at >> 32) as u32, value, missing as u32, (missing >> 32) as u32]; + submit(&write_root, &writer, None, &constants); + }; + let read = || -> u32 { + submit(&read_root, &reader, Some(out_gpu), &[at as u32, (at >> 32) as u32, 0]); + // SAFETY: the mapped output, the GPU done with it. + unsafe { out_cpu.cast::().read_volatile() } + }; + // SAFETY: our pool. + let title = || unsafe { (at as *const u32).read_volatile() }; + write(0x33, true); + // Another test's submission may have refreshed the copy already. + let held = copy.read_host(at as u64, 1)[0]; + assert!(!copy.clean() || held == 0x11, "the written page counts as changed at once"); + assert_eq!(title(), 0x11, "nothing went back"); + assert_eq!(read(), 0x11, "the next submission reads title memory's bytes"); + // Unless another test ends a frame meanwhile (its retake is right). + let frame = FRAMES.load(std::sync::atomic::Ordering::Relaxed); + write(0x44, false); + let kept = read(); + if FRAMES.load(std::sync::atomic::Ordering::Relaxed) == frame { + assert_eq!(kept, 0x44, "a submission that missed nothing keeps its writes"); + } + crate::shadow::unregister(p, p as u64); + drop(copy); + } } diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 6671d4b2e4..2df92a7413 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -71,6 +71,12 @@ pub(crate) extern "system" fn add_ref(this: This) -> u32 { unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 } +/// An object's reference count. +pub(crate) fn refs(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + unsafe { &*this }.refs.load(Ordering::Acquire) +} + pub(crate) extern "system" fn release(this: This) -> u32 { // SAFETY: `this` is one of our objects. let refs = &unsafe { &*this }.refs; diff --git a/crates/victory-gpu/src/placement.rs b/crates/victory-gpu/src/placement.rs new file mode 100644 index 0000000000..7c0afbbc35 --- /dev/null +++ b/crates/victory-gpu/src/placement.rs @@ -0,0 +1,285 @@ +//! Host textures placed in heaps made ahead instead of committed one by +//! one: a new shot brings hundreds of textures, and the host spent most of +//! a frame making them (300 textures, 430 MB on the RX 6700 XT: committed +//! 255 ms; one heap 32 ms, then placed 3 ms). +//! +//! Textures without render-target, depth or unordered-access use, up to a +//! quarter of a heap, go into heaps of [`HEAP`] bytes, first fit. A +//! texture's range is free again once nothing else holds its resource +//! (heap slots keep views' resources until the running submission has run, +//! lists until they are reset), so no view or list sees its memory reused. +//! Empty heaps past [`SPARE`] are released. + +use std::collections::BTreeMap; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +/// Bytes of one heap. +const HEAP: u64 = 64 << 20; +/// Empty heaps kept for the next textures. +const SPARE: usize = 2; +/// Placement alignment of textures that are not render targets. +const ALIGN: u64 = 64 << 10; + +/// Where a texture lies: heap, offset and bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Placement { + heap: u64, + offset: u64, + size: u64, +} + +/// A heap and its free ranges (offset → bytes). +struct Heap { + heap: ID3D12Heap, + id: u64, + free: BTreeMap, +} + +#[derive(Default)] +struct Heaps { + heaps: Vec, + next: u64, + /// Ranges whose texture may still be held elsewhere, with a holder of + /// our own. + pending: Vec<(ID3D12Resource, Placement)>, +} + +// SAFETY: D3D12 heaps and resources are free-threaded; used under the lock. +unsafe impl Send for Heaps {} + +static HEAPS: Mutex> = Mutex::new(None); + +/// The first range of `free` that fits `size` bytes at `align`: its +/// offset, taken out of `free`. +fn take(free: &mut BTreeMap, size: u64, align: u64) -> Option { + let (&start, &len, at) = free.iter().find_map(|(s, l)| { + let at = s.next_multiple_of(align); + (at + size <= s + l).then_some((s, l, at)) + })?; + free.remove(&start); + if at > start { + free.insert(start, at - start); + } + if at + size < start + len { + free.insert(at + size, start + len - at - size); + } + Some(at) +} + +/// Gives `[offset, offset + size)` back to `free`, joined with its +/// neighbours. +fn give(free: &mut BTreeMap, offset: u64, size: u64) { + let (mut start, mut end) = (offset, offset + size); + if let Some((&s, &l)) = free.range(..start).next_back() + && s + l == start + { + free.remove(&s); + start = s; + } + if let Some(&l) = free.get(&end) { + free.remove(&end); + end += l; + } + free.insert(start, end - start); +} + +/// Whether a resource has no holder but the one passed. +fn last_holder(resource: &ID3D12Resource) -> bool { + // SAFETY: a live COM object; one reference taken and given back. + unsafe { + let raw = resource.as_raw(); + let unknown = &*(raw as *const *const windows::core::IUnknown_Vtbl); + ((**unknown).AddRef)(raw); + ((**unknown).Release)(raw) == 1 + } +} + +impl Heaps { + /// Frees the pending ranges nothing else holds now, and releases empty + /// heaps past [`SPARE`]. + fn reap(&mut self) { + let mut i = 0; + while i < self.pending.len() { + if last_holder(&self.pending[i].0) { + let (_, p) = self.pending.swap_remove(i); + if let Some(h) = self.heaps.iter_mut().find(|h| h.id == p.heap) { + give(&mut h.free, p.offset, p.size); + } + } else { + i += 1; + } + } + let empty = |h: &Heap| h.free.get(&0) == Some(&HEAP); + let mut spare = 0; + self.heaps.retain(|h| { + if !empty(h) { + return true; + } + spare += 1; + spare <= SPARE + }); + } + + /// A range of `size` bytes: in a heap with room, else in a new heap. + fn allocate(&mut self, device: &ID3D12Device, size: u64, align: u64) -> Option<(ID3D12Heap, Placement)> { + for h in &mut self.heaps { + if let Some(offset) = take(&mut h.free, size, align) { + return Some((h.heap.clone(), Placement { heap: h.id, offset, size })); + } + } + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: ALIGN, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + // SAFETY: plain creation, our out pointer. + unsafe { device.CreateHeap(&desc, &mut heap) }.ok()?; + let heap = heap?; + crate::host::name(&heap, || "texture heap".into()); + let id = self.next; + self.next += 1; + let mut free = BTreeMap::new(); + free.insert(0, HEAP); + let offset = take(&mut free, size, align)?; + self.heaps.push(Heap { heap: heap.clone(), id, free }); + Some((heap, Placement { heap: id, offset, size })) + } +} + +/// Whether a texture of `desc` goes into a heap: no render-target, depth or +/// unordered-access use, and at most a quarter of a heap. +pub(crate) fn fits(device: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> bool { + const USES: i32 = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 + | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 + | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 + | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0; + if desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || desc.Flags.0 & USES != 0 || desc.SampleDesc.Count > 1 { + return false; + } + // SAFETY: a plain query. + let info = unsafe { device.GetResourceAllocationInfo(0, &[*desc]) }; + info.SizeInBytes != u64::MAX && info.SizeInBytes <= HEAP / 4 && info.Alignment <= ALIGN +} + +/// Room for a texture of `desc` in a heap ([`fits`] first): the heap and +/// the placement, which the texture gives back with [`free`]. +pub(crate) fn place(device: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> Option<(ID3D12Heap, Placement)> { + // SAFETY: a plain query. + let info = unsafe { device.GetResourceAllocationInfo(0, &[*desc]) }; + let size = info.SizeInBytes.next_multiple_of(ALIGN); + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = heaps.get_or_insert_with(Heaps::default); + heaps.reap(); + heaps.allocate(device, size, info.Alignment.max(ALIGN)) +} + +/// A range [`place`] gave whose texture could not be made there. +pub(crate) fn unplace(p: Placement) { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(h) = heaps.as_mut().and_then(|hs| hs.heaps.iter_mut().find(|h| h.id == p.heap)) { + give(&mut h.free, p.offset, p.size); + } +} + +/// The texture at `p` is let go of: its range is free again once nothing +/// else holds `resource` (checked at the next placements and passes). +pub(crate) fn free(resource: ID3D12Resource, p: Placement) { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(h) = heaps.as_mut() { + h.pending.push((resource, p)); + h.reap(); + } +} + +/// Bytes of heap space free for textures (after freeing what nothing +/// holds now): the card's memory they take is not in use. +pub(crate) fn free_bytes() -> u64 { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(h) = heaps.as_mut() else { return 0 }; + h.reap(); + h.heaps.iter().flat_map(|h| h.free.values()).sum() +} + +/// Heaps of textures held, and their used and free bytes (after freeing +/// what nothing holds now), for the statistics line. +pub(crate) fn stats() -> (usize, u64, u64) { + let mut heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(h) = heaps.as_mut() else { return (0, 0, 0) }; + h.reap(); + let free: u64 = h.heaps.iter().flat_map(|h| h.free.values()).sum(); + (h.heaps.len(), h.heaps.len() as u64 * HEAP - free, free) +} + +impl Placement { + /// Its offset in its heap. + pub(crate) fn offset(&self) -> u64 { + self.offset + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A texture's range is not handed out again while anything else holds + /// its resource (a view's slot, a list), and is once nothing does. + #[test] + fn a_range_is_reused_only_once_nothing_holds_its_texture() { + use windows::Win32::Graphics::Dxgi::Common::*; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: DXGI_FORMAT_BC1_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(fits(&host.device, &desc)); + let mut heaps = Heaps::default(); + let (heap, a) = heaps.allocate(&host.device, ALIGN, ALIGN).unwrap(); + let mut texture: Option = None; + // SAFETY: a range of the heap, our out pointer. + unsafe { host.device.CreatePlacedResource(&heap, a.offset(), &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut texture) }.unwrap(); + let texture = texture.unwrap(); + let held = texture.clone(); + heaps.pending.push((texture, a)); + heaps.reap(); + let (_, b) = heaps.allocate(&host.device, ALIGN, ALIGN).unwrap(); + assert_ne!(b, a, "still held: not handed out"); + drop(held); + heaps.reap(); + let (_, c) = heaps.allocate(&host.device, ALIGN, ALIGN).unwrap(); + assert_eq!(c, a, "nothing holds it: free again"); + } + + #[test] + fn ranges_are_taken_first_fit_and_joined_when_given_back() { + let k = 64 << 10; + let mut free = BTreeMap::from([(0, 10 * k)]); + let a = take(&mut free, 3 * k, k).unwrap(); + let b = take(&mut free, 2 * k, k).unwrap(); + let c = take(&mut free, 4 * k, k).unwrap(); + assert_eq!((a, b, c), (0, 3 * k, 5 * k)); + assert_eq!(take(&mut free, 2 * k, k), None, "one 64 KiB range left"); + give(&mut free, b, 2 * k); + assert_eq!(take(&mut free, 3 * k, k), None, "two ranges of 2 and 1, not joined"); + give(&mut free, c, 4 * k); + assert_eq!(free, BTreeMap::from([(3 * k, 7 * k)]), "joined with both neighbours"); + give(&mut free, a, 3 * k); + assert_eq!(free, BTreeMap::from([(0, 10 * k)])); + // An aligned range inside a free one keeps the padding before it. + let mut free = BTreeMap::from([(k, 10 * k)]); + assert_eq!(take(&mut free, k, 4 * k), Some(4 * k)); + assert_eq!(free, BTreeMap::from([(k, 3 * k), (5 * k, 6 * k)])); + } +} diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index fe1895cab1..a30b48a99e 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -1,9 +1,8 @@ //! Console primitive types the host lacks. A rectangle list gives three -//! corners per rectangle, the second the one between the other two, and -//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's -//! full-screen rectangles come as top left, bottom left, bottom right); on -//! the host each rectangle becomes two triangles, with the fourth vertex -//! made from the other three on the CPU. +//! corners per rectangle, in any order, and the hardware adds the fourth +//! opposite the right angle (`victory_shader::emit::right_angle`); on the +//! host each rectangle becomes two triangles, with the fourth vertex made +//! from the other three on the CPU when no geometry shader does it. //! //! shortcut: the fourth vertex is computed from vertex inputs, not from //! vertex shader outputs as the hardware does; that is the same for vertex @@ -13,8 +12,11 @@ //! next one, which the layout allows). /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six -/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both -/// triangles turn the same way. `elements` are (byte offset, format). +/// vertices each in `dst`: `(v0, v1, v2)` and `(va, vb, v3)`, so both +/// triangles turn the same way, with the right angle `vc` picked from the +/// first float element of two or more components (taken as the position; +/// none: at `v1`), `va` before it, `vb` after it and `v3 = va + vb - vc`. +/// `elements` are (byte offset, format). pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { if stride == 0 { return; @@ -27,11 +29,23 @@ pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: .zip(dst.chunks_exact_mut(out_rect)) { let v = |i: usize| &rect[i * stride..(i + 1) * stride]; - for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { + let right = elements + .iter() + .find_map(|&(offset, format)| { + let at = offset as usize; + let (n, kind) = components(format)?; + let float = matches!(kind, Kind::F32 | Kind::F16); + (float && n >= 2 && stride.saturating_sub(at) / kind.bytes() >= 2).then(|| { + victory_shader::emit::right_angle([0, 1, 2].map(|i| [0, 1].map(|k| kind.read(&v(i)[at..], k)))) + }) + }) + .unwrap_or(1); + let (a, b) = ((right + 2) % 3, (right + 1) % 3); + for (slot, i) in [0, 1, 2, a, b].into_iter().enumerate() { out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i)); } let fourth = &mut out[5 * stride..]; - fourth.copy_from_slice(v(0)); + fourth.copy_from_slice(v(a)); for &(offset, format) in elements { let at = offset as usize; let Some((n, kind)) = components(format) else { @@ -42,7 +56,7 @@ pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: let inside = stride.saturating_sub(at) / kind.bytes(); for c in 0..n.min(inside) { let get = |i: usize| kind.read(&v(i)[at..], c); - let value = get(0) + get(2) - get(1); + let value = get(a) + get(b) - get(right); kind.write(&mut fourth[at..], c, value); } } @@ -203,6 +217,30 @@ mod tests { assert_eq!(half_to_f32(0xc000), -2.0); } + /// The tiled lighting's order (top left, bottom left, top right: the + /// right angle first) completes at the bottom right, the second + /// triangle (v2, v1, v3); a triangle that is no rectangle's keeps its + /// winding in both halves. + #[test] + fn rectangles_complete_opposite_their_right_angle() { + let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat(); + let src = [vertex(0.0, 0.0), vertex(0.0, 1.0), vertex(1.0, 0.0)].concat(); + let mut dst = vec![0u8; 6 * 8]; + expand_rects(&src, &mut dst, 8, &[(0, 16)]); + assert_eq!(dst[24..], [&src[16..24], &src[8..16], &vertex(1.0, 1.0)[..]].concat()[..]); + let read = |d: &[u8], i: usize| { + let f = |k: usize| f32::from_le_bytes(d[i * 8 + k * 4..i * 8 + k * 4 + 4].try_into().unwrap()); + [f(0), f(1)] + }; + let turn = |d: &[u8], i: usize| { + let [a, b, c] = [i, i + 1, i + 2].map(|k| read(d, k)); + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + }; + let src = [vertex(0.0, 0.0), vertex(3.0, 1.0), vertex(1.0, 0.0)].concat(); + expand_rects(&src, &mut dst, 8, &[(0, 16)]); + assert!(turn(&dst, 0) * turn(&dst, 3) > 0.0, "same winding"); + } + /// A rounding that carries out of the mantissa raises the exponent /// (the carry used to be or-ed into an odd exponent, halving the value). #[test] diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 99a0d07a73..3da261b7be 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -110,20 +110,25 @@ extern "system" fn release(this: This) -> u32 { object::release_boxed::(this) } -/// Runs the lists' host lists and waits for them (decision 0007). -extern "system" fn execute(_: This, count: u32, lists: *const This) { +/// Queues the lists' host lists behind what the queue holds, and runs what +/// may run (`crate::hold`; decision 0007). +extern "system" fn execute(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } #[cfg(windows)] - if let Some(host) = crate::host::host() { + if crate::host::host().is_some() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; - let host_lists: Vec<_> = lists - .iter() - .filter_map(|&l| crate::list::host_list(l)) - .collect(); - host.execute(&host_lists); + let mut held = held(); + for &l in lists { + for segment in crate::list::segments(l) { + let waits = segment.waits(); + held.push(this as usize, Item::Segment(segment, waits)); + } + } + account().submissions += 1; + pump(&mut held, Why::Submission); return; } static ONCE: AtomicBool = AtomicBool::new(false); @@ -132,6 +137,213 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) { } } +/// What ran held work: the title's submission, a queue's Signal or Wait, a +/// CPU fence call, PresentX, or our timer. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Why { + Submission, + Signal, + Wait, + Fence, + Present, + Timer, +} + +#[cfg(windows)] +use crate::hold::Item; + +/// Every queue's held work. +#[cfg(windows)] +type Holding = crate::hold::Held>; + +#[cfg(windows)] +static HELD: std::sync::Mutex = std::sync::Mutex::new(crate::hold::Held::new()); + +#[cfg(windows)] +fn held() -> std::sync::MutexGuard<'static, Holding> { + HELD.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Runs held work that may run now (`why` for the frame line). +pub(crate) fn pump_held(why: Why) { + #[cfg(windows)] + pump(&mut held(), why); + #[cfg(not(windows))] + let _ = why; +} + +/// The same unless another thread is at it (calls that poll: a fence's +/// value, our timer). +pub(crate) fn pump_held_if_free(why: Why) { + #[cfg(windows)] + if let Ok(mut held) = HELD.try_lock() { + pump(&mut held, why); + } + #[cfg(not(windows))] + let _ = why; +} + +/// How long a queue's head may wait before it runs anyway. +// shortcut: a safety valve against a wait nothing satisfies (a write we do +// not make), which would hold the title's fences until its 30 s watchdog +// ends the run; counted and logged, remove once runs show it never fires. +#[cfg(windows)] +const VALVE: std::time::Duration = std::time::Duration::from_secs(10); + +#[cfg(windows)] +fn pump(held: &mut Holding, why: Why) { + if held.is_empty() { + return; + } + let Some(host) = crate::host::host() else { return }; + let read = read_value; + for (queue, waits) in held.force_older_than(VALVE) { + account().forced += 1; + tracing::warn!(queue = kind(queue), ?waits, "held work runs without its waits after {VALVE:?} (safety valve)"); + } + let fence = |f: usize| crate::fence::value(f as This); + let started = std::time::Instant::now(); + let mut ran = std::time::Duration::ZERO; + let mut run = |_: usize, segments: Vec>| { + let lists: Vec<&crate::host::HostList> = segments.iter().map(|s| &**s).collect(); + let at = std::time::Instant::now(); + host.execute(&lists); + ran += at.elapsed(); + drop(lists); + segments.into_iter().for_each(crate::list::recycle); + }; + let mut signal = |f: usize, value: u64| { + crate::fence::set(f as This, value); + crate::fence::let_go(f as This); + }; + let pumped = held.pump(&mut crate::hold::World { + read: &read, + fence: &fence, + run: &mut run, + signal: &mut signal, + }); + if pumped.segments > 0 || pumped.unknown > 0 { + let mut a = account(); + a.pump += started.elapsed().saturating_sub(ran); + a.pieces += pumped.pieces; + a.segments += pumped.segments; + a.unknown += pumped.unknown; + for (queue, waited) in pumped.waited { + a.released.push((kind(queue), waited, why)); + } + } + // Once work stays held, a timer tests it every 2 ms: memory the title + // writes from the CPU, or the valve, may let it go with no call of ours. + if held.blocked(&read).is_empty() { + return; + } + static TIMER: std::sync::Once = std::sync::Once::new(); + TIMER.call_once(|| { + let _ = std::thread::Builder::new().name("victory held work".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_millis(2)); + pump_held_if_free(Why::Timer); + }); + }); +} + +/// The value a wait tests (4 or 8 bytes), if the memory can be read. +#[cfg(windows)] +fn read_value(address: u64, bytes: u8) -> Option { + let mut value = [0u8; 8]; + crate::host::read_into(address as *const u8, &mut value[..usize::from(bytes.min(8))]).then(|| u64::from_le_bytes(value)) +} + +/// A queue's type, for logs (0 graphics, 2 compute, 3 copy). Titles do not +/// release queues that hold work. +#[cfg(windows)] +fn kind(queue: usize) -> u32 { + self::queue(queue as This).kind +} + +/// What queues did with held work since the last presented frame. +#[cfg(windows)] +#[derive(Default)] +struct Account { + submissions: u32, + pieces: u32, + segments: u32, + /// Segments that waited: queue type, how long, what ran them. + released: Vec<(u32, std::time::Duration, Why)>, + unknown: u32, + forced: u32, + mappings: u32, + /// Time in the pump outside host submissions. + pump: std::time::Duration, +} + +#[cfg(windows)] +fn account() -> std::sync::MutexGuard<'static, Account> { + static ACCOUNT: std::sync::OnceLock> = std::sync::OnceLock::new(); + ACCOUNT.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The frame line of held work: what waited, how long and what released it, +/// and what is still held at the present, with the waits that do not hold. +#[cfg(windows)] +fn account_frame(frame: u64) { + let (cuts, early) = crate::list::take_cuts(); + let (fence_waits, fence_waited) = crate::fence::take_waited(); + let a = std::mem::take(&mut *account()); + let blocked = held().blocked(&read_value); + if a.released.is_empty() && blocked.is_empty() && a.forced == 0 && a.unknown == 0 && a.mappings == 0 { + return; + } + let longest = a.released.iter().map(|r| r.1).max().unwrap_or_default(); + let mut by = [0u32; 6]; + for r in &a.released { + by[r.2 as usize] += 1; + } + tracing::info!( + frame, + submissions = a.submissions, + pieces = a.pieces, + segments = a.segments, + cuts, + early_resets = early, + waited = a.released.len(), + longest_ms = longest.as_secs_f64() * 1e3, + pump_ms = a.pump.as_secs_f64() * 1e3, + fence_waits, + fence_wait_ms = fence_waited.as_secs_f64() * 1e3, + "held work this frame (submissions; host submissions, segments; lists cut at waits; lists reset or released \ + while held, each keeping its own host list; segments that waited, released by \ + submission/signal/wait/fence/present/timer {by:?}; time in the pump outside host submissions; events the title waited on for fence values and their summed waits); held at the present: {}", + blocked.len() + ); + tracing::debug!( + frame, + "held work released this frame (queue type, ms, by): {:?}", + a.released.iter().map(|(k, d, w)| (k, d.as_secs_f64() * 1e3, w)).collect::>() + ); + for (queue, items, waited, unmet) in &blocked { + let level_warn = blocked.len() > 1; + let unmet: Vec = unmet + .iter() + .map(|w| format!("{:#x} cmp {} {:#x} (is {:?})", w.address, w.comparison, w.reference, read_value(w.address, w.bytes))) + .collect(); + if level_warn { + tracing::warn!(frame, queue = kind(*queue), items, waited_ms = waited.as_millis(), ?unmet, "two or more queues hold work at the present"); + } else { + tracing::info!(frame, queue = kind(*queue), items, waited_ms = waited.as_millis(), ?unmet, "a queue holds work at the present"); + } + } + if a.forced > 0 || a.unknown > 0 || a.mappings > 0 { + tracing::warn!( + frame, + forced = a.forced, + unknown = a.unknown, + mappings = a.mappings, + "held work: run without its waits (valve), waits with an unknown comparison (taken as holding), \ + page mappings done ahead of held work" + ); + } +} + /// The start of a present plane: frame token, then the plane's resources. #[repr(C)] pub(crate) struct Plane { @@ -145,7 +357,7 @@ extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: execute(this, count, lists); } /// Signal with sync settings for the top and bottom of the pipe; our -/// submissions are complete when they return, so it signals at once. +/// submissions are complete when they run, so it signals as Signal does. extern "system" fn signal2_x( this: This, fence: This, @@ -157,15 +369,48 @@ extern "system" fn signal2_x( } /// Markers and events only matter to profilers. extern "system" fn marker(_: This) {} -extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { +/// At once, or behind the work the queue holds (its fence, and the memory +/// the title reads it at, move only once that work has run). +extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } - crate::fence::signal(fence, value) + #[cfg(windows)] + { + let mut held = held(); + if held.holds_work(this as usize) { + crate::fence::keep(fence); + held.push(this as usize, Item::Signal(fence as usize, value)); + } else { + crate::fence::set(fence, value); + } + // Another queue may wait for this fence. + pump(&mut held, Why::Signal); + } + #[cfg(not(windows))] + { + let _ = this; + crate::fence::set(fence, value); + } + S_OK } -/// Nothing runs on the queue, so waiting for a fence never blocks it. -extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT { - if fence.is_null() { E_INVALIDARG } else { S_OK } +/// The queue's later work waits until the fence reaches `value`. +/// +/// shortcut: the fence is not kept alive while the queue waits for it; +/// Grand Theft Auto VI makes no queue wait for a fence. +extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + #[cfg(windows)] + if crate::host::host().is_some() && crate::fence::value(fence) < value { + let mut held = held(); + held.push(this as usize, Item::FenceWait(fence as usize, value)); + pump(&mut held, Why::Wait); + } + #[cfg(not(windows))] + let _ = (this, value); + S_OK } /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { @@ -227,7 +472,6 @@ fn system_timestamp() -> u64 { /// Frames presented so far. static FRAMES: AtomicU64 = AtomicU64::new(0); -#[cfg(feature = "diagnostics")] pub(crate) fn presented() -> u64 { FRAMES.load(Ordering::Relaxed) } @@ -242,7 +486,15 @@ extern "system" fn present( plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { + // What may run before the frame is shown does. + // shortcut: PresentX does not wait behind work the queue still holds (it + // shows the frame as far as it ran); the frame line names such work. + pump_held(Why::Present); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(windows)] + account_frame(frame); + #[cfg(feature = "diagnostics")] + crate::frame::presented(); if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); #[cfg(windows)] @@ -292,7 +544,7 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let shown = host.present(texture, state, frame); + let shown = host.present(&texture, state, frame); crate::resource::host_transition(resource, state); #[cfg(feature = "diagnostics")] blinks(frame, resource, state, shown); @@ -362,10 +614,12 @@ const PAGE: u64 = 64 << 10; /// pages of a pool (memory the title mapped physical pages into) at the /// batches' addresses. Grand Theft Auto VI streams textures into pool pages /// and maps them into its tiled heap this way (title+0xf2c470, ranges of -/// one constant page or of unmapped pages). Done at once: every earlier -/// submission has run. +/// one constant page or of unmapped pages). Done at once. +/// +/// shortcut: done ahead of work the queue still holds (counted in the frame +/// line); queue it as an item like Signal if that count is not 0. extern "system" fn copy_page_mappings( - _: This, + this: This, count: u32, batches: *const PageBatch, pool: u64, @@ -378,6 +632,12 @@ extern "system" fn copy_page_mappings( if batches.is_null() && count > 0 { return E_INVALIDARG; } + #[cfg(windows)] + if held().holds_work(this as usize) { + account().mappings += 1; + } + #[cfg(not(windows))] + let _ = this; let batches = (count > 0).then(|| { // SAFETY: the title passes `count` batches. unsafe { std::slice::from_raw_parts(batches, count as usize) } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 44de43ef22..9dd8d05936 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -227,12 +227,17 @@ fn footprint(desc: &ResourceDesc) -> Option { } /// A format as the host has it. The console's 16-bit depth with stencil -/// (and its typeless views) has no PC format: the 24-bit ones stand in. +/// (and its typeless views) has no PC format: the 32-bit float ones stand +/// in, so that depth its shaders write through unordered views +/// (`crate::twin`) arrives as the very float a draw rasterises; copied into +/// 24-bit depth it never tested EQUAL against a draw on the RX 6700 XT. +/// shortcut: a depth bias on such a target counts in float steps, not +/// 1/65535; scale it if a title's 16-bit depth biased draws show acne. pub(crate) fn pc_format(format: u32) -> u32 { match format { - 118 => 45, - 119 => 46, - 120 => 47, + 118 => 20, + 119 => 21, + 120 => 22, other => other, } } @@ -316,11 +321,11 @@ fn mip_count(desc: &ResourceDesc) -> u32 { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct PlacedFootprint { pub(crate) offset: u64, - format: u32, - width: u32, - height: u32, - depth: u32, - row_pitch: u32, + pub(crate) format: u32, + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) depth: u32, + pub(crate) row_pitch: u32, } impl PlacedFootprint { @@ -331,6 +336,27 @@ impl PlacedFootprint { let last = u64::from(self.width).div_ceil(block) * element; Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) } + + /// The byte ranges (from the footprint's start) that a `size` texel + /// region at texel `at` covers: one per row of blocks; `None` if the + /// format has no size or the region leaves the footprint. + pub(crate) fn rows(&self, at: [u32; 3], size: [u32; 3]) -> Option> { + let (element, block) = element(self.format)?; + let blocks = |texels: u32| u64::from(texels).div_ceil(block); + let [x, y, z] = at.map(u64::from); + let (w, h, d) = (blocks(size[0]), blocks(size[1]), u64::from(size[2])); + let (x, y) = (x / block, y / block); + if x + w > blocks(self.width) || y + h > blocks(self.height) || z + d > u64::from(self.depth) { + return None; + } + let pitch = u64::from(self.row_pitch); + let slice = pitch * blocks(self.height); + Some( + (z..z + d) + .flat_map(|k| (y..y + h).map(move |r| (k * slice + r * pitch + x * element, w * element))) + .collect(), + ) + } } const _: () = assert!(size_of::() == 32); @@ -751,10 +777,14 @@ struct Resource { heap: HeapProperties, heap_flags: u32, backing: Backing, - /// Textures also live on the host GPU (decision 0007); buffers do not - /// yet. + /// Textures also live on the host GPU (decision 0007), made on first use + /// ([`Resource::host`]); buffers do not yet. `None`: not made (yet, or + /// given up by [`evict`]); `Some(None)`: the host refused it. + #[cfg(windows)] + host: std::sync::Mutex>>>, + /// The creation's initial state and clear value, for the host texture. #[cfg(windows)] - host: Option>, + made_with: (u32, Option<[u32; 5]>), } /// A title texture's host copy and the state it is in. The title's barriers @@ -786,6 +816,16 @@ pub(crate) struct HostTexture { bytes: u64, /// A list used it (counted once). used: std::sync::atomic::AtomicBool, + /// A shader-visible heap slot viewed it (diagnostics: [`texture_census`]). + pub(crate) viewed: std::sync::atomic::AtomicBool, + /// The memory it copies, for title textures fed from it. + key: Option, + /// Its range in a heap of textures (`crate::placement`), given back + /// when it goes; `None` for a committed texture. + placement: Option, + /// When the title last used it: presented frame and milliseconds since + /// the first stamp ([`HostTexture::stamp`]). + last: [std::sync::atomic::AtomicU64; 2], } #[cfg(windows)] @@ -811,9 +851,48 @@ impl HostTexture { twin: std::sync::OnceLock::new(), bytes, used: false.into(), + viewed: false.into(), + key: None, + placement: None, + last: [crate::queue::presented().into(), now_ms().into()], } } + /// The title used it now: a list of the title's names it, or a shader + /// read a heap slot viewing it (`crate::descriptor::make_read`). + pub(crate) fn stamp(&self) { + self.stamp_at(crate::queue::presented(), now_ms()); + } + + /// Used at presented frame `frame`, `ms` milliseconds in. + fn stamp_at(&self, frame: u64, ms: u64) { + use std::sync::atomic::Ordering::Relaxed; + self.last[0].store(frame, Relaxed); + self.last[1].store(ms, Relaxed); + } + + /// When the title last used it: presented frame and milliseconds + /// (tests). + #[cfg(test)] + pub(crate) fn last_used(&self) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (self.last[0].load(Relaxed), self.last[1].load(Relaxed)) + } + + /// Forgets its uses (tests: a stamp is then seen to happen). + #[cfg(test)] + pub(crate) fn unstamp(&self) { + self.stamp_at(NEVER, 0); + } + + /// Whether the title used it in this presented frame or the last one + /// (made then, named by a list of its own, or read through the heap as + /// the last pass found). + pub(crate) fn used_recently(&self) -> bool { + let frame = self.last[0].load(std::sync::atomic::Ordering::Relaxed); + frame != NEVER && frame.saturating_add(1) >= crate::queue::presented() + } + /// A list uses it: counted the first time (diagnostics of how much of /// the host textures' memory the GPU ever touches). pub(crate) fn note_used(&self) { @@ -854,9 +933,29 @@ pub(crate) fn texture_counts() -> (u64, u64, u64, u64, u64, u64) { (TEXTURES.load(Relaxed), TEXTURE_BYTES.load(Relaxed), USED.load(Relaxed), shared.0, shared.1, shared.2) } +/// Bytes of the live host textures of title textures by what wrote them +/// (index 0 the GPU: render target, depth or unordered access; 1 title +/// memory) and how they were reached (0 by lists, 1 only by heap slots, 2 +/// neither). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_census() -> [[u64; 3]; 2] { + use std::sync::atomic::Ordering::Relaxed; + let mut bytes = [[0; 3]; 2]; + let map = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + for t in map.iter().flat_map(|m| m.values()).filter_map(std::sync::Weak::upgrade) { + let gpu = usize::from(!crate::texture::title_written(&t.texture)); + let reach = if t.used.load(Relaxed) { 0 } else if t.viewed.load(Relaxed) { 1 } else { 2 }; + bytes[1 - gpu][reach] += t.bytes; + } + bytes +} + #[cfg(windows)] impl Drop for HostTexture { fn drop(&mut self) { + if let Some(p) = self.placement.take() { + crate::placement::free(self.texture.clone(), p); + } TEXTURES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); TEXTURE_BYTES.fetch_sub(self.bytes, std::sync::atomic::Ordering::Relaxed); if *self.used.get_mut() { @@ -965,22 +1064,31 @@ pub(crate) mod life { #[cfg(windows)] pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { use windows::core::Interface; - let host = resource(this).host.as_ref()?; + let host = resource(this).host()?; let before = host .state .swap(wanted, std::sync::atomic::Ordering::Relaxed); (before != wanted).then(|| (host.texture.as_raw(), before)) } -/// The host GPU's copy of a title resource, if it has one. +/// The host GPU's copy of a title resource, if it has one (made on first +/// use). Owned: [`evict`] may give the host texture up meanwhile. #[cfg(windows)] -pub(crate) fn host_resource<'a>( - this: This, -) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { +pub(crate) fn host_resource(this: This) -> Option { if this.is_null() { return None; } - resource(this).host.as_deref().map(|h| &h.texture) + resource(this).host().map(|h| h.texture.clone()) +} + +/// A title texture's host copy if it is made, without making it: for work +/// that is no use of the title's (uploads of what heap slots view). +#[cfg(windows)] +pub(crate) fn made_copy(this: This) -> Option> { + if this.is_null() { + return None; + } + resource(this).host.lock().unwrap_or_else(|e| e.into_inner()).clone().flatten() } /// A title texture's host copy, shared, for a list to hold. @@ -989,7 +1097,7 @@ pub(crate) fn host_copy(this: This) -> Option> { if this.is_null() { return None; } - resource(this).host.clone() + resource(this).host() } /// The host description of a title texture: the same, without the @@ -1187,11 +1295,25 @@ fn shared_texture( } return live; } + // Host textures are made on first use, in any order: the new one takes + // the uses of every title texture of the memory, so none replaces it. + let mut d = d; + if let Some(k) = key { + let at = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); + for r in at.get(&address).into_iter().flatten().map(|&r| resource(r as This)) { + if memory_key(address, &r.desc) == Some(k) { + d.flags |= host_desc(&r.desc).map_or(0, |h| h.flags & USES); + } + } + } // shortcut: title textures of a replaced host texture keep it (placed // views move to the new one, `texture_at`); copies (`alias_source`) // bridge the two where the shapes allow. - let t = std::sync::Arc::new(make_texture(&d, state, clear)?); + let mut t = make_texture(&d, state, clear)?; + t.key = key; + let t = std::sync::Arc::new(t); if let Some(k) = key { + remade(&k); if live.is_some() { REPLACED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); tracing::debug!(?k, "a texture memory's host texture replaced by one with more uses or another format"); @@ -1222,13 +1344,14 @@ fn takes(t: &HostTexture, d: &ResourceDesc) -> bool { #[cfg(windows)] fn current(this: This) -> bool { let r = resource(this); - let (Some(h), Some(k)) = (&r.host, memory_key(r.data() as u64, &r.desc)) else { + let made = r.host.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let (Some(Some(h)), Some(k)) = (made, memory_key(r.data() as u64, &r.desc)) else { return true; }; let map = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref() .and_then(|m| m.get(&k)?.upgrade()) - .is_none_or(|live| std::sync::Arc::ptr_eq(&live, h)) + .is_none_or(|live| std::sync::Arc::ptr_eq(&live, &h)) } /// A host texture of host description `d` in GPU memory, castable to @@ -1257,25 +1380,54 @@ fn make_texture(d: &ResourceDesc, state: u32, clear: *const c_void) -> Option = None; let mut castable_formats = if d.flags & DEPTH == 0 { castable(d.format) } else { Vec::new() }; let mut initial = crate::host::legal_for(d.flags, crate::host::texture_state(state)); - if !castable_formats.is_empty() - && let Ok(device) = host.device.cast::() + // In a heap of textures if it fits there (`crate::placement`). + // SAFETY: the description has the host layout (checked size). + let plain = unsafe { std::ptr::from_ref(d).cast::().read_unaligned() }; + let mut placement = None; + if clear_value.is_none() + && crate::placement::fits(&host.device, &plain) + && let Some((heap, p)) = crate::placement::place(&host.device, &plain) { - // SAFETY: the description has the host layout (checked size). - let p = unsafe { std::ptr::from_ref(d).cast::().read_unaligned() }; - // The plain description plus the sampler feedback region (none). - let desc1 = D3D12_RESOURCE_DESC1 { - Dimension: p.Dimension, - Alignment: p.Alignment, - Width: p.Width, - Height: p.Height, - DepthOrArraySize: p.DepthOrArraySize, - MipLevels: p.MipLevels, - Format: p.Format, - SampleDesc: p.SampleDesc, - Layout: p.Layout, - Flags: p.Flags, - SamplerFeedbackMipRegion: Default::default(), + let formats: Vec = castable_formats.iter().map(|&f| DXGI_FORMAT(f as i32)).collect(); + let made = match host.device.cast::() { + Ok(device) if !formats.is_empty() => { + let desc1 = desc1_of(&plain); + // SAFETY: a range of the heap for this description; the + // list of formats lives through the call. + unsafe { + device.CreatePlacedResource2(&heap, p.offset(), &desc1, D3D12_BARRIER_LAYOUT_COMMON, None, Some(&formats), &mut texture) + } + .map(|()| 0) + } + _ => { + // SAFETY: as above. + unsafe { + host.device.CreatePlacedResource(&heap, p.offset(), &plain, D3D12_RESOURCE_STATES(initial as i32), None, &mut texture) + } + .map(|()| { + castable_formats.clear(); + initial + }) + } }; + match made { + Ok(state) => { + initial = state; + placement = Some(p); + } + Err(e) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(error = %e, desc = ?d, "a texture not placed in a heap: committed")); + crate::placement::unplace(p); + texture = None; + } + } + } + if texture.is_none() + && !castable_formats.is_empty() + && let Ok(device) = host.device.cast::() + { + let desc1 = desc1_of(&plain); let formats: Vec = castable_formats.iter().map(|&f| DXGI_FORMAT(f as i32)).collect(); // SAFETY: a host description and our out pointer; the list and the // clear value live through the call. @@ -1326,7 +1478,27 @@ fn make_texture(d: &ResourceDesc, state: u32, clear: *const c_void) -> Option windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_DESC1 { + windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_DESC1 { + Dimension: p.Dimension, + Alignment: p.Alignment, + Width: p.Width, + Height: p.Height, + DepthOrArraySize: p.DepthOrArraySize, + MipLevels: p.MipLevels, + Format: p.Format, + SampleDesc: p.SampleDesc, + Layout: p.Layout, + Flags: p.Flags, + SamplerFeedbackMipRegion: Default::default(), + } } /// A texture's console memory and description; `None` for buffers. @@ -1338,6 +1510,16 @@ pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) } +/// A texture's description as words (the layout of placed views' +/// resource descriptions); `None` for buffers. +pub(crate) fn texture_desc(this: This) -> Option<[u32; 14]> { + let (_, desc) = texture_memory(this)?; + let mut words = [0u32; 14]; + // SAFETY: 56 bytes in the description's layout. + unsafe { words.as_mut_ptr().cast::().write_unaligned(desc) }; + Some(words) +} + /// A texture's format as the title gave it. pub(crate) fn title_format(this: This) -> Option { (!this.is_null()).then(|| resource(this).desc.format) @@ -1353,6 +1535,24 @@ pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { } impl Resource { + /// Its host texture, made the first time it is asked for: a list uses + /// the texture, a heap slot views it, a copy or upload reaches it. Most + /// of the title's textures are never used (decision 0007, "Host + /// textures made on first use"). + #[cfg(windows)] + fn host(&self) -> Option> { + if let Some(made) = self.host.lock().unwrap_or_else(|e| e.into_inner()).clone() { + return made; + } + // Made without the lock held (`shared_texture` takes the memory + // maps, which `evict` holds while it takes this lock). + let (state, clear) = self.made_with; + let clear = clear.as_ref().map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast()); + let made = shared_texture(self.data() as u64, &self.desc, state, clear); + // A texture made meanwhile by another thread is the memory's too. + self.host.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(made).clone() + } + fn data(&self) -> *mut u8 { match self.backing { Backing::Committed(ref memory) => memory.ptr.as_ptr(), @@ -1374,6 +1574,227 @@ fn resource<'a>(this: This) -> &'a Resource { unsafe { &*this.cast::() } } +/// A title texture's host texture if it is made. +#[cfg(windows)] +fn made(r: &Resource) -> Option> { + r.host.lock().unwrap_or_else(|e| e.into_inner()).clone().flatten() +} + +/// Milliseconds since the first call: host textures' use stamps. +#[cfg(windows)] +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 +} + +/// A host texture fed from title memory that the title has not used for +/// this long (and this many presented frames) is given up ([`evict`]). +/// Two minutes: of the textures given up after 20 s, nine in ten were +/// read again within a minute (run evict4). +#[cfg(windows)] +pub(crate) const IDLE_MS: u64 = 120_000; +/// Frames as well as time: in slow runs (seconds a frame) 20 s alone cycled +/// the textures of a cutscene's alternating shots (run evict2), and 30 +/// frames gave up what the menus and loading made (at 30 fps) before the +/// world read it (run evict3). At 30 fps the idle time decides; slower, the +/// card's budget does. +#[cfg(windows)] +pub(crate) const IDLE_FRAMES: u64 = 300; +/// A use stamp's frame for "never" (tests). +#[cfg(windows)] +const NEVER: u64 = u64::MAX; +/// Past this share of the card's memory budget, host textures fed from +/// title memory are given up least recently used first, until the card's +/// use is back under [`BUDGET_LOW`]. +#[cfg(windows)] +const BUDGET_HIGH: f64 = 0.90; +#[cfg(windows)] +const BUDGET_LOW: f64 = 0.85; +/// A texture made again within this many frames of being given up counts +/// as remade soon ([`EVICTIONS`]): too eager an [`IDLE_MS`]. +#[cfg(windows)] +const SOON_FRAMES: u64 = 10; + +/// Host textures given up, their bytes, those made again since, and those +/// made again within [`SOON_FRAMES`]. +#[cfg(windows)] +pub(crate) static EVICTIONS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Memories whose host texture was given up, with the frame it was. +#[cfg(windows)] +static GIVEN_UP: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// A host texture is made for memory `k`: counted if it had been given up. +#[cfg(windows)] +fn remade(k: &MemoryKey) { + use std::sync::atomic::Ordering::Relaxed; + let mut given = GIVEN_UP.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = given.as_mut().and_then(|g| g.remove(k)) { + EVICTIONS[2].fetch_add(1, Relaxed); + if crate::queue::presented().saturating_sub(at) <= SOON_FRAMES { + EVICTIONS[3].fetch_add(1, Relaxed); + } + } +} + +/// Whether host texture `t` may be given up: its contents come from title +/// memory alone (no render target, depth or unordered access, no host copy +/// or resolve wrote it), so a texture made again has them back. +#[cfg(windows)] +fn evictable(t: &HostTexture) -> bool { + t.key.is_some() && crate::texture::title_written(&t.texture) && !t.host_written.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Once per presented frame, before a submission (`Host::execute`, one at a +/// time, the last one has run): gives up host textures fed from title memory +/// that the title has not used for [`IDLE_MS`], and past [`BUDGET_HIGH`] of +/// the card's budget the least recently used ones until [`BUDGET_LOW`]. +#[cfg(windows)] +pub(crate) fn evict_unused() { + use std::sync::atomic::Ordering::Relaxed; + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + let frame = crate::queue::presented(); + if LAST.swap(frame, Relaxed) == frame { + return; + } + let over = crate::host::video_memory().map_or(0, |[(used, budget), _]| { + // Free space in the heaps of textures takes the card's memory but + // is not in use: new textures go there first. + let used = used - crate::placement::free_bytes() as f64 / 1e6; + if used > BUDGET_HIGH * budget { ((used - BUDGET_LOW * budget) * 1e6) as u64 } else { 0 } + }); + evict(frame, now_ms(), over); +} + +/// A host texture and the title textures (resource objects) holding it. +#[cfg(windows)] +pub(crate) type Owned = (std::sync::Arc, Vec); + +/// Gives up the host textures fed from title memory that the title has +/// not used for [`IDLE_MS`] and [`IDLE_FRAMES`] at (`frame`, `now` ms), +/// then least recently used ones until `over` bytes are gone +/// ([`give_up`]). Returns how many and their bytes. +#[cfg(windows)] +fn evict(frame: u64, now: u64, over: u64) -> (u64, u64) { + // Read through the heap since the last pass: used (a slot's read mark is + // reported as new only once, so its first read alone stamped it; run + // evict1 gave up and made again hundreds of textures a frame). + let read = crate::descriptor::read_textures(&crate::shadow::reads_since()); + evict_among(&candidates(), &read, frame, now, over) +} + +/// [`evict`] among `candidates`, with `read` (raw pointers) the host +/// textures shaders read through the heap since the last pass. +#[cfg(windows)] +pub(crate) fn evict_among( + candidates: &[Owned], + read: &std::collections::HashSet, + frame: u64, + now: u64, + over: u64, +) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + for (t, _) in candidates { + if read.contains(&(windows::core::Interface::as_raw(&t.texture) as usize)) { + t.stamp_at(frame, now); + } + } + let uses: Vec<(u64, u64, u64)> = + candidates.iter().map(|(t, _)| (t.last[0].load(Relaxed), t.last[1].load(Relaxed), t.bytes)).collect(); + let chosen = choose(&uses, frame, now, over); + let gone: Vec = chosen.into_iter().map(|i| candidates[i].clone()).collect(); + give_up(&gone, frame) +} + +/// The host textures that may be given up ([`evictable`]), each with the +/// title textures holding it. +#[cfg(windows)] +fn candidates() -> Vec { + let at = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); + let mut by: std::collections::HashMap = std::collections::HashMap::new(); + for &r in at.values().flatten() { + if let Some(t) = made(resource(r as This)).filter(|t| evictable(t)) { + by.entry(std::sync::Arc::as_ptr(&t) as usize).or_insert_with(|| (t, Vec::new())).1.push(r); + } + } + by.into_values().collect() +} + +/// Of textures last used at (frame, ms) taking (bytes) each, those to give +/// up at (`frame`, `now`): every one idle for [`IDLE_FRAMES`] and +/// [`IDLE_MS`], then the least recently used others until `over` bytes are +/// gone (indices). +fn choose(uses: &[(u64, u64, u64)], frame: u64, now: u64, over: u64) -> Vec { + let idle = |&(f, ms, _): &(u64, u64, u64)| frame.saturating_sub(f) >= IDLE_FRAMES && now.saturating_sub(ms) >= IDLE_MS; + let (mut gone, mut rest): (Vec, Vec) = (0..uses.len()).partition(|&i| idle(&uses[i])); + let mut over = over.saturating_sub(gone.iter().map(|&i| uses[i].2).sum()); + rest.sort_by_key(|&i| uses[i].1); + for i in rest { + if over == 0 { + break; + } + over = over.saturating_sub(uses[i].2); + gone.push(i); + } + gone +} + +/// Gives up host textures `gone` at `frame`: first every heap slot viewing +/// one gets a null view (made again when a draw or a shader reads it), then +/// the title textures let go of it. Lists recorded before hold it until +/// they are reset, so no GPU work reads it freed; the next use makes it +/// again from title memory. +/// shortcut: a use racing this (a title thread recording) may view the +/// texture made again in a list that moved the one given up; the pass +/// gives up only textures unused for a while, or the least recently used. +#[cfg(windows)] +fn give_up(gone: &[Owned], frame: u64) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + if gone.is_empty() { + return (0, 0); + } + { + use windows::core::Interface; + let raws = gone.iter().map(|(t, _)| t.texture.as_raw() as usize).collect(); + crate::descriptor::evict(&raws); + } + let at = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); + let live: std::collections::HashSet = at.values().flatten().copied().collect(); + let mut given = GIVEN_UP.lock().unwrap_or_else(|e| e.into_inner()); + let given = given.get_or_insert_with(Default::default); + given.retain(|_, &mut f| frame.saturating_sub(f) <= SOON_FRAMES); + let bytes = gone.iter().map(|(t, _)| t.bytes).sum(); + for (t, owners) in gone { + for &r in owners.iter().filter(|r| live.contains(r)) { + let mut h = resource(r as This).host.lock().unwrap_or_else(|e| e.into_inner()); + if matches!(&*h, Some(Some(x)) if std::sync::Arc::ptr_eq(x, t)) { + *h = None; + } + } + if let Some(k) = t.key { + given.insert(k, frame); + } + } + EVICTIONS[0].fetch_add(gone.len() as u64, Relaxed); + EVICTIONS[1].fetch_add(bytes, Relaxed); + (gone.len() as u64, bytes) +} + +/// Gives up `this`'s host texture as [`evict`] would (tests); false if it +/// has none or may not be given up. +#[cfg(all(windows, test))] +pub(crate) fn give_up_now(this: This) -> bool { + owned(this).is_some_and(|o| give_up(&[o], crate::queue::presented()).0 == 1) +} + +/// `this`'s host texture with the title textures holding it, if it may be +/// given up (tests: [`evict_among`] over textures of their own). +#[cfg(all(windows, test))] +pub(crate) fn owned(this: This) -> Option { + let t = made(resource(this))?; + candidates().into_iter().find(|(c, _)| std::sync::Arc::ptr_eq(c, &t)) +} + // The creation methods' own arguments, passed on. #[allow(clippy::too_many_arguments)] fn hand_out_resource( @@ -1388,25 +1809,25 @@ fn hand_out_resource( ) -> HRESULT { #[cfg(not(windows))] let _ = (state, clear); - #[allow(unused_mut)] // the host texture is set on Windows only - let mut resource = Box::new(Resource { + let resource = Box::new(Resource { object: Object::new(&RESOURCE_FUNCTIONS), desc, heap, heap_flags, backing, #[cfg(windows)] - host: None, + host: std::sync::Mutex::new(None), + // The clear value names the format too: format, then color or + // depth and stencil (5 words), kept for when the texture is made. + #[cfg(windows)] + // SAFETY: the title passes a whole clear value (or null). + made_with: (state, (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() })), }); #[cfg(windows)] - { - resource.host = shared_texture(resource.data() as u64, &desc, state, clear); - } - #[cfg(windows)] if desc.dimension == BUFFER { let at = std::ptr::from_ref::(&resource) as usize; crate::shadow::register(at, resource.data() as u64, desc.width); - } else if resource.host.is_some() { + } else if host_desc(&desc).is_some() { let at = std::ptr::from_ref::(&resource) as usize; let mut map = TEXTURES_AT.lock().unwrap_or_else(|e| e.into_inner()); map.entry(resource.data() as u64).or_default().push(at); @@ -1451,7 +1872,7 @@ pub(crate) fn alias_source(placed: This) -> Option { let a = resource(r); a.desc.flags & WRITTEN != 0 && bytes(&a.desc) == Some(want) - && matches!((&a.host, &b.host), (Some(x), Some(y)) if !std::sync::Arc::ptr_eq(x, y)) + && matches!((made(a), made(b)), (Some(x), Some(y)) if !std::sync::Arc::ptr_eq(&x, &y)) }) } @@ -1459,10 +1880,7 @@ pub(crate) fn alias_source(placed: This) -> Option { impl Drop for Resource { fn drop(&mut self) { #[cfg(feature = "diagnostics")] - if self - .host - .as_ref() - .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) + if made(self).is_some_and(|h| std::sync::Arc::strong_count(&h) > 2) { // Before lists held their textures, this freed a texture that // lists not yet run still named (a GPU page fault). @@ -1477,7 +1895,7 @@ impl Drop for Resource { } } #[cfg(feature = "diagnostics")] - if let Some(h) = &self.host { + if let Some(h) = made(self) { use windows::core::Interface; life::note(h.texture.as_raw() as usize, life::RELEASED, 0, life::holders(&h.texture)); } @@ -1665,6 +2083,19 @@ pub(crate) extern "system" fn create_at_address( static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// Console bytes of the placed textures [`texture_at`] made (they are never +/// released). +#[cfg(windows)] +pub(crate) static PLACED_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Console bytes of a texture of resource description `desc` (as words). +#[cfg(windows)] +pub(crate) fn placed_size(desc: &[u32; 14]) -> Option { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + (d.dimension != BUFFER).then(|| footprint(&d).map(|f| f.size)).flatten() +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] @@ -1701,8 +2132,12 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { if made != S_OK { return None; } + PLACED_BYTES.fetch_add(placed_size(desc).unwrap_or(0), std::sync::atomic::Ordering::Relaxed); map.insert((address, *desc), out as usize); - resource(out).host.is_some().then_some(out) + // Its host texture is made without the map's lock: the textures of the + // slots a submission's shaders read are made several at a time. + drop(map); + resource(out).host().is_some().then_some(out) } pub(crate) extern "system" fn create_placed( @@ -1917,6 +2352,17 @@ pub(crate) fn test_buffer(width: u64) -> This { #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_regions_rows_in_a_footprint() { + // R32_FLOAT (41) 100x8x1, pitch 512. + let f = PlacedFootprint { offset: 4096, format: 41, width: 100, height: 8, depth: 1, row_pitch: 512 }; + assert_eq!(f.rows([2, 3, 0], [10, 2, 1]), Some(vec![(3 * 512 + 8, 40), (4 * 512 + 8, 40)])); + assert_eq!(f.rows([95, 0, 0], [10, 1, 1]), None, "past the width"); + // BC1 (71) 16x16, 8 bytes a 4x4 block, pitch 256: a block row per 4 texel rows. + let bc = PlacedFootprint { offset: 0, format: 71, width: 16, height: 16, depth: 1, row_pitch: 256 }; + assert_eq!(bc.rows([4, 4, 0], [8, 8, 1]), Some(vec![(256 + 8, 16), (2 * 256 + 8, 16)])); + } use crate::object::slot; #[test] @@ -1990,6 +2436,115 @@ mod tests { heap } + /// A title texture's host texture is made when first asked for, and a + /// texture of the same memory made later with more uses (unordered + /// access) shares it: the first one made takes every use the memory's + /// title textures have. + #[cfg(windows)] + #[test] + fn host_textures_are_made_on_first_use_with_every_use_of_their_memory() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |desc: &ResourceDesc| { + let mut out = null; + assert_eq!(create_placed(null, h, 0, desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut out), S_OK); + out + }; + let read = place(&texture(64, 64, 28, 1)); + let written = place(&ResourceDesc { flags: UNORDERED, ..texture(64, 64, 28, 1) }); + assert!(made(resource(read)).is_none() && made(resource(written)).is_none(), "made at creation"); + let first = host_copy(read).expect("a host texture"); + // SAFETY: a live resource. + assert_ne!(unsafe { first.texture.GetDesc() }.Flags.0 as u32 & UNORDERED, 0, "the memory's uses"); + assert!(std::sync::Arc::ptr_eq(&first, &host_copy(written).unwrap()), "shared"); + for r in [read, written] { + assert_eq!(slot::(r, 0x10)(r), 0); + } + assert_eq!(slot::(h, 0x10)(h), 0); + } + + /// Host textures the GPU writes (render target, depth, unordered access) + /// are never given up, and the title releasing its texture frees its + /// host texture (nothing else holds it); one fed from title memory is + /// given up and made again on its next use. + #[cfg(windows)] + #[test] + fn only_textures_fed_from_title_memory_are_given_up() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |offset: u64, desc: &ResourceDesc| { + let mut out = null; + assert_eq!(create_placed(null, h, offset, desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut out), S_OK); + out + }; + let read = place(0, &texture(64, 64, 28, 1)); + let target = place(1 << 18, &ResourceDesc { flags: 1, ..texture(64, 64, 28, 1) }); + let (r, t) = (host_copy(read).unwrap(), host_copy(target).unwrap()); + let listed = candidates(); + assert!(listed.iter().any(|(c, _)| std::sync::Arc::ptr_eq(c, &r)), "fed from title memory"); + assert!(!listed.iter().any(|(c, _)| std::sync::Arc::ptr_eq(c, &t)), "the GPU writes it"); + let (weak_r, weak_t) = (std::sync::Arc::downgrade(&r), std::sync::Arc::downgrade(&t)); + drop((listed, r, t)); + let (r, t) = (weak_r, weak_t); + assert!(!give_up_now(target), "never given up"); + assert!(give_up_now(read)); + // (Not checked freed: a pass in another test may hold it a moment.) + assert!(made(resource(read)).is_none(), "given up"); + drop(r); + assert!(host_copy(read).is_some(), "made again on its next use"); + assert_eq!(slot::(target, 0x10)(target), 0); + assert!(t.upgrade().is_none(), "freed with its title texture"); + assert_eq!(slot::(read, 0x10)(read), 0); + assert_eq!(slot::(h, 0x10)(h), 0); + } + + /// Placed textures asked for from several threads at once: one resource + /// and one host texture for each memory, made side by side. + #[cfg(windows)] + #[test] + fn placed_textures_made_side_by_side_are_one_each() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let memory = vec![0u8; 4 << 16]; + let words: [u32; 14] = [3, 0, 0, 0, 4, 0, 1, 1 | 1 << 16, 28, 1, 0, 0x100, 0, 0]; + let base = memory.as_ptr() as u64; + let made: Vec> = std::thread::scope(|s| { + let threads: Vec<_> = (0..4) + .map(|_| s.spawn(move || (0..4u64).map(|k| texture_at(base + (k << 16), &words).unwrap() as usize).collect::>())) + .collect(); + threads.into_iter().map(|t| t.join().unwrap()).collect() + }); + for k in 0..4 { + assert!(made.iter().all(|m| m[k] == made[0][k]), "one resource for memory {k}"); + assert!(made_copy(made[0][k] as This).is_some(), "with a host texture"); + } + } + + /// Textures idle for the idle time and frames are given up; past the + /// budget the least recently used others follow until the excess is + /// gone. + #[test] + fn idle_textures_go_and_past_the_budget_the_least_recently_used() { + let (frame, now) = (1_000, 1_000_000); + let recent = (frame, now - 1_000, 10); + let idle = (frame - IDLE_FRAMES, now - IDLE_MS, 10); + let older = (frame, now - 5_000, 30); + let uses = [recent, idle, older]; + assert_eq!(choose(&uses, frame, now, 0), vec![1], "idle only"); + assert_eq!(choose(&uses, frame, now, 10), vec![1], "the idle one covers the excess"); + assert_eq!(choose(&uses, frame, now, 11), vec![1, 2], "then the least recently used"); + assert_eq!(choose(&uses, frame, now, 1 << 20), vec![1, 2, 0], "all of them if need be"); + let early = (frame - 1, now - IDLE_MS, 10); + assert!(choose(&[early], frame, now, 0).is_empty(), "too few frames ago"); + } + /// Title textures of one memory share a key in any format of the same /// element; another address, shape, element size or a depth texture is /// another memory. The library's own layout pick resolves as spelled. @@ -2414,7 +2969,7 @@ mod tests { // SAFETY: an open list, live resources, locations in the host layout. unsafe { back.list.ResourceBarrier(&[crate::host::transition( - host_image, + &host_image, D3D12_RESOURCE_STATES(before as i32), D3D12_RESOURCE_STATE_COPY_SOURCE, )]); @@ -2450,6 +3005,176 @@ mod tests { } } + /// A texture region copied into a title buffer through our list and + /// queue: once the list has run, its rows are in the buffer at the + /// footprint's offset and pitch, and nothing else of the buffer moved. + #[cfg(windows)] + #[test] + fn a_texture_read_back_reaches_the_title_buffer() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source, mut target) = (null, null, null); + let created = |desc: &ResourceDesc, state, out: &mut This| { + assert_eq!(create_committed(null, &PROPERTIES, 0, desc, state, null.cast(), iid, out), S_OK); + }; + created(&texture(4, 4, 28, 1), COPY_DEST, &mut image); + created(&buffer(1024), 0, &mut source); + created(&buffer(4096), 0, &mut target); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + let (out, _) = buffer_bytes(target).unwrap(); + // SAFETY: the buffer holds 4096 bytes. + unsafe { std::ptr::write_bytes(out, 0xEE, 4096) }; + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_desc = [0u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed]), &mut queue), + S_OK + ); + assert_eq!( + crate::list::create_allocator(null, 0, &guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24]), &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, 0, allocator, null, &guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55]), &mut list), + S_OK + ); + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { offset: 0, format: 28, width: 4, height: 4, depth: 1, row_pitch: 256 }; + let image_at = Location { resource: image, kind: 0, footprint: rows }; + let from_source = Location { resource: source, kind: 1, footprint: rows }; + // Texels (1..3, 1..3) into the target's footprint at 512, at texel (2, 1). + let into_target = Location { resource: target, kind: 1, footprint: PlacedFootprint { offset: 512, ..rows } }; + let region: [u32; 6] = [1, 1, 0, 3, 3, 1]; + type Copy = extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + let copy = slot::(list, 0x80); + copy(list, &image_at, 0, 0, 0, &from_source, null.cast()); + copy(list, &into_target, 2, 1, 0, &image_at, region.as_ptr().cast()); + slot:: HRESULT>(list, 0x48)(list); + slot::(queue, 0x50)(queue, 1, &list); + // SAFETY: the buffer holds 4096 bytes; the submission has run. + let read = unsafe { std::slice::from_raw_parts(out, 4096) }; + let mut want = vec![0xEEu8; 4096]; + for row in 0..2 { + let (to, from) = (512 + (1 + row) * 256 + 2 * 4, (1 + row) * 256 + 4); + want[to..to + 8].copy_from_slice(&bytes[from..from + 8]); + } + assert!(read == want.as_slice(), "the region's rows, and nothing else"); + } + + /// Two queues, as Grand Theft Auto VI's: a compute list copies a buffer, + /// then waits for a value a graphics list writes at its end, then reads + /// back the texture that graphics list fills. Submitted first, its first + /// part runs at once and the rest waits for the graphics list, then + /// reads what it wrote. + #[cfg(windows)] + #[test] + fn a_list_waiting_for_another_queues_write_reads_what_it_wrote() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source, mut target, mut early, mut words) = (null, null, null, null, null); + let created = |desc: &ResourceDesc, state, out: &mut This| { + assert_eq!(create_committed(null, &PROPERTIES, 0, desc, state, null.cast(), iid, out), S_OK); + }; + // A plain texture: its contents are the host's from the graphics + // list's submission on (`texture::host_writes`), not from when the + // compute list was recorded. + created(&texture(4, 4, 28, 1), COPY_DEST, &mut image); + created(&buffer(1024), 0, &mut source); + created(&buffer(1024), 0, &mut target); + created(&buffer(1024), 0, &mut early); + created(&buffer(256), 0, &mut words); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + let (out, _) = buffer_bytes(target).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + unsafe { std::ptr::write_bytes(out, 0xEE, 1024) }; + let (flag, _) = buffer_bytes(words).unwrap(); + let flag = flag.cast::(); + + let queue_iid = guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed]); + let allocator_iid = guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24]); + let list_iid = guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55]); + let (mut graphics, mut compute, mut allocator, mut drawing, mut computing) = (null, null, null, null, null); + for (kind, queue) in [(0u32, &mut graphics), (2, &mut compute)] { + let desc = [kind, 0, 0, 0]; + assert_eq!(crate::queue::create(null, desc.as_ptr().cast(), &queue_iid, queue), S_OK); + } + assert_eq!(crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), S_OK); + for (kind, list) in [(0u32, &mut drawing), (2, &mut computing)] { + assert_eq!(crate::list::create_list(null, 0, kind, allocator, null, &list_iid, list), S_OK); + } + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { offset: 0, format: 28, width: 4, height: 4, depth: 1, row_pitch: 256 }; + let image_at = Location { resource: image, kind: 0, footprint: rows }; + type Copy = extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + type CopyBuffer = extern "system" fn(This, This, u64, This, u64, u64); + type Close = extern "system" fn(This) -> HRESULT; + type Execute = extern "system" fn(This, u32, *const This); + const GREATER_EQUAL: u32 = 7; + + // Compute: [copy source → early][wait flag ≥ 1][image → target]. + slot::(computing, 0x78)(computing, early, 0, source, 0, 1024); + crate::list::wait64(computing, flag as u64, GREATER_EQUAL, 1, 0); + let into_target = Location { resource: target, kind: 1, footprint: rows }; + slot::(computing, 0x80)(computing, &into_target, 0, 0, 0, &image_at, null.cast()); + slot::(computing, 0x48)(computing); + // Graphics: [source → image][flag = 1 at its end]. + let from_source = Location { resource: source, kind: 1, footprint: rows }; + slot::(drawing, 0x80)(drawing, &image_at, 0, 0, 0, &from_source, null.cast()); + crate::list::write64(drawing, flag as u64, 1, 0, 0); + slot::(drawing, 0x48)(drawing); + + slot::(compute, 0x50)(compute, 1, &computing); + let (copied, _) = buffer_bytes(early).unwrap(); + // SAFETY: the buffers hold 1024 bytes; nothing runs meanwhile. + let read = |at: *mut u8| unsafe { std::slice::from_raw_parts(at, 1024) }.to_vec(); + assert_eq!(read(copied), bytes, "the part before the wait ran"); + assert!(read(out).iter().all(|&b| b == 0xEE), "the part after it waits"); + // SAFETY: the buffer holds 256 bytes. + assert_eq!(unsafe { flag.read_volatile() }, 0); + // D3D12 lets the title reset a list as soon as it has submitted it: + // the held part keeps its own host list and what it reads. + type Reset = extern "system" fn(This, This, This) -> HRESULT; + assert_eq!(slot::(computing, 0x50)(computing, allocator, null), S_OK); + slot::(computing, 0x48)(computing); + + slot::(graphics, 0x50)(graphics, 1, &drawing); + // SAFETY: as above. + assert_eq!(unsafe { flag.read_volatile() }, 1); + let read = read(out); + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}: the texture as the graphics list filled it"); + } + } + #[test] fn committed_and_placed_resources_map_at_their_gpu_address() { let null = std::ptr::null(); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 7c29f8112d..8d57a2864f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -46,6 +46,11 @@ pub(crate) struct Shadow { /// 64 KiB title page it touches (tracked memory only): writes through /// views of it are marked there ([`Shadow::mark_entry`]). marks: Option, + /// Where it starts in `buffer` (0 but for copies sharing a buffer), and + /// the run of the shared buffer it holds ([`Arena`]), given back when it + /// goes. + base: u64, + slice: Option, } /// Snapshot segments (offset, bytes) and the pieces compared. @@ -86,7 +91,7 @@ fn give_back(v: Vec) { } /// Snapshot memory kept for reuse. -const POOL_BYTES: usize = 2 << 30; +const POOL_BYTES: usize = 512 << 20; // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping // written only on the submitting thread. @@ -138,7 +143,7 @@ impl Shadow { /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { - address - self.start + address - self.start + self.base } /// Where the title memory it copies starts, and its length. @@ -200,7 +205,13 @@ impl Shadow { } fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Arc { - let tracked = crate::watch::track(start as usize, len as usize, true); + Shadow::new_at(buffer, data, gpu, start, len, None) + } + + /// [`Shadow::new`] of a copy in a run of a shared buffer (`data` and + /// `gpu` are the run's). + fn new_at(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64, slice: Option) -> Arc { + let tracked = crate::watch::track_copy(start as usize, len as usize, true); let marks = tracked.as_ref().and_then(|_| marks().take(pages(start, len))); let shadow = Arc::new(Shadow { buffer, @@ -212,6 +223,8 @@ impl Shadow { pending: Mutex::default(), before: Mutex::default(), marks, + base: slice.map_or(0, |s| s.offset), + slice, }); if let Some(base) = marks { self::marks().owners.insert(base, Arc::downgrade(&shadow)); @@ -479,10 +492,25 @@ impl Shadow { written.map_or(0, |_| n) } + /// Whether the title wrote none of the copy's memory since the copy took + /// it (tracked memory only): [`Shadow::update`] would copy nothing. + pub(crate) fn clean(&self) -> bool { + self.tracked.as_ref().is_some_and(crate::watch::Tracked::clean) + } + + /// Its tracker's bit: `crate::watch::clean_bit` of it is + /// [`Shadow::clean`] (none for memory that is not tracked: never clean). + pub(crate) fn dirty_bit(&self) -> Option { + self.tracked.as_ref().and_then(crate::watch::Tracked::bit) + } + /// At submission: copies what changed of `[address, address + len)` /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. pub(crate) fn update(&self, address: usize, len: usize) -> usize { + if self.clean() { + return 0; + } let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { @@ -563,11 +591,29 @@ impl Shadow { if let Some(t) = &self.tracked { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); - let runs = t.take(from, to); + let (runs, unmapped) = t.take_split(from, to); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::WatchUs, started.elapsed().as_micros() as u64); // Cut to the range: next to it shaders may be writing the copy. - let copied: usize = runs.into_iter().map(|(a, b)| self.copy(a, b)).sum(); + let mut copied: usize = runs.into_iter().map(|(a, b)| self.copy(a, b)).sum(); + for (a, b) in unmapped { + // SAFETY: inside the mapping (`take_split` cuts to the buffer). + unsafe { self.data.add(a - self.start as usize).write_bytes(0, b - a) }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, (b - a) as u64); + } + // Parts on memory that is not the runtime's: whole, as below. + for (a, b) in t.untracked(from, to) { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + copied += self.copy(a, b); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::WholeBytes, (b - a) as u64); + add(C::WholeUs, started.elapsed().as_micros() as u64); + } + } #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -602,6 +648,9 @@ impl Shadow { impl Drop for Shadow { fn drop(&mut self) { + if let Some(slice) = self.slice { + arena().give_back(slice); + } if let Some(base) = self.marks { let mut m = marks(); m.owners.remove(&base); @@ -687,13 +736,18 @@ unsafe impl Send for Bitmap {} // SAFETY: as above. unsafe impl Sync for Bitmap {} -fn bitmap() -> Option<&'static Bitmap> { - static BITMAP: std::sync::OnceLock> = std::sync::OnceLock::new(); - BITMAP +/// The bitmap of other shaders, or (`memory`) of shaders that use title +/// memory, whose marks go back only while it is not withheld +/// (`crate::memory::withholding`). +fn bitmap(memory: bool) -> Option<&'static Bitmap> { + static BITMAPS: [std::sync::OnceLock>; 2] = [const { std::sync::OnceLock::new() }; 2]; + BITMAPS[usize::from(memory)] .get_or_init(|| { - let bytes = u64::from(victory_shader::emit::VIEW_WRITE_BITS / 8); + // Written pages, then one read mark per heap index. + let bits = victory_shader::emit::VIEW_READS + victory_shader::emit::HEAP_VIEWS; + let bytes = u64::from(bits / 8); let (buffer, data) = host()?.shared_buffer(bytes)?; - crate::host::name(&buffer, || "views' written pages".into()); + crate::host::name(&buffer, || "views' written pages and read slots".into()); // SAFETY: our mapped buffer of `bytes` bytes. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; // SAFETY: a live buffer. @@ -708,38 +762,136 @@ fn bitmap() -> Option<&'static Bitmap> { } /// The host GPU address of the buffer views' written-pages bitmap, for the -/// root UAV of shaders that mark their writes. -pub(crate) fn view_writes() -> Option { - bitmap().map(|b| b.gpu) +/// root UAV of shaders that mark their writes (`memory`: shaders that use +/// title memory, see [`bitmap`]). +pub(crate) fn view_writes(memory: bool) -> Option { + bitmap(memory).map(|b| b.gpu) +} + +/// Heap slots whose texture views shaders read: the marks seen so far (a +/// slot's stays set in the bitmap until [`forget_read`]), and the slots to +/// clear at the next [`take_reads`]. +static READS: Mutex<(Vec, Vec)> = Mutex::new((Vec::new(), Vec::new())); + +/// After a submission: the heap slots its shaders first read texture views +/// at (`victory_shader::emit`, "Read marks"), each once until +/// [`forget_read`]. Clears the slots forgotten since first. +pub(crate) fn take_reads() -> Vec { + let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize; + let first = (victory_shader::emit::VIEW_READS / 32) as usize; + // Both bitmaps: shaders that use title memory mark their reads in theirs. + let mut maps: Vec<&mut [u32]> = [false, true] + .into_iter() + .filter_map(bitmap) + // SAFETY: the mapped bitmap's read marks; the GPU is done with them + // (one submission runs at a time). + .map(|b| unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }) + .collect(); + if maps.is_empty() { + return Vec::new(); + } + let mut reads = READS.lock().unwrap_or_else(|e| e.into_inner()); + let (seen, forgotten) = &mut *reads; + seen.resize(words, 0); + for slot in forgotten.drain(..) { + let (w, bit) = ((slot / 32) as usize, 1u32 << (slot % 32)); + if w < words { + maps.iter_mut().for_each(|bits| bits[w] &= !bit); + seen[w] &= !bit; + } + } + let mut new = Vec::new(); + for (w, s) in seen.iter_mut().enumerate() { + let mut fresh = maps.iter().fold(0, |x, bits| x | bits[w]) & !*s; + *s |= fresh; + while fresh != 0 { + new.push(w as u32 * 32 + fresh.trailing_zeros()); + fresh &= fresh - 1; + } + } + new +} + +/// The heap slots shaders read texture views at since the last call (both +/// bitmaps), whose marks are cleared: what the title used (eviction stamps, +/// `crate::resource::evict`). Between submissions, after [`take_reads`] +/// has seen every mark: its own record of slots seen keeps a slot read +/// again from being reported as new. +pub(crate) fn reads_since() -> Vec { + let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize; + let first = (victory_shader::emit::VIEW_READS / 32) as usize; + let mut slots = Vec::new(); + for b in [false, true].into_iter().filter_map(bitmap) { + // SAFETY: the mapped bitmap's read marks; no submission runs. + let bits = unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }; + for (w, word) in bits.iter_mut().enumerate() { + let mut x = std::mem::take(word); + while x != 0 { + slots.push(w as u32 * 32 + x.trailing_zeros()); + x &= x - 1; + } + } + } + slots.sort_unstable(); + slots.dedup(); + slots +} + +/// Heap slot `slot` now holds a texture view left null: its next read is +/// marked again. +pub(crate) fn forget_read(slot: u32) { + READS.lock().unwrap_or_else(|e| e.into_inner()).1.push(slot); } /// After a submission: every page its shaders marked as written through /// views goes back ([`Shadow::copy_back_marked`]), but for pages in /// `withheld` (ranges of copies that lists whose writes stay out of title -/// memory declared); the bitmap is cleared. Before the copy-backs of +/// memory declared) and, with `memory_withheld`, pages that shaders using +/// title memory marked; the bitmaps are cleared. Before the copy-backs of /// declared ranges, which disarm the copies. // shortcut: marks do not tell lists apart: a page that a withheld list and // another both wrote through views goes back unless the withheld list // declared it. -pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)]) { - let Some(b) = bitmap() else { - return; - }; +pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)], memory_withheld: bool) { + let (mut marked, mut held) = (Vec::new(), Vec::new()); + for memory in [false, true] { + let Some(b) = bitmap(memory) else { + continue; + }; + let words = (victory_shader::emit::VIEW_WRITE_BITS / 32) as usize; + // SAFETY: the mapped bitmap; the GPU is done with it (one submission + // runs at a time). + let bits = unsafe { std::slice::from_raw_parts_mut(b.data as *mut u32, words) }; + // Marks of offsets past the bitmap land in its last bit, no copy's. + bits[words - 1] = 0; + let used = (marks().end as usize).div_ceil(32).min(words); + for (w, word) in bits[..used].iter_mut().enumerate() { + let mut x = std::mem::take(word); + let into = if memory && memory_withheld { &mut held } else { &mut marked }; + while x != 0 { + into.push((w * 32) as u32 + x.trailing_zeros()); + x &= x - 1; + } + } + } #[cfg(feature = "diagnostics")] let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::MarkedUs); - let words = (victory_shader::emit::VIEW_WRITE_BITS / 32) as usize; - // SAFETY: the mapped bitmap; the GPU is done with it (one submission - // runs at a time). - let bits = unsafe { std::slice::from_raw_parts_mut(b.data as *mut u32, words) }; - // Marks of offsets past the bitmap land in its last bit, no copy's. - bits[words - 1] = 0; - let mut marked = Vec::new(); - let used = (marks().end as usize).div_ceil(32).min(words); - for (w, word) in bits[..used].iter_mut().enumerate() { - let mut x = std::mem::take(word); - while x != 0 { - marked.push((w * 32) as u32 + x.trailing_zeros()); - x &= x - 1; + marked.sort_unstable(); + marked.dedup(); + let page_of = |m: &Marks, n: u32| { + let (&base, copy) = m.owners.range(..=n).next_back()?; + let copy = copy.upgrade()?; + let k = n - base; + (k < pages(copy.start, copy.len)).then(|| { + let page = (((copy.start >> 16) + u64::from(k)) << 16) as usize; + (copy, page) + }) + }; + // Held back: dropped from the copies (`crate::memory::drop_withheld`). + if !held.is_empty() { + let m = marks(); + for (_, page) in held.into_iter().filter_map(|n| page_of(&m, n)) { + crate::memory::drop_withheld(page, PAGE); } } if marked.is_empty() { @@ -747,18 +899,7 @@ pub(crate) fn copy_back_marks(withheld: &[(Arc, usize, usize)]) { } let pages: Vec<(Arc, usize)> = { let m = marks(); - marked - .iter() - .filter_map(|&n| { - let (&base, copy) = m.owners.range(..=n).next_back()?; - let copy = copy.upgrade()?; - let k = n - base; - (k < pages(copy.start, copy.len)).then(|| { - let page = (((copy.start >> 16) + u64::from(k)) << 16) as usize; - (copy, page) - }) - }) - .collect() + marked.iter().filter_map(|&n| page_of(&m, n)).collect() }; for (copy, page) in pages { if withheld @@ -913,7 +1054,7 @@ pub(crate) fn for_view(address: u64, len: u64, element: u64) -> Option<(Arc 0) .count(); + let (chunks, held) = { + let a = arena(); + // SAFETY: live buffers. + let size = |c: &(ID3D12Resource, usize, u64, BTreeMap)| unsafe { c.0.GetDesc() }.Width; + let held: u64 = a.chunks.iter().map(|c| size(c) - c.3.values().sum::()).sum(); + (a.chunks.len(), held) + }; if asks > 0 { tracing::info!( - "buffer views off their copy's elements: {:.0} asked for/frame, {:.0} copies made/frame ({:.1} KB), largest {largest} bytes, {live} live", + "buffer views off their copy's elements: {:.0} asked for/frame, {:.0} copies made/frame ({:.1} KB), largest {largest} bytes, {live} live in {chunks} shared buffers ({:.1} MB held)", asks as f64 / frames, made as f64 / frames, - bytes as f64 / frames / 1e3 + bytes as f64 / frames / 1e3, + held as f64 / 1e6 ); } } @@ -950,12 +1099,12 @@ pub(crate) fn log_views(frames: f64) { /// new copy of the same bytes took the refreshes). With the size the map /// is next pruned of dead entries at. #[allow(clippy::type_complexity)] -static EXACT: Mutex<(usize, BTreeMap<(u64, u64), std::sync::Weak>)> = Mutex::new((0, BTreeMap::new())); +static EXACT: Mutex<(usize, BTreeMap<(u64, u64, u64), std::sync::Weak>)> = Mutex::new((0, BTreeMap::new())); -fn exact(address: u64, len: u64) -> Option> { +fn exact(address: u64, len: u64, element: u64) -> Option> { let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner()); let (prune_at, map) = &mut *guard; - if let Some(shadow) = map.get(&(address, len)).and_then(std::sync::Weak::upgrade) { + if let Some(shadow) = map.get(&(address, len, element)).and_then(std::sync::Weak::upgrade) { return Some(shadow); } // Ring positions change every frame: entries die by the hundred. @@ -963,12 +1112,10 @@ fn exact(address: u64, len: u64) -> Option> { map.retain(|_, w| w.strong_count() > 0); *prune_at = (2 * map.len()).max(1024); } - 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 = Shadow::new(buffer, data, gpu, address, len); - map.insert((address, len), Arc::downgrade(&shadow)); + // A run of a shared buffer, its start a whole number of elements in. + let (buffer, data, gpu, slice) = arena().take(len, element)?; + let shadow = Shadow::new_at(buffer, data, gpu, address, len, Some(slice)); + map.insert((address, len, element), Arc::downgrade(&shadow)); #[cfg(feature = "diagnostics")] { use std::sync::atomic::Ordering::Relaxed; @@ -979,6 +1126,98 @@ fn exact(address: u64, len: u64) -> Option> { Some(shadow) } +/// A run of an [`Arena`] buffer: the buffer, where the run starts, its +/// bytes. +#[derive(Clone, Copy)] +struct Slice { + chunk: usize, + offset: u64, + len: u64, +} + +/// Shared buffers for the copies of single views ([`exact`]): they are +/// small (~2 KB on average) and come and go by the hundred a frame, and a +/// buffer of their own each cost a kernel call to make and one to free on +/// the title's threads and the submitting one (300-820 a frame), and 64 KiB +/// of memory each (~5,000 live). +#[derive(Default)] +struct Arena { + /// Each buffer, its mapping and host address, and its free runs + /// (offset → bytes). + chunks: Vec<(ID3D12Resource, usize, u64, BTreeMap)>, +} + +/// Bytes of each arena buffer (a larger copy gets one of its size). +const CHUNK: u64 = 16 << 20; + +static ARENA: Mutex = Mutex::new(Arena { chunks: Vec::new() }); + +fn arena() -> std::sync::MutexGuard<'static, Arena> { + ARENA.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Arena { + /// A run of `len` bytes starting at a multiple of `element` (and of 256) + /// in a shared buffer: the buffer, the run's mapping and host address. + fn take(&mut self, len: u64, element: u64) -> Option<(ID3D12Resource, *mut u8, u64, Slice)> { + let gcd = |mut a: u64, mut b: u64| { + while b != 0 { + (a, b) = (b, a % b); + } + a + }; + let align = 256 / gcd(256, element.max(1)) * element.max(1); + let len = len.max(1).next_multiple_of(4); + let fits = |free: &BTreeMap| { + free.iter().find_map(|(&at, &n)| { + let start = at.next_multiple_of(align); + (start + len <= at + n).then_some((at, n, start)) + }) + }; + let found = self.chunks.iter().enumerate().find_map(|(c, chunk)| fits(&chunk.3).map(|f| (c, f))); + let (chunk, (at, n, start)) = match found { + Some(found) => found, + None => { + let size = CHUNK.max((len + align).next_multiple_of(1 << 16)); + let (buffer, data) = host()?.shared_buffer(size)?; + crate::host::name(&buffer, || format!("title views {size:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let free = BTreeMap::from([(0, size)]); + self.chunks.push((buffer, data as usize, gpu, free)); + let c = self.chunks.len() - 1; + (c, fits(&self.chunks[c].3)?) + } + }; + let (buffer, data, gpu, free) = &mut self.chunks[chunk]; + free.remove(&at); + if start > at { + free.insert(at, start - at); + } + if at + n > start + len { + free.insert(start + len, at + n - start - len); + } + let slice = Slice { chunk, offset: start, len }; + Some((buffer.clone(), (*data + start as usize) as *mut u8, *gpu + start, slice)) + } + + /// A run goes back, joined to its free neighbours. + fn give_back(&mut self, slice: Slice) { + let Some((_, _, _, free)) = self.chunks.get_mut(slice.chunk) else { return }; + let (mut at, mut n) = (slice.offset, slice.len); + if let Some((&before, &m)) = free.range(..at).next_back() + && before + m == at + { + free.remove(&before); + (at, n) = (before, n + m); + } + if let Some(m) = free.remove(&(at + n)) { + n += m; + } + free.insert(at, n); + } +} + /// Every host copy of title memory made so far (buffers and windows). pub(crate) fn all() -> Vec> { let mut all: Vec> = buffers().values().filter_map(|e| e.shadow.clone()).collect(); @@ -1019,9 +1258,19 @@ pub(crate) fn near(va: u64) -> String { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + /// A shader's read mark of heap slot `slot` in the bitmap of shaders + /// that use title memory (`memory`) or of the others. + pub(crate) fn mark_read(memory: bool, slot: u32) { + let b = bitmap(memory).expect("a host GPU"); + let bit = victory_shader::emit::VIEW_READS + slot; + // SAFETY: a bit of the mapped bitmap; no submission runs (the caller + // holds the submission lock). + unsafe { *(b.data as *mut u32).add((bit / 32) as usize) |= 1 << (bit % 32) }; + } + /// The title writes a constant under a range an earlier list of the /// submission declared as written by shaders: the refresh before the /// submission runs still brings it to the copy, a shader's write still @@ -1057,6 +1306,95 @@ mod tests { unregister(p, p as u64); } + /// A title buffer over a pool and, after it, a plain allocation (memory + /// that is not the runtime's): the pool is tracked and guarded; the + /// plain allocation's bytes are copied at each use and never guarded, + /// so a value the title keeps there reaches the copy, and again after + /// the title changes it. + #[test] + fn bytes_off_the_runtimes_memory_are_copied_at_each_use() { + use crate::watch::tests::{MEM_WRITE_WATCH, free}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, + VirtualAlloc, VirtualFree, VirtualQuery, + }; + // A pool page and a plain one right after it, in two pages found free + // (other tests allocate meanwhile: tried again if taken). + let (pool, plain) = (0..8) + .find_map(|_| { + // SAFETY: a fresh reservation, released at once; then + // allocations where it was, freed below. + unsafe { + let p = VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + VirtualFree(p as *mut _, 0, MEM_RELEASE); + let at = |q: usize, kind: u32| { + VirtualAlloc(q as *const _, PAGE, MEM_RESERVE | MEM_COMMIT | kind, PAGE_READWRITE) as usize + }; + let (pool, plain) = (at(p, MEM_WRITE_WATCH), at(p + PAGE, 0)); + if p != 0 && pool == p && plain == p + PAGE { + return Some((pool, plain)); + } + [pool, plain].into_iter().filter(|&q| q != 0).for_each(free); + None + } + }) + .expect("two free pages"); + let len = 2 * PAGE; + register(pool, pool as u64, len as u64); + let Some(copy) = find(pool as u64, len as u64) else { + unregister(pool, pool as u64); + [pool, plain].into_iter().for_each(free); + return; // no host GPU here + }; + let word = (plain + 64) as *mut u32; + let protection = |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. + unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + info.Protect + }; + // SAFETY: a word of our plain allocation. + unsafe { word.write_volatile(0x1234) }; + copy.update(pool, len); + assert_eq!(copy.read_host(word as u64, 1), [0x1234]); + assert!(!copy.clean(), "never clean: part of it is not tracked"); + // SAFETY: as above. + unsafe { word.write_volatile(0x5678) }; + copy.update(pool, len); + assert_eq!(copy.read_host(word as u64, 1), [0x5678], "the title's change reaches the copy"); + assert_eq!(protection(pool), PAGE_READONLY, "the pool is guarded"); + assert_eq!(protection(plain), PAGE_READWRITE, "the plain allocation is not"); + unregister(pool, pool as u64); + // The pages stay allocated (as the other tests' pools): a copy some + // page table still holds must not name memory reused meanwhile. + } + + /// Runs of the shared buffers start a whole number of elements (and of + /// 256 bytes) in, do not overlap, and join again when given back. + #[test] + fn arena_runs_are_aligned_to_their_elements_and_join_again() { + if host().is_none() { + return; // no host GPU here + } + let mut arena = Arena::default(); + let (_, _, _, a) = arena.take(100, 456).unwrap(); + let (_, _, _, b) = arena.take(5000, 16).unwrap(); + let (_, _, _, c) = arena.take(4, 4).unwrap(); + assert!(a.offset % 456 == 0 && a.offset % 256 == 0 && b.offset % 256 == 0); + let mut runs = [a, b, c].map(|s| (s.offset, s.offset + s.len)); + runs.sort_unstable(); + assert!(runs.windows(2).all(|w| w[0].1 <= w[1].0), "{runs:?}"); + for s in [b, a, c] { + arena.give_back(s); + } + assert_eq!(arena.chunks.len(), 1); + assert_eq!(arena.chunks[0].3.len(), 1, "one free run again"); + // Larger than a buffer: one of its own. + let (_, _, _, d) = arena.take(CHUNK + 1, 4).unwrap(); + assert_eq!((arena.chunks.len(), d.chunk), (2, 1)); + } + /// Ranges shaders write far apart are kept apart (not the copy between /// them); what the GPU wrote goes back once, whichever overlapping /// ranges declared it, and nothing else does. @@ -1104,7 +1442,7 @@ mod tests { let p = crate::watch::tests::pool(3); let len = 3 * PAGE; register(p, p as u64, len as u64); - let (Some(copy), Some(b)) = (find(p as u64, len as u64), bitmap()) else { + let (Some(copy), Some(b)) = (find(p as u64, len as u64), bitmap(false)) else { unregister(p, p as u64); return; // no host GPU here }; @@ -1130,7 +1468,7 @@ mod tests { // SAFETY: a dword of the mapped bitmap. unsafe { *bits.add(n / 32) |= 1 << (n % 32) }; } - copy_back_marks(&[]); + copy_back_marks(&[], false); // SAFETY: bytes of our pool. let read = |at: usize| unsafe { title(at).read_volatile() }; assert_eq!(read(10), 0xaa, "the shader's byte, page 0"); @@ -1143,6 +1481,80 @@ mod tests { unregister(p, p as u64); } + /// Marks of shaders using title memory stay out of title memory while + /// their results are held back, and are cleared; the other shaders' + /// marks of the same submission go back. + #[test] + fn marks_of_shaders_using_title_memory_are_held_back() { + let p = crate::watch::tests::pool(2); + let len = 2 * PAGE; + register(p, p as u64, len as u64); + let (Some(copy), Some(others), Some(memory)) = (find(p as u64, len as u64), bitmap(false), bitmap(true)) else { + unregister(p, p as u64); + return; // no host GPU here + }; + let base = copy.marks.expect("tracked memory gets mark bits") as usize; + copy.update(p, len); + copy.writing(p, len, true); + copy.write_host((p + 10) as u64, &[0xaa]); + copy.write_host((p + PAGE + 10) as u64, &[0xbb]); + // Page 0 marked by another shader, page 1 by one using title memory. + for (b, n) in [(others, base), (memory, base + 1)] { + // SAFETY: a dword of the mapped bitmap. + unsafe { *(b.data as *mut u32).add(n / 32) |= 1 << (n % 32) }; + } + copy_back_marks(&[], true); + // SAFETY: bytes of our pool. + let read = |at: usize| unsafe { ((p + at) as *const u8).read_volatile() }; + assert_eq!((read(10), read(PAGE + 10)), (0xaa, 0), "page 1 held back"); + // SAFETY: a dword of the mapped bitmap. + assert_eq!(unsafe { *(memory.data as *const u32).add((base + 1) / 32) } & 1 << ((base + 1) % 32), 0, "cleared"); + unregister(p, p as u64); + } + + /// What a frame withheld leaves every host copy of its memory at the + /// frame's end (run textures9's shape): in frame N a program using title + /// memory writes a record into the copies and the frame misses, so it + /// stays out of title memory but in the copies for the GPU; in frame + /// N+1, which misses nothing, a program reading the record must see + /// title memory's bytes, not frame N's, in a title buffer's copy and in + /// an inner buffer's copy of the same pages alike. + #[test] + fn what_a_frame_withholds_leaves_the_copies_at_its_end() { + let p = crate::watch::tests::pool(2); + let len = 2 * PAGE; + // SAFETY: a byte of our pool. + unsafe { ((p + 16) as *mut u8).write_volatile(0x11) }; + register(p, p as u64, len as u64); + register(p + 1, p as u64, PAGE as u64); + let (Some(outer), Some(inner)) = (find(p as u64, len as u64), find(p as u64 + 16, 16)) else { + unregister(p + 1, p as u64); + unregister(p, p as u64); + return; // no host GPU here + }; + assert!(!Arc::ptr_eq(&outer, &inner)); + let byte = |c: &Shadow| c.read_host(p as u64 + 16, 1)[0] & 0xff; + for c in [&outer, &inner] { + let (start, n) = c.range(); + c.update(start as usize, n as usize); + c.writing(start as usize, n as usize, false); + c.write_host(p as u64 + 16, &[0x22]); + c.keep_writes(start as usize, n as usize); + } + crate::memory::drop_withheld(p + 16, 4); + assert_eq!((byte(&outer), byte(&inner)), (0x22, 0x22), "frame N: the GPU's copies keep it"); + crate::memory::log_frame(); + for c in [&outer, &inner] { + let (start, n) = c.range(); + c.update(start as usize, n as usize); + } + assert_eq!((byte(&outer), byte(&inner)), (0x11, 0x11), "frame N+1: title memory's bytes"); + // SAFETY: as above. + assert_eq!(unsafe { ((p + 16) as *const u8).read_volatile() }, 0x11, "title memory untouched"); + unregister(p + 1, p as u64); + unregister(p, p as u64); + } + /// Mark bits are handed out in runs and come back joined. #[test] fn mark_runs_are_reused_and_joined() { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 9670f394d0..4a502c1abd 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -33,13 +33,15 @@ macro_rules! once { }}; } -/// A texture's upload state: the staging buffer laid out as the host -/// texture's subresources, and what was last detiled. +/// A texture's upload state: how a staging buffer lays out the host +/// texture's subresources, and what was last detiled. The buffer itself is +/// taken for each upload from a small pool shared by all textures +/// ([`staging_buffer`]; kept for each texture's life, the buffers took its +/// size again in system memory: 2.6-2.8 GB with placed textures made on +/// read, run integ2). pub(crate) struct Staging { - buffer: ID3D12Resource, - /// Its bytes. + /// A staging buffer's bytes. size: u64, - data: *mut u8, footprints: Vec, rows: Vec, layout: victory_formats::texture::Layout, @@ -49,60 +51,178 @@ pub(crate) struct Staging { /// The memory's pages changed since detiled (none: not the runtime's /// memory, hashed instead). tracked: Option, + /// Per subresource, the bytes of the texture's memory it lies in (from + /// its start, whole layout blocks); empty where the layout gives none. + spans: Vec<(usize, usize)>, last: Mutex, + /// Uploads [`record_upload`] recorded, and the subresources they + /// copied. + uploads: std::sync::atomic::AtomicU64, + copied: std::sync::atomic::AtomicU64, } -/// What a texture's staging buffer holds: the digest of the memory detiled -/// (memory not tracked), with room to read tracked memory into. +/// What was last detiled: the hash of the memory (not tracked), or of each +/// subresource's bytes (tracked). #[derive(Default)] struct Last { - hash: Option, - read: Vec, + hash: Option, + hashes: Vec>, } -/// The digest `refresh_now` change-checks the texture's memory with, once -/// per submission when no write-watch covers it. It is not a hash anyone -/// stores or names: the only question it answers is "did these bytes -/// change", so it trades BLAKE3's exactness for memory speed. BLAKE3's -/// compute is several times the cost of the read it guards; this runs at -/// the speed of the read. A change that leaves the same digest happens -/// about one submission in 2^64 per texture, which no one will meet; a -/// stale texture would show as never-updated art, so anything cheaper -/// than a real comparison is the wrong trade. -fn digest(tiled: &[u8]) -> u64 { - // splitmix64 finalizers over 32-byte blocks with two independent - // lanes; the block length folds in so trails of zeros differ. - const P: u64 = 0x9E37_79B9_7F4A_7C15; - let mix = |x: u64| -> u64 { - let z = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB) ^ (z >> 31) +/// Per subresource of `layout` (`mips` per array slice; a 3D texture's +/// are its mips), the bytes of the texture's memory it lies in, rounded out +/// to the layout's blocks; empty if the layout cannot say. +fn spans(layout: &victory_formats::texture::Layout, count: u32, mips: u32) -> Vec<(usize, usize)> { + use victory_formats::texture::Dimension; + let d = &layout.desc; + let block = layout.alignment.max(256); + (0..count) + .map(|i| { + let (mip, slice) = (i % mips, i / mips); + let m = layout.mips.get(mip as usize)?; + let (z0, z1) = if d.dimension == Dimension::Tex3d { (0, m.depth.max(1) - 1) } else { (slice, slice) }; + let first = layout.offset(mip, 0, 0, z0).ok()?; + let last = layout.offset(mip, m.width.max(1) - 1, m.height.max(1) - 1, z1).ok()? + u64::from(d.element_bytes); + let (from, to) = (first / block * block, last.div_ceil(block) * block); + Some((from as usize, (to.min(layout.size)) as usize)) + }) + .collect::>>() + .unwrap_or_default() +} + +/// Staging buffers for detiles to reuse, by size: the menu movie rewrites +/// the same textures every frame, and a fresh 12.7 MB of upload buffers a +/// frame cost ~5 ms (run textures8). Uploads run only inside +/// `Host::execute`, which waits for each submission, so the buffers of one +/// submission are free from the next on. +struct Buffers { + /// (bytes, buffer, mapping), oldest first. + free: std::collections::VecDeque<(u64, ID3D12Resource, usize)>, + free_bytes: u64, + /// Taken by the submission being prepared. + used: Vec<(u64, ID3D12Resource, usize)>, +} + +// SAFETY: the mappings are persistent mappings of the upload buffers. +unsafe impl Send for Buffers {} + +static BUFFERS: Mutex = Mutex::new(Buffers { + free: std::collections::VecDeque::new(), + free_bytes: 0, + used: Vec::new(), +}); + +/// Free staging buffers kept at most. +const KEPT_BYTES: u64 = 64 << 20; + +/// Called before a submission's uploads: the buffers of the last one are +/// free again (the oldest dropped past `KEPT_BYTES`). +pub(crate) fn recycle() { + { + let mut c = CHUNKS.lock().unwrap_or_else(|e| e.into_inner()); + (c.current, c.used) = (0, 0); + c.all.truncate(CHUNKS_KEPT); + } + let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); + let b = &mut *b; + for e in b.used.drain(..) { + b.free_bytes += e.0; + b.free.push_back(e); + } + while b.free_bytes > KEPT_BYTES + && let Some((n, ..)) = b.free.pop_front() + { + b.free_bytes -= n; + } +} + +/// A free staging buffer of `size` bytes, or a new one. +/// Sizes are taken in powers of two (at least 64 KiB), so a buffer serves +/// textures of other sizes too: a new shot's textures came in new sizes and +/// made buffers 10 % of the submitting thread (run evict5). +fn staging_buffer(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let class = size.max(1 << 16).next_power_of_two(); + let taken = { + let mut b = BUFFERS.lock().unwrap_or_else(|e| e.into_inner()); + let i = b.free.iter().position(|e| e.0 == class); + i.and_then(|i| b.free.remove(i)).inspect(|_| b.free_bytes -= class) }; - let (mut a, mut b) = (0x243F_6A88_85A3_08D3, 0x1319_8A2E_0370_7344 ^ P); - let (blocks, tail) = tiled.as_chunks::<32>(); - for block in blocks { - let w = |i: usize| u64::from_le_bytes(block[8 * i..8 * i + 8].try_into().unwrap()); - a = mix(a ^ w(0)).rotate_left(31) ^ w(1); - b = mix(b ^ w(2)).rotate_left(27) ^ w(3); + // Made without the pool's lock (refreshes run on several threads). + let e = match taken { + Some(e) => e, + None => { + let (buffer, data) = host()?.upload_buffer(class)?; + crate::host::name(&buffer, || "texture staging".into()); + (class, buffer, data as usize) + } + }; + let made = (e.1.clone(), e.2 as *mut u8); + BUFFERS.lock().unwrap_or_else(|e| e.into_inner()).used.push(e); + Some(made) +} + +/// Staging space carved from large upload buffers, front to back: most +/// textures take a part of one instead of a buffer of their own (making +/// upload buffers was 10 % of the submitting thread in a new shot, run +/// evict5). Rewound at each submission ([`recycle`]): the last one has run. +struct Chunks { + /// (buffer, mapping), [`CHUNK`] bytes each. + all: Vec<(ID3D12Resource, usize)>, + /// The chunk being carved and the bytes taken from it. + current: usize, + used: u64, +} + +// SAFETY: the mappings are persistent mappings of the upload buffers. +unsafe impl Send for Chunks {} + +static CHUNKS: Mutex = Mutex::new(Chunks { all: Vec::new(), current: 0, used: 0 }); + +const CHUNK: u64 = 32 << 20; +/// Chunks kept between submissions (more are made while one needs them). +const CHUNKS_KEPT: usize = 16; + +/// `size` bytes of staging space: a buffer, the offset of the space in it +/// (a multiple of 512, as texture copies need) and its mapping there. +/// Space larger than a chunk is a buffer of its own ([`staging_buffer`]). +fn staging_space(size: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { + if size > CHUNK { + return staging_buffer(size).map(|(b, data)| (b, 0, data)); } - for (i, &byte) in tail.iter().enumerate() { - let lane = if i < 8 { &mut a } else { &mut b }; - let shift = 8 * ((i % 8) as u32); - *lane = mix(*lane ^ (u64::from(byte) << shift)); + let mut c = CHUNKS.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some((buffer, data)) = c.all.get(c.current) { + let at = c.used.next_multiple_of(512); + if at + size <= CHUNK { + let made = (buffer.clone(), at, (*data + at as usize) as *mut u8); + c.used = at + size; + return Some(made); + } + (c.current, c.used) = (c.current + 1, 0); + continue; + } + let (buffer, data) = host()?.upload_buffer(CHUNK)?; + crate::host::name(&buffer, || "texture staging chunk".into()); + c.all.push((buffer, data as usize)); } - mix(mix(a ^ b.rotate_left(32)) ^ tiled.len() as u64) } -// SAFETY: the staging mapping is written only at submission, under -// `last`'s lock; the title memory is only read. +// SAFETY: the title memory is only read, under `last`'s lock. unsafe impl Send for Staging {} // SAFETY: as above. unsafe impl Sync for Staging {} -/// A host copy or resolve writes `resource`: its host texture's contents -/// are the host's, not title memory's, which stays as it was. -pub(crate) fn host_written(resource: This) { +/// A host copy or resolve that `list` records writes `resource`: from the +/// submission that runs `list` on, its host texture's contents are the +/// host's, not title memory's, which stays as it was. Marked when that +/// submission is made, not when `list` is recorded: a list recorded before +/// it but run after it must not upload title memory over the host's texels +/// (submissions run in the order they are made, which need not be the +/// order their lists were recorded in), and one run before it must still +/// get its upload. +pub(crate) fn host_writes(list: &HostList, resource: This) { if let Some(copy) = crate::resource::host_copy(resource) { - copy.host_written.store(true, std::sync::atomic::Ordering::Relaxed); + list.defer_host(move || copy.host_written.store(true, std::sync::atomic::Ordering::Relaxed)); } } @@ -180,7 +300,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { } let Some(buffer) = host.default_buffer(total) else { return }; list.keep(&buffer); - crate::texture::host_written(to); + crate::texture::host_writes(list, to); crate::list::ensure_state(list, from, COPY_SOURCE); crate::list::ensure_state(list, to, COPY_DEST); let place = |r: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { @@ -199,7 +319,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { // SAFETY: an open list; live resources in the states named. unsafe { for i in 0..n { - l.CopyTextureRegion(&place(&buffer, fa[i as usize]), 0, 0, 0, &sub(a, i), None); + l.CopyTextureRegion(&place(&buffer, fa[i as usize]), 0, 0, 0, &sub(&a, i), None); } l.ResourceBarrier(&[crate::host::transition( &buffer, @@ -207,7 +327,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { D3D12_RESOURCE_STATE_COPY_SOURCE, )]); for i in 0..n { - l.CopyTextureRegion(&sub(b, i), 0, 0, 0, &place(&buffer, fb[i as usize]), None); + l.CopyTextureRegion(&sub(&b, i), 0, 0, 0, &place(&buffer, fb[i as usize]), None); } } ALIAS_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -219,64 +339,112 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { } } -/// Records, once per list, the copy of `resource`'s staging buffer into -/// its host copy, and the detiling that refreshes the staging buffer at -/// submission if the memory changed. Leaves the texture in the copy -/// destination state. +/// Has `resource`'s host copy brought up to date at the submission that +/// runs `list`: its staging buffer detiled again if the memory changed, and +/// then copied into the host texture by the submission's own upload list, +/// once for all its lists (`crate::bindless::uploads`). +/// +/// shortcut: a title copy into texture memory recorded in the same +/// submission shows from the next one on. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { // shortcut: a texture the host copied into keeps the host's contents // even if the title later writes its memory too. // Once per list for each host texture, however many title textures of // its memory the list samples. - if is_host_written(resource) || !list.first_use(texture.as_raw() as usize) { + if is_host_written(resource) { + #[cfg(feature = "diagnostics")] + { + static SEEN: Mutex>> = Mutex::new(None); + if SEEN.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default().insert(resource as usize) { + let memory = crate::resource::texture_memory(resource).map(|(m, _)| m); + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + tracing::debug!(?resource, ?memory, ?desc, "a sampled texture keeps what the host copied into it: not uploaded from title memory"); + } + } + return; + } + if !list.first_use(texture.as_raw() as usize) { return; } - let Some(staging) = staging(resource, texture) else { + let (Some(staging), Some(copy)) = (staging(resource, texture), crate::resource::host_copy(resource)) else { return; }; - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - record(list, resource, texture, &staging); - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); + // Each list recorded the copy before (run perf7: 149 textures uploaded + // 3,195 times in a frame, 17 ms of GPU time), changed or not. + list.defer_texture(staging, copy); } -/// For textures shaders reach through the heap itself, at submission -/// (`crate::bindless::uploads`): brings the staging buffer up to date and -/// records its copy into `list` only if the memory changed since (or was -/// never uploaded). True if it recorded; the texture is then in the copy -/// destination state. -pub(crate) fn upload_changed(list: &HostList, resource: This, texture: &ID3D12Resource) -> bool { - if is_host_written(resource) { - return false; - } - let Some(staging) = staging(resource, texture) else { - return false; - }; - if !staging.refresh() { - return false; +/// Records into `list` the copy of `buffer` (laid out as `staging` says) +/// into host texture `copy`. Returns the barrier that leaves it readable by +/// shaders, for the caller to record with the others after every copy: one +/// barrier per texture between the copies kept the GPU from overlapping +/// them (new shots copy hundreds of textures, run evict6). +#[must_use] +pub(crate) fn record_upload( + list: &HostList, + copy: &Arc, + staging: &Staging, + (buffer, at, subresources): &Upload, +) -> Option { + const COPY_DEST: u32 = 0x400; + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + if let Some(b) = list.move_texture(copy, COPY_DEST) { + // SAFETY: an open list; the barrier names a live texture. + unsafe { list.list.ResourceBarrier(&[b]) }; } - record(list, resource, texture, &staging); - list.keep(&staging.buffer); - true + copies(list, ©.texture, staging, (buffer, *at), subresources, String::new); + list.keep(buffer); + staging.uploads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + staging.copied.fetch_add(subresources.len() as u64, std::sync::atomic::Ordering::Relaxed); + list.move_texture(copy, SHADER_RESOURCE) } -/// Records the copy of every subresource of `staging` into `texture`, -/// moving it to the copy destination state first. -fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &Staging) { - const COPY_DEST: u32 = 0x400; - crate::list::ensure_state(list, resource, COPY_DEST); - for (i, footprint) in staging.footprints.iter().enumerate() { +/// The uploads [`record_upload`] recorded into `resource`'s host texture +/// (tests: counts of their own texture, whatever other tests upload +/// meanwhile). +#[cfg(test)] +pub(crate) fn uploads(resource: This) -> u64 { + let staging = crate::resource::host_copy(resource).and_then(|c| c.staging.lock().unwrap_or_else(|e| e.into_inner()).clone()); + staging.map_or(0, |s| s.uploads.load(std::sync::atomic::Ordering::Relaxed)) +} + +/// The subresources those uploads copied (tests, as [`uploads`]). +#[cfg(test)] +pub(crate) fn copied(resource: This) -> u64 { + let staging = crate::resource::host_copy(resource).and_then(|c| c.staging.lock().unwrap_or_else(|e| e.into_inner()).clone()); + staging.map_or(0, |s| s.copied.load(std::sync::atomic::Ordering::Relaxed)) +} + + +/// Records the copy of `subresources` of `buffer` (laid out as `staging` +/// says) into `texture` (in the copy destination state); `name` names it +/// in diagnostics notes. +#[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] +fn copies( + list: &HostList, + texture: &ID3D12Resource, + staging: &Staging, + (buffer, at): (&ID3D12Resource, u64), + subresources: &[u32], + name: impl Fn() -> String, +) { + for &i in subresources { + let i = i as usize; + let mut footprint = staging.footprints[i]; + footprint.Offset += at; + let footprint = &footprint; #[cfg(feature = "diagnostics")] { let f = footprint.Footprint; // SAFETY: live resources. - let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; + let (gpu, d) = unsafe { (buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); list.note_read( || { format!( - "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + "texture upload {} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + name(), d.Width, d.Height, d.DepthOrArraySize, @@ -304,7 +472,7 @@ fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &S }; let from = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, + pResource: unsafe { std::mem::transmute_copy(buffer) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint, @@ -315,37 +483,151 @@ fn record(list: &HostList, resource: This, texture: &ID3D12Resource, staging: &S } } +/// What a refresh gives: a staging buffer, where its space starts in it, +/// and the subresources detiled into it. +pub(crate) type Upload = (ID3D12Resource, u64, Vec); + +/// Runs `f(i)` for each `i` below `n` on up to a quarter of the CPUs (four +/// at most: the title's own threads need the rest), here when that is +/// fewer than two. +pub(crate) fn in_parallel(n: usize, f: impl Fn(usize) + Sync) { + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(1, 4).min(n); + if threads < 2 { + (0..n).for_each(f); + return; + } + let next = AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + loop { + let i = next.fetch_add(1, Relaxed); + if i >= n { + break; + } + f(i); + } + }); + } + }); +} + +/// [`Staging::refresh`] of each of `work`, those whose memory may have +/// changed on several threads at once (reading title memory and detiling +/// cost ~6 ms of frame a MB on one thread in a new shot, run evict5). +pub(crate) fn refresh_all(work: &[(Arc, Arc)]) -> Vec> { + // Most find nothing changed (their trackers' clean bits say so): those + // are not handed to threads. + let changed: Vec = (0..work.len()).filter(|&i| work[i].0.maybe_changed()).collect(); + let results: Vec>> = changed.iter().map(|_| Mutex::new(None)).collect(); + in_parallel(changed.len(), |k| { + *results[k].lock().unwrap_or_else(|e| e.into_inner()) = work[changed[k]].0.refresh(); + }); + let mut out: Vec> = vec![None; work.len()]; + for (k, r) in results.into_iter().enumerate() { + out[changed[k]] = r.into_inner().unwrap_or_else(|e| e.into_inner()); + } + out +} + impl Staging { - /// Detiles the texture memory into the staging buffer if it changed - /// since the last time (and is mapped at all): whether it did. - pub(crate) fn refresh(&self) -> bool { + /// Whether its memory may have changed since it was last detiled (an + /// untracked texture always may). + pub(crate) fn maybe_changed(&self) -> bool { + self.tracked.as_ref().is_none_or(|t| !t.clean()) + } + + /// A staging buffer with the texture memory detiled into it if it + /// changed since the last time (and is mapped at all), and the + /// subresources that changed (only those are detiled and to be copied). + pub(crate) fn refresh(&self) -> Option { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); - let (read, changed) = self.refresh_now(); + let (read, buffer) = self.refresh_now(); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); preparing[3].fetch_add(read as u64, Relaxed); - changed + buffer } - /// Returns the bytes of title memory read, and whether it detiled. - fn refresh_now(&self) -> (usize, bool) { + /// Returns the bytes of title memory read, and the buffer it detiled + /// into with the subresources detiled. + fn refresh_now(&self) -> (usize, Option) { + let all = || (0..self.footprints.len() as u32).collect::>(); let size = self.layout.size as usize; let start = self.memory as usize; let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); let last = &mut *last; if let Some(t) = &self.tracked { - if t.take(start, start + size).is_empty() { - return (0, false); + // Most refreshes find nothing: the tracker's dense bit says so + // without its lock (123,000 refreshes a frame, run evict3). + if t.clean() { + return (0, None); + } + let ranges = t.take(start, start + size); + if ranges.is_empty() { + return (0, None); } + // Only the subresources in the pages that changed (streamed + // textures change page by page; a whole re-read and detile of + // each cost up to 430 MB a frame, run integ2). + let n = self.footprints.len(); + let span = |i: usize| self.spans.get(i).copied().unwrap_or((0, size)); + let touched: Vec = (0..n) + .filter(|&i| { + let (a, b) = span(i); + ranges.iter().any(|&(f, e)| f - start < b && a < e - start) + }) + .collect(); // Read through the copy, which stands unmapped pages: memory of - // big pools is too slow to ask page by page. - last.read.resize(size, 0); - crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); - self.detile(&last.read); + // big pools is too slow to ask page by page. Not kept: it would + // double each texture's system memory. Only the touched spans + // are written, and only they are hashed and detiled. + let mut scratch = Scratch::take(size); + let read = &mut scratch.0[..size]; + let mut bytes = 0; + let mut done: Vec<(usize, usize)> = Vec::new(); + for &i in &touched { + let (a, b) = span(i); + if !done.contains(&(a, b)) { + // SAFETY: inside the buffer of the texture's size. + crate::host::copy_mapped(unsafe { read.as_mut_ptr().add(a) }, self.memory.wrapping_add(a), b - a, false); + (bytes, _) = (bytes + b - a, done.push((a, b))); + } + } + // A changed page that holds only the subresource's bytes says it + // changed. Pages it shares with other data the title writes + // (small textures): its own bytes decide. (Hashing a movie frame + // cost 8 ms a frame.) + let page = crate::watch::PAGE; + last.hashes.resize(n, None); + let fresh: Vec = touched + .into_iter() + .filter(|&i| { + let (a, b) = span(i); + let (a0, b0) = (start + a, start + b); + if ranges.iter().any(|&(f, e)| f.max(a0).next_multiple_of(page) + page <= e.min(b0)) { + last.hashes[i] = None; + return true; + } + let hash = blake3::hash(&read[a..b]); + last.hashes[i].replace(hash) != Some(hash) + }) + .map(|i| i as u32) + .collect(); + if fresh.is_empty() { + return (bytes, None); + } + let buffer = self.detile(read, &fresh); + if buffer.is_none() { + for &i in &fresh { + last.hashes[i as usize] = None; + } + } #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return (size, true); + crate::copystat::add(crate::copystat::C::TexWatched, bytes as u64); + return (bytes, buffer.map(|(b, at)| (b, at, fresh))); } if !committed(self.memory, size) { #[cfg(feature = "diagnostics")] @@ -355,52 +637,101 @@ impl Staging { desc = ?self.layout.desc, "a sampled texture's memory is not committed" ); - return (0, false); + // Never uploaded: zeros, as a committed texture starts (one in + // a heap of textures starts with whatever the range held). + if last.hash.is_some() { + return (0, None); + } + let zeros = vec![0u8; size]; + let every = all(); + let buffer = self.detile(&zeros, &every); + last.hash = buffer.is_some().then(|| blake3::hash(&zeros)); + return (0, buffer.map(|(b, at)| (b, at, every))); } // SAFETY: committed memory of the texture's layout size. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; - let hash = digest(tiled); + let hash = blake3::hash(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); if last.hash == Some(hash) { - return (size, false); + return (size, None); } - last.hash = Some(hash); - self.detile(tiled); + let every = all(); + let buffer = self.detile(tiled, &every); + last.hash = buffer.is_some().then_some(hash); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); - (size, true) + (size, buffer.map(|(b, at)| (b, at, every))) } - /// Detiles `tiled` (the texture's memory) into the staging buffer. - fn detile(&self, tiled: &[u8]) { + /// Detiles `subresources` of `tiled` (the texture's memory) into a + /// staging buffer (`None` if none could be had or a subresource could + /// not be read). + fn detile(&self, tiled: &[u8], subresources: &[u32]) -> Option<(ID3D12Resource, u64)> { + let (buffer, at, data) = staging_space(self.size)?; #[cfg(feature = "diagnostics")] - if tiled.iter().all(|&b| b == 0) { - tracing::debug!( - memory = ?self.memory, - desc = ?self.layout.desc, - "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" - ); + // Scanned only when its message is wanted: a pass over every + // texture read, in timing runs too. + if tracing::enabled!(tracing::Level::DEBUG) { + if tiled.iter().all(|&b| b == 0) { + tracing::debug!( + memory = ?self.memory, + desc = ?self.layout.desc, + "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" + ); + } else { + tracing::debug!(memory = ?self.memory, desc = ?self.layout.desc, "a sampled texture detiled"); + } } - for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { - let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + for &i in subresources { + let (footprint, rows) = (&self.footprints[i as usize], self.rows[i as usize]); + let (mip, slice) = (i % self.mips, i / self.mips); let f = footprint.Footprint; let pitch = f.RowPitch as usize; let len = subresource_len(footprint.Offset, pitch, rows, f.Depth, self.size); // SAFETY: `subresource_len` clamps `len` to `self.size - footprint.Offset`, // keeping the slice strictly inside the mapped staging buffer even when // GetCopyableFootprints does not pad the final row of the last subresource. - let linear = unsafe { - std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) - }; + let linear = unsafe { std::slice::from_raw_parts_mut(data.add(footprint.Offset as usize), len) }; if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) { tracing::warn!(?e, mip, slice, "texture not detiled"); - return; + return None; } } + Some((buffer, at)) + } +} + +/// A buffer for the title memory a refresh reads, kept by the thread for +/// its next refresh: a fresh one for each texture cost a zero-fill and a +/// page fault per 4 KiB (129,000 faults in a frame, run placed1). +struct Scratch(Vec); + +thread_local! { + static SCRATCH: std::cell::Cell> = const { std::cell::Cell::new(Vec::new()) }; +} + +impl Scratch { + /// The thread's buffer, at least `size` bytes. + fn take(size: usize) -> Self { + let mut v = SCRATCH.take(); + if v.len() < size { + v.resize(size, 0); + } + Scratch(v) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + // The largest textures' buffers are not kept. + const KEEP: usize = 32 << 20; + if self.0.len() <= KEEP { + SCRATCH.set(std::mem::take(&mut self.0)); + } } } @@ -447,7 +778,7 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool { /// The staging state of a title texture's host texture, made on first use /// (one for all title textures of its memory). -fn staging(resource: This, texture: &ID3D12Resource) -> Option> { +pub(crate) fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let copy = crate::resource::host_copy(resource)?; let mut held = copy.staging.lock().unwrap_or_else(|e| e.into_inner()); if let Some(s) = held.as_ref() { @@ -490,26 +821,21 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { Some(&mut total), ); } - let (buffer, data) = host.upload_buffer(total)?; - crate::host::name(&buffer, || { - format!( - "staging of {resource:?} {}x{}x{} f{}", - d.Width, d.Height, d.DepthOrArraySize, d.Format.0 - ) - }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); let layout_size = layout.size as usize; + let spans = spans(&layout, count, u32::from(d.MipLevels)); let s = Arc::new(Staging { - buffer, size: total, - data, footprints, rows, layout, mips: u32::from(d.MipLevels), memory, tracked: crate::watch::track(memory as usize, layout_size, true), + spans, last: Mutex::default(), + uploads: Default::default(), + copied: Default::default(), }); *held = Some(s.clone()); Some(s) @@ -519,77 +845,6 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { mod tests { use super::*; - fn fill(seed: u64, buf: &mut [u8]) { - let mut s = seed; - for b in buf.iter_mut() { - s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - *b = (s >> 33) as u8; - } - } - - #[test] - fn is_deterministic_and_changes_with_any_byte() { - let mut a = vec![0_u8; 4096]; - fill(1, &mut a); - assert_eq!(digest(&a), digest(&a)); - let base = digest(&a); - for pos in 0..a.len() { - let old = a[pos]; - a[pos] ^= 0xff; - assert_ne!(digest(&a), base, "a flip of byte {pos} was missed"); - a[pos] = old; - } - } - - #[test] - fn changes_with_any_sampled_bit_of_a_large_texture() { - let mut big = vec![0_u8; 1 << 20]; - fill(2, &mut big); - let base = digest(&big); - for &pos in &[0, 1, 7, 8, 31, 4095, 1 << 19, (1 << 20) - 1] { - for bit in 0..8 { - big[pos] ^= 1 << bit; - assert_ne!(digest(&big), base, "a flip of bit {pos}:{bit} was missed"); - big[pos] ^= 1 << bit; - } - } - } - - #[test] - fn folds_in_length_and_trailing_zeros() { - assert_ne!(digest(&[0; 63]), digest(&[0; 64])); - assert_ne!(digest(&[0; 65]), digest(&[0; 64])); - let zeros = [0_u8; 1 << 20]; - assert_ne!(digest(&zeros[..1 << 19]), digest(&zeros)); - } - - #[test] - fn is_independent_of_capacity() { - let mut a = vec![0_u8; 4096]; - fill(1, &mut a); - let mut odd = a.clone(); - odd.push(0x5a); - assert_eq!(digest(&odd[..4096]), digest(&a)); - } - - #[test] - fn every_rewrite_of_a_frame_registers() { - // A 64 KiB frame, rewritten one byte at a time 100,000 times: the - // change-check the digest serves must catch each one. - let mut frame = vec![0_u8; 65536]; - fill(3, &mut frame); - let mut h = digest(&frame); - let mut s = 7_u64; - for _ in 0..100_000 { - let i = s % 65280; - s = s.wrapping_mul(6364136223846793005).wrapping_add(1); - frame[i as usize] ^= 0x01; - let n = digest(&frame); - assert_ne!(n, h, "a rewrite of byte {i} was missed"); - h = n; - } - } - #[test] fn subresource_len_stays_inside_staging_total() { // A 4x4 RGBA8 texture has RowPitch=256, rows=4, last_row=16 -> total=784. diff --git a/crates/victory-gpu/src/twin.rs b/crates/victory-gpu/src/twin.rs index e54f19cec6..6013b4fa00 100644 --- a/crates/victory-gpu/src/twin.rs +++ b/crates/victory-gpu/src/twin.rs @@ -8,7 +8,7 @@ //! contents move between the two by copies where the use changes: within //! a list where it records the change (`HostList::transition`), and at //! submission for each list's first use, from the side the lists before it -//! left newer. A 16-bit depth plane in the host's 24-bit one (the +//! left newer. A 16-bit depth plane in the host's 32-bit float one (the //! console's 16-bit depth with stencil) is converted on the way, so a //! value written as 16-bit depth compares equal to the same depth //! rasterised. @@ -86,7 +86,7 @@ struct Route { /// Its place in the scratch buffer as the twin's texture has it. twin: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, /// As the depth texture has it, where that differs: a 16-bit depth - /// plane the host keeps in 24 bits (32 per texel), converted. + /// plane the host keeps as 32-bit floats, converted. depth: Option, } @@ -563,27 +563,20 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } } -/// 16-bit depth (unorm, two per dword) to the host's 24-bit depth plane (in -/// the low 24 bits of 32) and back, in the scratch buffer: `u * (2^24 - 1) -/// / 65535` rounded, exactly, and back to the 16-bit value whose 24-bit one -/// is nearest. Modes 1 to 3 convert a packed 16-bit colour (`B5G6R5`, -/// `B5G5R5A1`, `B4G4R4A4`: blue, green, red, then alpha from the low bits) -/// to the 8-bit channels of its twin's `R8G8B8A8` (red in the low byte) and +/// 16-bit depth (unorm, two per dword) to the host's 32-bit float depth +/// plane and back, in the scratch buffer: `u` becomes `u` times +/// `0x37800080` (the title's 1/65535; its tiled-lighting draws rasterise +/// that very float and test it EQUAL), and a float back the nearest `u`. +/// Modes 1 to 3 convert a packed 16-bit colour (`B5G6R5`, `B5G5R5A1`, +/// `B4G4R4A4`: blue, green, red, then alpha from the low bits) to the +/// 8-bit channels of its twin's `R8G8B8A8` (red in the low byte) and /// back, each side rounded the way its hardware would. const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=8, b0), UAV(u0)" cbuffer C : register(b0) { uint width; uint height; uint pitch16; uint at16; uint pitch32; uint at32; uint toDepth; uint mode; }; RWByteAddressBuffer buf : register(u0); -uint d24(uint u) { return u * 256 + (u * 255 + 32767) / 65535; } -uint u16(uint d) { - d &= 0xffffff; - uint u = min(d >> 8, 65535); - uint best = u; - int err = abs((int)d24(u) - (int)d); - if (u > 0 && abs((int)d24(u - 1) - (int)d) < err) { best = u - 1; err = abs((int)d24(u - 1) - (int)d); } - if (u < 65535 && abs((int)d24(u + 1) - (int)d) < err) { best = u + 1; } - return best; -} +uint depth(uint u) { return asuint((float)u * asfloat(0x37800080)); } +uint u16(uint d) { return (uint)(saturate(asfloat(d)) * 65535.0 + 0.5); } uint up(uint v, uint m) { return (v * 255 + m / 2) / m; } uint down(uint v, uint m) { return (v * m + 127) / 255; } [RootSignature(RS)] @@ -599,8 +592,8 @@ void main(uint3 id : SV_DispatchThreadID) { bool two = x + 1 < width; if (toDepth != 0) { uint pair = buf.Load(a); - buf.Store(b, d24(pair & 0xffff)); - if (two) buf.Store(b + 4, d24(pair >> 16)); + buf.Store(b, depth(pair & 0xffff)); + if (two) buf.Store(b + 4, depth(pair >> 16)); } else { uint lo = u16(buf.Load(b)); uint hi = two ? u16(buf.Load(b + 4)) : 0; @@ -714,4 +707,56 @@ mod tests { assert_eq!(again(DEPTH, &mut last, TWIN, true), Some(false)); assert_eq!(last, Some(TWIN)); } + + /// A list that writes a depth texture through its twin and then reads + /// its depth side: its prelude owes a copy into the twin first. Every + /// barrier the prelude and the list issue starts from the state the + /// texture is in, as the debug layer checks (run light21: the prelude's + /// copy started from the states the list leaves). + #[test] + fn prelude_copies_start_from_the_real_states() { + use crate::host::tests::{issued, replay}; + use windows::core::Interface; + let Some(host) = host() else { + return; // no host GPU here + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut texture: Option = None; + // SAFETY: plain creation; our out pointer. + unsafe { host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, None, &mut texture) }.unwrap(); + let depth = Arc::new(HostTexture::new(texture.unwrap(), DEPTH_WRITE, Vec::new())); + let twin = depth.twin.get_or_init(|| make(53, &depth.texture)).as_ref().unwrap(); + let list = host.new_list().unwrap(); + issued(); + assert!(route(&list, &depth, twin, UNORDERED_ACCESS)); + const PIXEL_SHADER_RESOURCE: u32 = 0x80; + assert!(!route(&list, &depth, twin, PIXEL_SHADER_RESOURCE)); + if let Some(b) = list.move_texture(&depth, PIXEL_SHADER_RESOURCE) { + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[b]) }; + } + list.close(); + let recorded = issued(); + host.execute(&[&list]); + // The GPU runs the prelude, then the list. + let mut run = issued(); + run.extend(recorded); + let key = |t: &HostTexture| t.texture.as_raw() as usize; + let mut states = std::collections::HashMap::from([(key(&depth), DEPTH_WRITE), (key(&twin.planes[0]), 0)]); + replay(&run, &mut states).unwrap(); + // What the list left is what the next prelude starts from. + assert_eq!(states[&key(&depth)], depth.state.load(Relaxed)); + assert_eq!(states[&key(&twin.planes[0])], twin.planes[0].state.load(Relaxed)); + } } diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index df74cc0cb7..aaeaa0e9fa 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -35,6 +35,7 @@ //! and allocated again while a tracker holds it is not seen. use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; /// The unit tracked and copied: 64 KiB, the console's page. Finer units @@ -42,9 +43,58 @@ use std::sync::{Arc, Mutex}; /// they saved. pub(crate) const PAGE: usize = 64 << 10; -/// The pages a tracker has not taken since they changed, and what it saves -/// of pages it armed. -struct Changed(Mutex>, Mutex); +/// The pages a tracker has not taken since they changed, what it saves of +/// pages it armed, its bit in [`DIRTY`] (none: always taken as dirty), and +/// whether it is a host buffer copy's (the only trackers [`retake`] marks). +struct Changed(Mutex>, Mutex, Option, bool); + +/// A bit per tracker, set while it holds changed pages: set and cleared +/// under the tracker's lock, read without one ([`Tracked::clean`]). Dense, +/// so that a submission asking about every copy its heaps reach (~14,000) +/// reads a few KB instead of a cache line per copy. +static DIRTY: [AtomicU64; DIRTY_WORDS] = [const { AtomicU64::new(0) }; DIRTY_WORDS]; +const DIRTY_WORDS: usize = 1 << 14; + +/// Bits of [`DIRTY`] given back, and the first never handed out. +static FREE_BITS: Mutex<(Vec, u32)> = Mutex::new((Vec::new(), 0)); + +fn dirty_bit() -> Option { + let mut free = FREE_BITS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(bit) = free.0.pop() { + return Some(bit); + } + let bit = free.1; + (bit < (DIRTY_WORDS * 64) as u32).then(|| { + free.1 += 1; + bit + }) +} + +fn set_dirty(bit: Option, dirty: bool) { + if let Some(bit) = bit { + let (word, mask) = (&DIRTY[bit as usize / 64], 1u64 << (bit % 64)); + if dirty { + word.fetch_or(mask, Ordering::Release); + } else { + word.fetch_and(!mask, Ordering::Release); + } + } +} + +/// Whether the tracker with bit `bit` holds no changed page (see +/// [`Tracked::clean`]). +pub(crate) fn clean_bit(bit: Option) -> bool { + bit.is_some_and(|bit| DIRTY[bit as usize / 64].load(Ordering::Acquire) & 1 << (bit % 64) == 0) +} + +impl Drop for Changed { + fn drop(&mut self) { + if let Some(bit) = self.2 { + set_dirty(Some(bit), false); + FREE_BITS.lock().unwrap_or_else(|e| e.into_inner()).0.push(bit); + } + } +} /// Pages (page numbers) whose bytes a tracker keeps when they are first /// written after it took them, and those bytes: while shaders may be @@ -78,11 +128,17 @@ impl Changed { } } +/// Byte runs `[start, end)` in order. +pub(crate) type Runs = Vec<(usize, usize)>; + /// Title memory a host copy or texture staging takes: bytes `[start, end)`. pub(crate) struct Tracked { start: usize, end: usize, changed: Arc, + /// Parts of the range on pages that are not the runtime's memory (in + /// order): not tracked, copied whole at each use ([`Tracked::untracked`]). + untracked: Vec<(usize, usize)>, } struct Guards { @@ -207,51 +263,109 @@ fn guard_aliases(g: &mut Guards, pairs: &[(usize, usize)]) { /// written through other views showing the same pages: the title fills /// streamed textures and video planes through a pool view and maps the /// pages into its tiled heap, where a guard sees none of it). +/// +/// Only the pages of the range that are such memory are tracked; the rest is +/// never guarded and is copied whole at each use, as memory with no tracker. pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { - if len == 0 || !runtime_memory(start, views) { + track_as(start, len, views, false) +} + +/// [`track`] for a host buffer copy: what shaders write lands in it, so a +/// [`retake`] of its memory marks it. +pub(crate) fn track_copy(start: usize, len: usize, views: bool) -> Option { + track_as(start, len, views, true) +} + +fn track_as(start: usize, len: usize, views: bool, copy: bool) -> Option { + if len == 0 { return None; } - install(); let end = start + len; - let pages = start / PAGE..end.div_ceil(PAGE); - let changed = Arc::new(Changed(Mutex::new(pages.clone().collect()), Mutex::default())); + let pages = runtime_pages(start, end, views); + if pages.is_empty() { + return None; + } + install(); + // The rest of the range, as byte runs. + let mut untracked: Vec<(usize, usize)> = Vec::new(); + let mut at = start; + for &page in pages.iter().chain([&usize::MAX]) { + let (a, b) = ((page.saturating_mul(PAGE)).max(start).min(end), (page.saturating_add(1).saturating_mul(PAGE)).min(end)); + if at < a { + untracked.push((at, a)); + } + at = at.max(b); + } + // A tracker with untracked parts is never clean: no bit. + let bit = if untracked.is_empty() { dirty_bit() } else { None }; + set_dirty(bit, true); + let changed = Arc::new(Changed(Mutex::new(pages.iter().copied().collect()), Mutex::default(), bit, copy)); let mut g = guards(); - for page in pages { + for &page in &pages { g.holders.entry(page).or_default().push(changed.clone()); } + drop(g); Some(Tracked { start, end, changed, + untracked, }) } -/// Whether memory at `at` is the runtime's GPU memory: a write-watched -/// pool, or (with `views`) a view or a placeholder (anything but plain -/// committed memory). -fn runtime_memory(at: usize, views: bool) -> bool { +/// The pages of `[start, end)` that are the runtime's GPU memory: a +/// write-watched pool, or (with `views`) anything but plain committed memory +/// and images (views, placeholders, nothing mapped yet). Decided for every +/// region the range covers, and a page touching any other memory is left +/// out: a range can run past its allocation (a 4 MiB window of memory +/// outside buffers, `crate::shadow`), and when the first page alone decided, +/// a window starting in free memory had the process heap's pages after it +/// guarded; the heap's own code then faulted while holding its lock, and the +/// guard handler waited for the guard lock, whose holder waited for the heap +/// lock (the crate's tests hung). +/// +/// shortcut: memory free or reserved when the range is tracked counts as the +/// runtime's; another allocator committing it before the first take would +/// have it guarded. +fn runtime_pages(start: usize, end: usize, views: bool) -> Vec { use windows_sys::Win32::System::Memory::{ - GetWriteWatch, MEM_COMMIT, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, VirtualQuery, + GetWriteWatch, MEM_COMMIT, MEM_IMAGE, MEM_PRIVATE, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + let watched = |at: usize, len: usize| { + let (mut found, mut count, mut granularity) = (0usize, 1usize, 0u32); + // SAFETY: room for one answer; no reset, so nothing changes. + unsafe { GetWriteWatch(0, at as *const _, len, (&raw mut found).cast(), &mut count, &mut granularity) == 0 } }; - let page = at & !(4096 - 1); - let (mut found, mut count, mut granularity) = (0usize, 1usize, 0u32); - // SAFETY: room for one answer; no reset, so nothing changes. - let watched = unsafe { - GetWriteWatch(0, page as *const _, 4096, (&raw mut found).cast(), &mut count, &mut granularity) - } == 0; - if watched || !views { - return watched; + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + // One pool holds it all (the common case; asking `VirtualQuery` costs + // milliseconds in the runtime's big pools). + if watched(start & !(4096 - 1), end - (start & !(4096 - 1))) { + return (first..last).collect(); } - // 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(page as *const _, &mut info, size_of_val(&info)) }; - n != 0 && !(info.State == MEM_COMMIT && info.Type == MEM_PRIVATE) + let (mut runtime, mut other) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + let mut at = start & !(4096 - 1); + while at < end { + // 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. + if unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) } == 0 { + break; + } + let next = (info.BaseAddress as usize + info.RegionSize).max(at + 1).min(end); + let ours = watched(at, next - at) + || views && info.Type != MEM_IMAGE && !(info.State == MEM_COMMIT && info.Type == MEM_PRIVATE); + (if ours { &mut runtime } else { &mut other }).extend(at / PAGE..next.div_ceil(PAGE)); + at = next; + } + runtime.difference(&other).copied().collect() } impl Drop for Tracked { /// Pages no tracker holds any more get write access back, so that the - /// guard set never names memory freed and allocated again. + /// guard set never names memory freed and allocated again; unless another + /// mapping of the page is held: the guard here is that tracker's too (it + /// was set when that tracker took its page), and with it opened a write + /// here went unseen there. fn drop(&mut self) { let mut g = guards(); let mut free = Vec::new(); @@ -265,7 +379,10 @@ impl Drop for Tracked { } } for page in free { - open(&mut g, page); + let watched_elsewhere = g.alias_of.get(&page).is_some_and(|o| o.iter().any(|p| g.holders.contains_key(p))); + if !watched_elsewhere { + open(&mut g, page); + } } } } @@ -290,9 +407,26 @@ impl Tracked { /// `[from, to)`, in order. A page whose part in the tracked memory lies /// only partly in `[from, to)` is copied in part and stays changed. pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + let (copy, zero) = self.take_split(from, to); + let mut runs: Vec<(usize, usize)> = copy.into_iter().chain(zero).collect(); + runs.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for (a, b) in runs { + match merged.last_mut() { + Some((_, end)) if *end == a => *end = b, + _ => merged.push((a, b)), + } + } + merged + } + + /// [`Tracked::take`], the runs on pages with nothing mapped apart: they + /// read as zeros, with no copy to try (each such page cost a dozen + /// failing kernel reads, 7-30 ms a frame in run perf4). + pub(crate) fn take_split(&self, from: usize, to: usize) -> (Runs, Runs) { let (from, to) = (from.max(self.start), to.min(self.end)); if from >= to { - return Vec::new(); + return (Vec::new(), Vec::new()); } let pages: Vec = { #[cfg(feature = "diagnostics")] @@ -303,7 +437,7 @@ impl Tracked { changed.range(from / PAGE..to.div_ceil(PAGE)).copied().collect() }; if pages.is_empty() { - return Vec::new(); + return (Vec::new(), Vec::new()); } let whole: Vec = pages .iter() @@ -324,21 +458,24 @@ impl Tracked { guard_aliases(&mut g, &others); #[cfg(feature = "diagnostics")] drop(asked); - for page in protect(&mut g, &whole) { + let mut unmapped = Vec::new(); + for page in protect_noting(&mut g, &whole, &mut unmapped) { changed.remove(&page); self.changed.taken(page); } + set_dirty(self.changed.2, !changed.is_empty()); drop(changed); drop(g); - let mut runs: Vec<(usize, usize)> = Vec::new(); + let (mut copy, mut zero): (Runs, Runs) = (Vec::new(), Vec::new()); for p in pages { let (a, b) = ((p * PAGE).max(from), ((p + 1) * PAGE).min(to)); + let runs = if unmapped.contains(&p) { &mut zero } else { &mut copy }; match runs.last_mut() { Some((_, end)) if *end == a => *end = b, _ => runs.push((a, b)), } } - runs + (copy, zero) } /// Whether page `page` (a page number) changed since it was taken. @@ -361,6 +498,30 @@ impl Tracked { changed.remove(&page); self.changed.taken(page); } + set_dirty(self.changed.2, !changed.is_empty()); + } + + /// Whether no page changed since it was taken: then [`Tracked::take`] + /// finds nothing, and asking costs no lock. A write racing this answer + /// is found by the next asking, as one racing a take. + pub(crate) fn clean(&self) -> bool { + clean_bit(self.changed.2) + } + + /// The tracker's bit for [`clean_bit`], for callers that ask about + /// many trackers at once without touching each (none: never clean). + pub(crate) fn bit(&self) -> Option { + self.changed.2 + } + + /// The parts of `[from, to)` that are not tracked (see + /// [`Tracked::untracked`] field): to be copied whole at each use. + pub(crate) fn untracked(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + self.untracked + .iter() + .map(|&(a, b)| (a.max(from), b.min(to))) + .filter(|&(a, b)| a < b) + .collect() } /// Shaders may write the copy's bytes `[from, to)` until [`Tracked::disarm`]: @@ -397,6 +558,12 @@ impl Tracked { /// now guarded or with nothing mapped (taken either way); a page that is /// mapped but cannot be guarded is left out (it stays changed). fn protect(g: &mut Guards, pages: &[usize]) -> Vec { + protect_noting(g, pages, &mut Vec::new()) +} + +/// [`protect`], also listing in `unmapped` the pages taken because nothing +/// is mapped there. +fn protect_noting(g: &mut Guards, pages: &[usize], unmapped_pages: &mut Vec) -> Vec { #[cfg(feature = "diagnostics")] let counted = |calls: u64, pages: u64| { crate::copystat::add(crate::copystat::C::ProtectCalls, calls); @@ -449,6 +616,7 @@ fn protect(g: &mut Guards, pages: &[usize]) -> Vec { taken.push(page); } else if unmapped(page) { taken.push(page); + unmapped_pages.push(page); } } } @@ -482,7 +650,11 @@ fn changed_here(g: &mut Guards, first: usize, last: usize, save: bool) -> bool { } for (&page, holders) in g.holders.range(first..last) { for c in holders { - let first_write = c.0.lock().unwrap_or_else(|e| e.into_inner()).insert(page); + let first_write = { + let mut set = c.0.lock().unwrap_or_else(|e| e.into_inner()); + set_dirty(c.2, true); + set.insert(page) + }; if first_write && save { c.save(page); } @@ -561,6 +733,36 @@ pub fn title_memory_remapped(at: usize, len: usize) { } } +/// What shaders wrote into host copies of `[at, at + len)` is dropped: +/// every host buffer copy holding the memory takes it from title memory +/// again at its next refresh (the pages count as changed in each, aliases +/// too). Title memory itself did not change, so its guards stay (opened page +/// by page, they cost ~15 % of the submitting thread at each frame end, run +/// perf15), and other trackers (textures' staging, heaps) are left alone: +/// shaders' writes never reach them (marked, textures over withheld ranges +/// were uploaded again for nothing: 19 % of the uploads, run evict3). +pub(crate) fn retake(at: usize, len: usize) { + let (first, last) = (at / PAGE, at.saturating_add(len).div_ceil(PAGE)); + let g = guards(); + let others: Vec = g.alias_of.range(first..last).flat_map(|(_, o)| o.iter().copied()).collect(); + mark(&g, first, last); + for page in others { + mark(&g, page, page + 1); + } +} + +/// Pages `[first, last)` count as changed in every host buffer copy's +/// tracker holding them. +fn mark(g: &Guards, first: usize, last: usize) { + for (&page, holders) in g.holders.range(first..last) { + for c in holders.iter().filter(|c| c.3) { + let mut set = c.0.lock().unwrap_or_else(|e| e.into_inner()); + set_dirty(c.2, true); + set.insert(page); + } + } +} + /// The runtime mapped the page at `at` where `others` show it already: the /// pages are linked both ways, and if we guard it there, it is guarded here /// too (a write through the new mapping must not go unseen by the trackers @@ -684,16 +886,21 @@ pub(crate) mod tests { let p = pool(4); let a = track(p, 4 * PAGE, true).expect("pool memory is tracked"); let b = track(p + PAGE, 2 * PAGE, true).expect("tracked"); + assert!(!a.clean() && !b.clean(), "changed at first"); assert_eq!(a.take(p, p + 4 * PAGE), [(p, p + 4 * PAGE)]); + assert!(a.clean() && !b.clean()); assert_eq!(b.take(p, p + 4 * PAGE), [(p + PAGE, p + 3 * PAGE)]); assert!(a.take(p, p + 4 * PAGE).is_empty() && b.take(p, p + 4 * PAGE).is_empty()); + assert!(a.clean() && b.clean()); // SAFETY: committed pages of ours, now read-only: the handler opens // the block; the second write needs no fault. unsafe { ((p + PAGE + 8) as *mut u8).write_volatile(1); ((p + PAGE + 9) as *mut u8).write_volatile(2); } + assert!(!a.clean() && !b.clean(), "a write is seen by every tracker"); assert_eq!(a.take(p, p + 4 * PAGE), [(p + PAGE, p + 2 * PAGE)]); + assert!(a.clean()); // `a` guarded it again; `b` still has it changed. assert!(b.changed(p / PAGE + 1)); assert_eq!(b.take(p, p + 4 * PAGE), [(p + PAGE, p + 2 * PAGE)]); @@ -709,6 +916,89 @@ pub(crate) mod tests { free(p); } + /// A range running from free memory over another allocation into a pool + /// (a 4 MiB window of memory outside buffers) tracks the pool's pages + /// and leaves the other allocation alone: taking guards the pool only. + #[test] + fn a_range_over_foreign_memory_guards_only_the_runtimes() { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, PAGE_READONLY, VirtualQuery}; + const WINDOW: usize = 4 << 20; + // In a free 4 MiB-aligned window: plain committed memory (as the + // process heap's) 1 MiB in, a pool 2 MiB in. Other tests allocate + // meanwhile, so a window taken under our feet is tried again. + let (base, foreign, pool) = (0..8) + .find_map(|_| { + // SAFETY: a fresh reservation, released at once; then + // allocations in the window it left free, freed below. + unsafe { + let p = VirtualAlloc(std::ptr::null(), 2 * WINDOW, MEM_RESERVE, PAGE_READWRITE) as usize; + VirtualFree(p as *mut _, 0, MEM_RELEASE); + let base = p.next_multiple_of(WINDOW); + let at = |offset: usize, kind: u32| { + VirtualAlloc((base + offset) as *const _, PAGE, MEM_RESERVE | MEM_COMMIT | kind, PAGE_READWRITE) as usize + }; + let (foreign, pool) = (at(1 << 20, 0), at(2 << 20, MEM_WRITE_WATCH)); + if p != 0 && foreign == base + (1 << 20) && pool == base + (2 << 20) { + return Some((base, foreign, pool)); + } + [foreign, pool].into_iter().filter(|&q| q != 0).for_each(free); + None + } + }) + .expect("a free window"); + let t = track(base, WINDOW, true).expect("the pool is tracked"); + let taken = t.take(base, base + WINDOW); + assert!(taken.iter().any(|&(a, b)| a <= pool && pool + PAGE <= b), "{taken:x?}"); + assert!(!taken.iter().any(|&(a, b)| a < foreign + PAGE && foreign < b), "{taken:x?}"); + let protection = |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. + unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + info.Protect + }; + assert_eq!(protection(pool), PAGE_READONLY, "the pool is guarded"); + assert_eq!(protection(foreign), PAGE_READWRITE, "the other allocation is not"); + drop(t); + free(foreign); + free(pool); + } + + /// A tracker's dirty bit goes back when it goes, and the next tracker + /// starts dirty on it (everything changed at first). + #[test] + fn a_new_tracker_starts_dirty_on_a_bit_given_back() { + let p = pool(1); + let a = track(p, PAGE, true).expect("tracked"); + assert_eq!(a.take(p, p + PAGE).len(), 1); + assert!(a.clean() && clean_bit(a.bit())); + drop(a); + let b = track(p, PAGE, true).expect("tracked"); + assert!(!b.clean() && !clean_bit(b.bit())); + assert!(!clean_bit(None), "no bit: never clean"); + drop(b); + free(p); + } + + /// A page with nothing mapped is taken as zeros: `take_split` lists it + /// apart from the pages to copy. + #[test] + fn unmapped_pages_are_taken_apart() { + // SAFETY: a fresh write-watched reservation of two pages, the first + // committed; freed below. + let p = unsafe { + let p = VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(p, 0); + assert_ne!(VirtualAlloc(p as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) as usize, 0); + p + }; + let t = track(p, 2 * PAGE, true).expect("tracked"); + assert_eq!(t.take_split(p, p + 2 * PAGE), (vec![(p, p + PAGE)], vec![(p + PAGE, p + 2 * PAGE)])); + assert!(t.take(p, p + 2 * PAGE).is_empty(), "both taken"); + drop(t); + free(p); + } + /// A page only partly in the range asked is copied in part and stays /// changed; edge pages count whole when the tracked part is covered. #[test] @@ -717,8 +1007,10 @@ pub(crate) mod tests { let t = track(p + 100, 2 * PAGE, true).expect("tracked"); assert_eq!(t.take(p + 100, p + PAGE + 10), [(p + 100, p + PAGE + 10)]); assert!(!t.changed(p / PAGE) && t.changed(p / PAGE + 1)); + assert!(!t.clean(), "a page taken in part stays changed"); assert_eq!(t.take(p, p + 3 * PAGE), [(p + PAGE, p + 2 * PAGE + 100)]); assert!(t.take(p, p + 3 * PAGE).is_empty()); + assert!(t.clean()); drop(t); free(p); } @@ -845,6 +1137,82 @@ pub(crate) mod tests { assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + PAGE)]); } + /// A tracker of one mapping going away leaves the guard its page shares + /// with a tracker of another mapping, so a write there still counts (it + /// was opened, and the pages it went unseen in stayed clean). + #[test] + fn a_tracker_dropped_on_one_mapping_leaves_the_other_guarded() { + let (a, b) = twin_views(1); + let t = track(a, PAGE, true).expect("views are tracked"); + let u = track(b, PAGE, true).expect("views are tracked"); + assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); + assert_eq!(u.take(b, b + PAGE), [(b, b + PAGE)]); + drop(u); + // SAFETY: the second view, guarded for `t`'s page too. + unsafe { ((b + 4) as *mut u32).write_volatile(7) }; + assert_eq!(t.take(a, a + PAGE), [(a, a + PAGE)]); + } + + /// A retake has every copy of the memory, and of its other mappings, + /// take it again, and leaves it guarded: a later write still counts. + #[test] + fn a_retake_marks_the_copies_and_keeps_the_guard() { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, PAGE_READONLY, VirtualQuery}; + let protection = |at: 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. + unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + info.Protect + }; + let (a, b) = twin_views(2); + let t = track_copy(a, 2 * PAGE, true).expect("views are tracked"); + let u = track_copy(b, 2 * PAGE, true).expect("views are tracked"); + assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + 2 * PAGE)]); + assert_eq!(u.take(b, b + 2 * PAGE), [(b, b + 2 * PAGE)]); + assert!(t.clean() && u.clean()); + retake(a + PAGE + 16, 32); + // Marked in both copies, the second mapping's too, still guarded. + assert!(!t.clean() && !u.clean()); + assert!(t.changed((a + PAGE) / PAGE) && u.changed((b + PAGE) / PAGE)); + assert!(!t.changed(a / PAGE)); + assert_eq!(protection(a + PAGE), PAGE_READONLY); + assert_eq!(protection(b + PAGE), PAGE_READONLY); + // Taken again (the copies re-copy that page), then guarded and clean. + assert_eq!(t.take(a, a + 2 * PAGE), [(a + PAGE, a + 2 * PAGE)]); + assert_eq!(u.take(b, b + 2 * PAGE), [(b + PAGE, b + 2 * PAGE)]); + assert!(t.clean() && u.clean()); + assert_eq!(protection(a + PAGE), PAGE_READONLY); + // SAFETY: the second view, guarded all along. + unsafe { ((b + PAGE + 8) as *mut u32).write_volatile(3) }; + assert_eq!(t.take(a, a + 2 * PAGE), [(a + PAGE, a + 2 * PAGE)]); + assert_eq!(u.take(b, b + 2 * PAGE), [(b + PAGE, b + 2 * PAGE)]); + // A retake while marked and guarded, then a drop: nothing breaks. + retake(a, 2 * PAGE); + drop(u); + assert_eq!(t.take(a, a + 2 * PAGE), [(a, a + 2 * PAGE)]); + assert!(t.clean()); + } + + /// A retake marks host buffer copies holding the memory, not other + /// trackers of it (a texture's staging): shaders' writes reach only the + /// copies. A title write still marks both. + #[test] + fn a_retake_marks_buffer_copies_alone() { + let p = pool(2); + let copy = track_copy(p, 2 * PAGE, true).expect("pool memory is tracked"); + let texture = track(p, 2 * PAGE, true).expect("pool memory is tracked"); + assert_eq!(copy.take(p, p + 2 * PAGE), [(p, p + 2 * PAGE)]); + assert_eq!(texture.take(p, p + 2 * PAGE), [(p, p + 2 * PAGE)]); + retake(p + PAGE, 16); + assert!(copy.changed(p / PAGE + 1), "the copy takes it again"); + assert!(!texture.changed(p / PAGE + 1) && texture.clean(), "the texture's tracker is left alone"); + assert_eq!(copy.take(p, p + 2 * PAGE), [(p + PAGE, p + 2 * PAGE)]); + // SAFETY: a page of our pool, guarded: the handler opens it. + unsafe { ((p + PAGE + 8) as *mut u8).write_volatile(1) }; + assert!(copy.changed(p / PAGE + 1) && texture.changed(p / PAGE + 1), "a title write marks both"); + } + /// 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/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 83a7a81ae2..9cef4f09a1 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -144,7 +144,7 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; - let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file, path: name }); put(out, file) } @@ -258,6 +258,8 @@ static FACTORY_VTABLE: Methods<16> = Methods([ struct File { file: std::fs::File, + /// As the title named it (diagnostics). + path: String, } static FILE_VTABLE: Methods<8> = Methods([ @@ -368,6 +370,9 @@ struct Lane { clock: u64, /// Enqueued, not yet submitted. unsubmitted: Vec, + /// Left out when the queue submitted itself, until the title's Submit: + /// reads into physical pages and the status entries behind them. + held: Vec, /// Submitted, by sequence number: reads not started, status entries /// not written, reads running, and failures not yet reported. reads: VecDeque<(u64, Request)>, @@ -547,8 +552,20 @@ impl Lanes { } } - /// Moves a queue's enqueued commands to the workers. + /// Moves a queue's enqueued commands to the workers (the title's + /// Submit). fn submit(&mut self, id: u64) { + self.submit_as(id, true); + } + + /// As [`Lanes::submit`]; `explicit` false when a half-full queue submits + /// itself, which leaves reads into physical pages for the title's + /// Submit: their page lists point into the title's page table, which + /// Grand Theft Auto VI fills for the batch in its own submit path, right + /// before Submit (`sub_1400e88f0`), so until then they name no page or a + /// page that now holds something else. A status entry behind a held + /// read waits with it. + fn submit_as(&mut self, id: u64, explicit: bool) { let Some(class) = self.lanes.get(&id).map(|l| l.class) else { return; }; @@ -567,7 +584,18 @@ impl Lanes { if lane.reads.is_empty() { lane.clock = lane.clock.max(self.lane_now[class]); } - for command in std::mem::take(&mut lane.unsubmitted) { + let mut commands = if explicit { std::mem::take(&mut lane.held) } else { Vec::new() }; + commands.append(&mut lane.unsubmitted); + for command in commands { + let hold = !explicit + && match &command { + Command::Read(r) => r.options & PAGE_DESTINATION != 0, + Command::Status(_) => !lane.held.is_empty(), + }; + if hold { + lane.held.push(command); + continue; + } let seq = self.next_seq; self.next_seq += 1; match command { @@ -586,6 +614,7 @@ impl Lane { capacity: usize::from(capacity), clock: 0, unsubmitted: Vec::new(), + held: Vec::new(), reads: VecDeque::new(), statuses: VecDeque::new(), running: BTreeSet::new(), @@ -596,7 +625,11 @@ impl Lane { /// Requests and status entries held, submitted or not. fn entries(&self) -> usize { - self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + self.unsubmitted.len() + + self.held.len() + + self.reads.len() + + self.statuses.len() + + self.running.len() } /// Writes the status entries whose earlier reads have all finished. @@ -644,6 +677,7 @@ fn close_lane(id: u64) { }; lane.closed = true; lane.unsubmitted.clear(); + lane.held.clear(); lane.reads.clear(); lane.statuses.clear(); // releases their arrays while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { @@ -755,6 +789,16 @@ fn queue(this: QueueRef, command: Command) { if lane.entries() + 1 < lane.capacity.max(2) { break; } + // Full with reads held for a Submit the title cannot make while it + // waits here: they go now, page lists as they are. + if !lane.held.is_empty() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!("dstorage: a full queue's reads into physical pages start before the title's Submit"); + } + lanes.submit(id); + scheduler.work.notify_all(); + } lanes = scheduler .finished .wait(lanes) @@ -765,8 +809,19 @@ fn queue(this: QueueRef, command: Command) { }; lane.unsubmitted.push(command); if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { - lanes.submit(id); + let capacity = lane.capacity; + lanes.submit_as(id, false); scheduler.work.notify_all(); + let held = lanes.lanes.get(&id).map_or(0, |l| l.held.len()); + let n = AUTO_SUBMITS.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + capacity, + held, + "dstorage: a queue half full submitted itself; reads into physical pages wait for the title's Submit" + ); + } } } @@ -777,7 +832,7 @@ extern "system" fn submit(this: QueueRef) { return; }; let mut lanes = scheduler.lock(); - let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len() + l.held.len()); tracing::debug!(commands = pending, "dstorage: submit"); lanes.submit(id); scheduler.work.notify_all(); @@ -1012,11 +1067,28 @@ fn into_destination( offset, len, pages = pages.len(), + unknown = super::xmem::unknown_pages(pages), + list = format_args!("{:x?}", &pages[..pages.len().min(8)]), + options = format_args!("{:#x}", request.options), + file = source_name(request), + file_offset = request.offset, "dstorage: a destination's physical pages could not be written; its request fails" ); Err(E_INVALIDARG) } +/// The file a request reads, as the title named it, or "memory". +fn source_name(request: &Request) -> &str { + if request.options & MEMORY_SOURCE != 0 { + return "memory"; + } + // SAFETY: a file object we created; the title keeps it open. + &unsafe { &*request.source.cast::>() }.state.path +} + +/// Queues that submitted themselves, half full (diagnostics). +static AUTO_SUBMITS: AtomicU32 = AtomicU32::new(0); + /// Milliseconds a page list naming page 0 is read again for. const LATE_LIST_TRIES: u32 = 8; /// Page lists filled after their request started (written late). @@ -1573,6 +1645,95 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::(), plain.len()) }; assert_eq!(seen, plain); } + #[test] + fn a_queue_that_submits_itself_holds_reads_into_pages() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(1).cast::>(); + read(&mut l, 0, PAGE_DESTINATION, 16); + read(&mut l, 0, 0, 16); + add_ref_instance(array); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(Command::Status(Status { array, index: 0 })); + l.submit_as(0, false); + // Only the plain read starts; the status waits behind the held one. + let plain = l.start().unwrap(); + assert_eq!(plain.request.options, 0); + assert!(l.start().is_none()); + l.finish(&plain, Ok(())); + assert_eq!(l.lanes[&0].held.len(), 2); + l.submit(0); + let paged = l.start().unwrap(); + assert_eq!(paged.request.options, PAGE_DESTINATION); + assert!(l.lanes[&0].held.is_empty()); + assert!(!l.lanes[&0].statuses.is_empty()); + l.finish(&paged, Ok(())); + assert!(l.lanes[&0].statuses.is_empty()); + } + + #[test] + fn a_page_list_the_title_changes_before_its_submit() { + use crate::modules::xmem; + let (mut given, mut pages) = (2usize, [0usize; 2]); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!(xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), mapped); + // The title's page table: still the page's previous owner when the + // request is enqueued, the right page by its Submit. + let mut list = [pages[0]]; + let plain = pattern(4096); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"pages".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + list.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + enqueue(queue, &r); + let mut out = [0u8; 16]; + enqueue(queue, &request(MEMORY_SOURCE, out.as_mut_ptr().cast(), 16, plain.as_ptr().cast(), 0, 16)); + // Half of four: the queue submitted itself. Time for a read started + // then to land in the old page. + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the list outlives the request, which reads it when it runs. + unsafe { std::ptr::write_volatile(list.as_mut_ptr(), pages[1]) }; + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain[..16]); + // SAFETY: both pages are mapped read-write. + let (first, second) = unsafe { + ( + std::slice::from_raw_parts(mapped.cast::(), plain.len()), + std::slice::from_raw_parts(mapped.cast::().add(PAGE), plain.len()), + ) + }; + assert_eq!(second, plain); + assert!(first.iter().all(|&b| b == 0), "the old page was written"); + } + #[test] fn zlib_into_pages_in_place_and_across_allocations() { use crate::modules::xmem; diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 83c96132cf..5b515a04a7 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -441,10 +441,18 @@ fn shown_at(pages: &[usize]) -> Vec { /// view showing them (DirectStorage's page destinations). fn report_written(shown: &[usize]) { for &page in shown { + #[cfg(test)] + REPORTED.with(|r| r.borrow_mut().push(page)); drop(victory_gpu::kernel_will_write(page, PAGE)); } } +#[cfg(test)] +thread_local! { + /// The title addresses this thread's writes into physical pages reported. + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + static PHYSICAL: LazyLock> = LazyLock::new(|| { Mutex::new(Physical { // Page numbers are opaque to titles; 0 stays unused. @@ -523,6 +531,13 @@ pub extern "system" fn XMemAllocatePhysicalPages( /// them with `<< 4` (128 GiB of pages at most). const FRAMES: usize = PAGE >> 12; +/// How many of `pages` are no allocated page (diagnostics: a DirectStorage +/// destination that could not be written). +pub(crate) fn unknown_pages(pages: &[usize]) -> usize { + let physical = physical(); + pages.iter().filter(|p| !physical.pages.contains_key(p)).count() +} + /// Pages still mapped stay readable through their views until unmapped. pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL { if pages.is_null() { @@ -615,7 +630,6 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo let Some(runs) = runs(pages, offset, data.len()) else { return false; }; - let shown = shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[])); let (mut within, mut done) = (offset % PAGE, 0); for (slice, n) in &runs { let Some(mut view) = View::map(slice, *n) else { @@ -625,7 +639,8 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); (within, done) = (0, done + k); } - report_written(&shown); + // Where the pages show once written (see `PageWindow`). + report_written(&shown_at(pages.get(offset / PAGE..(offset + data.len()).div_ceil(PAGE)).unwrap_or(&[]))); true } @@ -636,13 +651,18 @@ pub(crate) struct PageWindow { view: View, within: usize, len: usize, - /// Title views showing the pages, told when the window is done. - shown: Vec, + /// The pages (page numbers) the bytes reach: the title views showing + /// them when the window is done are told. Looked up then, not when the + /// window opens: a decode takes milliseconds, and the title may map a + /// page at another address meanwhile (its GPU heap); a copy that took + /// the page there before the bytes landed would never hear of them. An + /// address that stops showing a page meanwhile was told by the unmap. + pages: Vec, } impl Drop for PageWindow { fn drop(&mut self) { - report_written(&self.shown); + report_written(&shown_at(&self.pages)); } } @@ -667,7 +687,7 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< view: View::map(slice, *n)?, within: offset % PAGE, len, - shown: shown_at(pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or(&[])), + pages: pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or(&[]).to_vec(), }) } @@ -1343,6 +1363,35 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + /// A page mapped at a second address while a window writes it is + /// reported there too when the window is done (the title maps streamed + /// pages into its GPU heap while their reads decode); an address that + /// stopped showing it meanwhile is not. + #[test] + fn page_windows_report_where_the_pages_show_when_done() { + let pages = allocate(1); + let reserve = || XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 1, pages.as_ptr()), a); + REPORTED.with(|r| r.borrow_mut().clear()); + let mut window = page_window(&pages, 0, 16).expect("one run"); + // Mapped at `b`, unmapped from `a`, while the bytes are written. + assert_eq!(XMemMapPhysicalPages(b, 1, pages.as_ptr()), b); + assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); + window.bytes().fill(3); + drop(window); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [b as usize]); + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::().read() }, 3); + // `write_physical` the same way. + REPORTED.with(|r| r.borrow_mut().clear()); + assert!(write_physical(&pages, 0, &[4])); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [b as usize]); + assert_eq!(XMemMapPhysicalPages(b, 1, std::ptr::null()), b); + assert_eq!(XMemFreePhysicalPages(1, pages.as_ptr()), 1); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1)); diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 77cfff3b90..d727154e89 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -521,11 +521,49 @@ impl Module { self.named.push((name.into(), nodes)); } - /// The module as bitcode. - /// Which instructions are written: every body instruction, the branch - /// conditions, and whatever they read, transitively (a phi nothing reads - /// is dropped). A worklist visits each instruction once, so a long chain - /// of merges costs one pass, not one pass per merge. + /// Whether body instruction `i` is written even if nothing reads it: it + /// has effects (stores, atomics, calls of operations that are neither + /// read-none nor read-only). + fn rooted(&self, i: u32) -> bool { + match &self.insts[i as usize].op { + Op::Call(f, _) => !matches!(self.funcs[*f as usize].attr, Some(Attr::ReadNone | Attr::ReadOnly)), + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true, + _ => false, + } + } + + /// What the instructions [`Module::write`] writes use, of what the + /// shader flags declare (which must match it, or the validator refuses + /// the module: "Flags must match usage"). + pub fn uses(&self) -> Uses { + let plan = self.plan(); + let wide = |t: Ty| self.types[t.0 as usize] == TypeDef::Int(64); + let mut u = Uses::default(); + for b in plan.layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().chain(&b.body).filter(|&&i| plan.live[i as usize]) { + let inst = &self.insts[i as usize]; + u.int64 |= wide(inst.ty); + for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + let Op::Call(f, args) = &inst.op else { continue }; + let name = self.funcs[*f as usize].name.as_str(); + if name.starts_with("dx.op.createHandleFromHeap") { + // Arguments: opcode, index, sampler heap, non-uniform. + let sampler = args.get(2).and_then(|&a| self.int_value(a)).is_some_and(|x| x != 0); + u.heap |= !sampler; + u.sampler_heap |= sampler; + } + u.wave |= name.starts_with("dx.op.wave") || name.starts_with("dx.op.quad"); + } + } + u + } + + /// Which instructions are written: those [`Module::rooted`], the + /// branch conditions, and whatever they read, transitively (a phi or a + /// value nothing reads is dropped: lowering makes size queries for + /// descriptor words no path reads, 556 of ActivateRays' 587). A worklist + /// visits each instruction once, so a long chain of merges costs one + /// pass, not one pass per merge. fn live(&self) -> Vec { let mut live = vec![false; self.insts.len()]; let mut work: Vec = Vec::new(); @@ -538,7 +576,7 @@ impl Module { } }; for b in &self.blocks { - for &i in &b.body { + for &i in b.body.iter().filter(|&&i| self.rooted(i)) { mark(&mut live, &mut work, V::Inst(i)); } if let Some(Term::CondBr(c, ..)) = b.term { @@ -553,7 +591,155 @@ impl Module { live } + /// Block `b`'s terminator, a branch on a constant taking its one edge + /// (lowering leaves many: lane conditions structurisation knows, edges + /// no lane takes). + fn term(&self, b: usize) -> Option { + match self.blocks[b].term { + Some(Term::CondBr(c, t, f)) => match self.int_value(c) { + Some(x) => Some(Term::Br(if x != 0 { t } else { f })), + None => Some(Term::CondBr(c, t, f)), + }, + t => t, + } + } + + /// Calls of functions named `name` that [`Module::write`] writes. + #[cfg(test)] + pub fn written_calls(&self, name: &str) -> usize { + let plan = self.plan(); + let calls = plan.layout.iter().flat_map(|&b| &self.blocks[b].body); + calls + .filter(|&&i| plan.live[i as usize]) + .filter(|&&i| matches!(self.insts[i as usize].op, Op::Call(f, _) if self.funcs[f as usize].name == name)) + .count() + } + + /// The globals and functions [`Module::write`] declares, each kept + /// one's new index and their number: functions declared and not called, + /// and constant globals nothing reads, are left out (the validator + /// refuses them). + fn kept(&self, plan: &Plan) -> ((Vec, u32), (Vec, u32)) { + let mut called = vec![false; self.funcs.len()]; + let mut read = vec![false; self.globals.len()]; + for m in &self.mds { + if let MdDef::Value(_, V::Global(g)) = m { + read[*g as usize] = true; + } + } + for b in plan.layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().chain(&b.body).filter(|&&i| plan.live[i as usize]) { + let op = &self.insts[i as usize].op; + if let Op::Call(f, _) = *op { + called[f as usize] = true; + } + for_each_operand(op, |v| { + if let V::Global(g) = v { + read[g as usize] = true; + } + }); + } + } + let number = |keep: &mut dyn Iterator| { + let mut n = 0; + let ids = keep + .map(|k| { + n += u32::from(k); + if k { n - 1 } else { u32::MAX } + }) + .collect(); + (ids, n) + }; + let globals = number(&mut self.globals.iter().zip(&read).map(|(g, &r)| g.init.is_none() || r)); + let funcs = number(&mut self.funcs.iter().zip(&called).map(|(f, &c)| f.body || c)); + (globals, funcs) + } + + /// What [`Module::write`] writes: the instructions ([`Module::live`]), + /// the blocks reached from the entry through terminators as + /// [`Module::term`] gives them, in reverse postorder (every block after + /// its forward predecessors: drivers take a branch to an earlier block + /// for a loop's back edge), and the empty blocks folded away. + /// + /// An empty block (only a branch) with one predecessor is folded into + /// it: the predecessor branches to its target instead. For an empty + /// latch (a branch back to its loop header) this makes the exiting block + /// the latch, as in DXC's loops (the AMD driver hangs on divergent loops + /// otherwise); a forward one goes unless it splits a critical edge + /// (lowering splits them so that loops have dedicated exits and + /// preheaders, as DXC emits them), or its predecessor would reach the + /// target twice (the target's phis have one entry per predecessor). + fn plan(&self) -> Plan { + let live = self.live(); + let succs = |b: usize| successors(self.term(b)); + let mut seen = vec![false; self.blocks.len()]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in post.iter().enumerate() { + pos[b] = n as u64; + } + let mut preds = vec![Vec::new(); self.blocks.len()]; + for &b in &post { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + let mut plan = Plan { + live, + seen, + layout: Vec::new(), + pos: Vec::new(), + fold: vec![None; self.blocks.len()], + }; + for &b in &post { + let blk = &self.blocks[b]; + let empty = b != 0 && blk.phis.iter().chain(&blk.body).all(|&i| !plan.live[i as usize]); + if let (Some(Term::Br(h)), true, [p]) = (self.term(b), empty, &preds[b][..]) + && plan.to(h) != b + { + plan.fold[b] = Some((*p, h)); + let (from, at) = (plan.src(b), plan.to(h)); + let critical = succs(from).len() > 1 && preds[at].len() > 1 && pos[h] > pos[b]; + if critical || succs(from).iter().filter(|&&s| plan.to(s) == at).count() != 1 { + plan.fold[b] = None; + } + } + } + plan.layout = post.into_iter().filter(|&b| plan.fold[b].is_none()).collect(); + plan.pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in plan.layout.iter().enumerate() { + plan.pos[b] = n as u64; + } + plan + } + pub fn write(&self) -> Vec { + let plan = self.plan(); + let (live, layout) = (&plan.live, &plan.layout); + let term_of = |b: usize| self.term(b); + let target = |t: usize| plan.pos[plan.to(t)]; + let from = |b: usize| plan.pos[plan.src(b)]; + + let ((kept_globals, g_n), (kept, n)) = self.kept(&plan); + let mut w = Writer::default(); w.bytes(b"BC\xC0\xDE"); w.enter(MODULE_BLOCK, 3); @@ -616,8 +802,8 @@ impl Module { "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64", ), ); - let first_const = (self.globals.len() + self.funcs.len()) as u64; - for g in &self.globals { + let first_const = u64::from(g_n) + u64::from(n); + for g in self.globals.iter().zip(&kept_globals).filter(|(_, k)| **k != u32::MAX).map(|(g, _)| g) { // [type, address space << 2 | explicit type | constant, init id // + 1, linkage (external 0, internal 3), log2 alignment + 1, // section] @@ -637,7 +823,7 @@ impl Module { ], ); } - for f in &self.funcs { + for f in self.funcs.iter().zip(&kept).filter(|(_, k)| **k != u32::MAX).map(|(f, _)| f) { // [type, cc, isproto, linkage, paramattr, align, section, // visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix] let attr = f.attr.map_or(0, |a| a as u64); @@ -663,8 +849,8 @@ impl Module { } // Value ids: globals, functions, constants, instructions. - let globals = self.globals.len() as u32; - let funcs = globals + self.funcs.len() as u32; + let globals = g_n; + let funcs = globals + n; let const_id = |i: u32| u64::from(funcs + i); w.enter(CONSTANTS_BLOCK, 4); let mut current = None; @@ -685,74 +871,12 @@ impl Module { } w.exit(); - // Phis nothing reads are left out (one register per phi makes many). - let live = self.live(); - - // Blocks are laid out in reverse postorder, so every block follows - // its forward predecessors (drivers take a branch to an earlier - // block for a loop's back edge). - let succs = |b: usize| successors(self.blocks[b].term); - let mut seen = vec![false; self.blocks.len()]; - let mut post = Vec::new(); - let mut stack = vec![(0usize, 0usize)]; - seen[0] = true; - while let Some(top) = stack.last_mut() { - let (b, k) = *top; - top.1 += 1; - match succs(b).get(k) { - Some(&s) if !seen[s] => { - seen[s] = true; - stack.push((s, 0)); - } - Some(_) => {} - None => { - post.push(b); - stack.pop(); - } - } - } - post.reverse(); - let mut pos = vec![u64::MAX; self.blocks.len()]; - for (n, &b) in post.iter().enumerate() { - pos[b] = n as u64; - } - // An empty latch (only a branch back to its loop header) is folded - // into its one predecessor, so the exiting block is the latch as in - // DXC's loops; the AMD driver hangs on divergent loops otherwise. - let mut preds = vec![Vec::new(); self.blocks.len()]; - for &b in &post { - for &s in succs(b).iter() { - preds[s].push(b); - } - } - let mut fold = vec![None; self.blocks.len()]; - for &b in &post { - let blk = &self.blocks[b]; - if let (Some(Term::Br(h)), true, [p]) = ( - blk.term, - blk.phis.iter().all(|&i| !live[i as usize]) && blk.body.is_empty(), - &preds[b][..], - ) && pos[h] < pos[b] - && !succs(*p).contains(&h) - { - fold[b] = Some((*p, h)); - } - } - let layout: Vec = post.into_iter().filter(|&b| fold[b].is_none()).collect(); - let mut pos = vec![u64::MAX; self.blocks.len()]; - for (n, &b) in layout.iter().enumerate() { - pos[b] = n as u64; - } - // Branch targets and phi blocks through folded latches. - let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]); - let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]); - // Instruction value ids, in layout order. let base = funcs + self.consts.len() as u32; let mut ids = vec![u32::MAX; self.insts.len()]; let mut next = base; for b in layout.iter().map(|&b| &self.blocks[b]) { - for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + for &i in b.phis.iter().chain(&b.body).filter(|&&i| live[i as usize]) { if !self.is_void(self.insts[i as usize].ty) { ids[i as usize] = next; next += 1; @@ -761,8 +885,8 @@ impl Module { } let abs = |v: V| -> u32 { match v { - V::Global(i) => i, - V::Func(i) => globals + i, + V::Global(i) => kept_globals[i as usize], + V::Func(i) => globals + kept[i as usize], V::Const(i) => funcs + i, V::Inst(i) => { let id = ids[i as usize]; @@ -820,8 +944,9 @@ impl Module { w.exit(); w.enter(VALUE_SYMTAB_BLOCK, 4); - let names = self.globals.iter().map(|g| &g.name); - for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() { + let names = self.globals.iter().zip(&kept_globals).filter(|(_, k)| **k != u32::MAX).map(|(g, _)| &g.name); + let kept_names = self.funcs.iter().zip(&kept).filter(|(_, k)| **k != u32::MAX).map(|(f, _)| &f.name); + for (i, name) in names.chain(kept_names).enumerate() { let mut r = vec![i as u64]; r.extend(chars(name)); w.record(1, &r); @@ -833,8 +958,9 @@ impl Module { let mut inst_id = base; // The operands of variable-length records, reused across them. let mut r: Vec = Vec::new(); - for b in layout.iter().map(|&b| &self.blocks[b]) { - for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + for &x in layout { + let b = &self.blocks[x]; + for &i in b.phis.iter().chain(&b.body).filter(|&&i| live[i as usize]) { let inst = &self.insts[i as usize]; let rel = |v: V| { let a = abs(v); @@ -857,7 +983,7 @@ impl Module { Op::Phi(incoming) => { r.clear(); r.push(u64::from(inst.ty.0)); - for &(v, b) in incoming { + for &(v, b) in incoming.iter().filter(|&&(_, b)| plan.edge(self, b, x)) { r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); r.push(from(b)); } @@ -884,7 +1010,7 @@ impl Module { inst_id += 1; } } - match b.term.expect("unterminated block") { + match term_of(x).expect("unterminated block") { Term::Ret => w.record(10, &[]), Term::Br(t) => w.record(11, &[target(t)]), Term::CondBr(c, t, f) => { @@ -909,6 +1035,59 @@ const VALUE_SYMTAB_BLOCK: u64 = 14; const METADATA_BLOCK: u64 = 15; const TYPE_BLOCK: u64 = 17; +/// What the written instructions use of the features shader flags declare +/// ([`Module::uses`]). +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Uses { + /// Handles from the resource heap. + pub heap: bool, + /// Handles from the sampler heap. + pub sampler_heap: bool, + /// Wave and quad operations. + pub wave: bool, + /// 64-bit integers. + pub int64: bool, +} + +/// What [`Module::write`] writes ([`Module::plan`]). +struct Plan { + /// Per instruction: written. + live: Vec, + /// Per block: reached from the entry. + seen: Vec, + /// The blocks written, in order. + layout: Vec, + /// Per block: its place in `layout` (`u64::MAX` if not written). + pos: Vec, + /// Per folded block: its one predecessor and its target. + fold: Vec>, +} + +impl Plan { + /// The block a branch to `t` lands in (through folded blocks). + fn to(&self, mut t: usize) -> usize { + while let Some((_, h)) = self.fold[t] { + t = h; + } + t + } + + /// The block an edge from `b` leaves from (through folded blocks). + fn src(&self, mut b: usize) -> usize { + while let Some((p, _)) = self.fold[b] { + b = p; + } + b + } + + /// Whether a phi of block `x` keeps its entry from block `b`: the edge + /// is still there (not a constant branch's other edge, not from a block + /// left out). + fn edge(&self, m: &Module, b: usize, x: usize) -> bool { + self.seen[b] && successors(m.term(b)).iter().any(|&s| self.to(s) == x) + } +} + /// Calls `f` with every value `op` reads, in operand order. fn for_each_operand(op: &Op, mut f: impl FnMut(V)) { match op { @@ -1119,7 +1298,11 @@ mod tests { for &v in &stepped[1..read.max(1)] { acc = m.bin(exit, Bin::Add, acc, v); } - let _ = m.call(exit, f, vec![acc, cur[0]]); + // What the program does with it (a store, say): the rest is live + // because this reads it. + let sink_ty = m.func_ty(void, vec![i32t, i32t]); + let sink = m.function("dx.op.sink", sink_ty, Some(Attr::NoUnwind), false); + let _ = m.call(exit, sink, vec![acc, cur[0]]); m.terminate(exit, Term::Ret); m } @@ -1136,7 +1319,7 @@ mod tests { fn live_by_passes(m: &Module) -> Vec { let mut live = vec![false; m.insts.len()]; for b in &m.blocks { - for &i in &b.body { + for &i in b.body.iter().filter(|&&i| m.rooted(i)) { live[i as usize] = true; } if let Some(Term::CondBr(V::Inst(c), ..)) = b.term { @@ -1188,6 +1371,11 @@ mod tests { m.set_phi(cyc_a, vec![(cyc_b, entry)]); m.set_phi(cyc_b, vec![(cyc_a, entry)]); let sum = m.bin(join, Bin::Add, read, b); + // An unread sum would be dropped too: a store keeps it. + let void = m.void(); + let sink_ty = m.func_ty(void, vec![i32t]); + let sink = m.function("dx.op.sink", sink_ty, Some(Attr::NoUnwind), false); + let _ = m.call(join, sink, vec![sum]); m.terminate(join, Term::Ret); let ids = |v: V| match v { V::Inst(i) => i as usize, @@ -1238,6 +1426,217 @@ mod tests { assert_eq!(build(false), build(true)); } + /// A module with `main`, `n` blocks and a call with effects to keep + /// values alive (what a store does). + fn module(n: usize) -> (Module, Vec, V) { + let mut m = Module::default(); + let (i32t, void) = (m.int(32), m.void()); + let ty = m.func_ty(void, vec![i32t]); + let sink = m.function("dx.op.sink", ty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let blocks = (0..n).map(|_| m.new_block()).collect(); + (m, blocks, sink) + } + + /// A branch on a constant takes its one edge: what only the other side + /// reaches is not written, and a phi loses that side's entry and keeps + /// the others. + #[test] + fn a_constant_branch_drops_its_other_side_and_that_side_s_phi_entry() { + let (mut m, b, sink) = module(6); + let [entry, p, q, a, dead, join] = b[..] else { unreachable!() }; + let i32t = m.int(32); + let (one, two, three) = (m.i32(1), m.i32(2), m.i32(3)); + let x = m.cmp(entry, pred::EQ, one, two); + m.terminate(entry, Term::CondBr(x, p, q)); + let t = m.bool(true); + m.terminate(p, Term::CondBr(t, a, dead)); + m.terminate(q, Term::Br(join)); + let _ = m.call(a, sink, vec![one]); + m.terminate(a, Term::Br(join)); + let _ = m.call(dead, sink, vec![two]); + m.terminate(dead, Term::Br(join)); + let phi = m.phi(join, i32t); + m.set_phi(phi, vec![(one, a), (two, dead), (three, q)]); + let _ = m.call(join, sink, vec![phi]); + m.terminate(join, Term::Ret); + let plan = m.plan(); + assert!(!plan.seen[dead] && !plan.layout.contains(&dead)); + assert!(!plan.edge(&m, dead, join), "the dead side's entry goes"); + assert!(plan.edge(&m, a, join) && plan.edge(&m, q, join), "the others stay"); + // `q` splits a critical edge (entry has two successors, the join + // two predecessors): it stays. + assert_eq!(plan.fold[q], None); + let _ = m.write(); + } + + /// A loop whose back edge is a constant branch's other edge is no loop: + /// the latch is not written and the header's phi keeps the entry's + /// value only. + #[test] + fn a_loop_whose_back_edge_is_never_taken() { + let (mut m, b, sink) = module(4); + let [entry, head, latch, exit] = b[..] else { unreachable!() }; + let i32t = m.int(32); + let (zero, one) = (m.i32(0), m.i32(1)); + m.terminate(entry, Term::Br(head)); + let i = m.phi(head, i32t); + let next = m.bin(head, Bin::Add, i, one); + let f = m.bool(false); + m.terminate(head, Term::CondBr(f, latch, exit)); + m.terminate(latch, Term::Br(head)); + m.set_phi(i, vec![(zero, entry), (next, latch)]); + let _ = m.call(exit, sink, vec![next]); + m.terminate(exit, Term::Ret); + let plan = m.plan(); + assert!(!plan.seen[latch]); + assert!(plan.edge(&m, entry, head) && !plan.edge(&m, latch, head)); + assert_eq!(plan.layout, [entry, head, exit]); + let _ = m.write(); + } + + /// An empty block that is a phi's predecessor: folded only where its + /// predecessor then reaches the phi's block once, the phi's entry then + /// coming from that predecessor. + #[test] + fn empty_blocks_before_a_phi_fold_only_where_the_entry_can_move() { + let (mut m, b, sink) = module(7); + let [entry, f, t, p2, f2, q2, t2] = b[..] else { unreachable!() }; + let i32t = m.int(32); + let (one, two) = (m.i32(1), m.i32(2)); + // entry branches to `t` both directly and through empty `f`, with + // different values: `f` stays. + let x = m.cmp(entry, pred::EQ, one, two); + m.terminate(entry, Term::CondBr(x, f, t)); + m.terminate(f, Term::Br(t)); + let phi = m.phi(t, i32t); + m.set_phi(phi, vec![(one, entry), (two, f)]); + let _ = m.call(t, sink, vec![phi]); + let y = m.cmp(t, pred::EQ, phi, two); + m.terminate(t, Term::CondBr(y, p2, q2)); + // `p2` reaches `t2` only through empty `f2`, which has one + // predecessor and splits no critical edge: folded, its entry now + // `p2`'s. + let _ = m.call(p2, sink, vec![one]); + m.terminate(p2, Term::Br(f2)); + m.terminate(f2, Term::Br(t2)); + let _ = m.call(q2, sink, vec![two]); + m.terminate(q2, Term::Br(t2)); + let phi2 = m.phi(t2, i32t); + m.set_phi(phi2, vec![(one, f2), (two, q2)]); + let _ = m.call(t2, sink, vec![phi2]); + m.terminate(t2, Term::Ret); + let plan = m.plan(); + assert_eq!(plan.fold[f], None); + assert_eq!(plan.fold[f2], Some((p2, t2))); + assert_eq!((plan.src(f2), plan.to(f2)), (p2, t2)); + assert!(plan.edge(&m, f2, t2) && plan.edge(&m, q2, t2)); + assert!(!plan.layout.contains(&f2)); + let _ = m.write(); + } + + /// A value only a dropped value reads is dropped too; operations with + /// effects (calls neither read-none nor read-only: stores, atomics, + /// discard, barriers, marks; stores and atomic instructions) never are. + #[test] + fn only_values_with_effects_or_readers_are_written() { + let (mut m, b, sink) = module(1); + let entry = b[0]; + let (i32t, void) = (m.int(32), m.void()); + let ty = m.func_ty(i32t, vec![i32t]); + let pure = m.function("dx.op.pure", ty, Some(Attr::ReadNone), false); + let reads = m.function("dx.op.reads", ty, Some(Attr::ReadOnly), false); + let barrier_ty = m.func_ty(void, vec![i32t]); + let barrier = m.function("dx.op.barrier", barrier_ty, Some(Attr::NoDuplicate), false); + let (one, two) = (m.i32(1), m.i32(2)); + let x = m.bin(entry, Bin::Add, one, two); + let unread = m.bin(entry, Bin::Mul, x, two); + let p = m.call(entry, pure, vec![one]); + let r = m.call(entry, reads, vec![one]); + let kept = m.bin(entry, Bin::Sub, two, one); + let s = m.call(entry, sink, vec![kept]); + let bar = m.call(entry, barrier, vec![one]); + let cell = m.global("cell", i32t, 3); + m.store(entry, cell, one); + let old = m.atomic(entry, Rmw::Add, cell, two); + m.terminate(entry, Term::Ret); + let live = m.live(); + let at = |v: V| match v { + V::Inst(i) => live[i as usize], + _ => unreachable!(), + }; + assert!(!at(x) && !at(unread) && !at(p) && !at(r), "unread pure values"); + assert!(at(kept) && at(s) && at(bar) && at(old), "effects and what they read"); + // The store has no value of its own: it is the instruction after the + // atomic's operand list, kept as its body entry. + let store = m.blocks[entry].body.iter().any(|&i| matches!(m.insts[i as usize].op, Op::Store(..)) && live[i as usize]); + assert!(store); + let _ = m.write(); + } + + /// A constant global only dropped values read is not declared; one a + /// written load reads is. + #[test] + fn constant_globals_nothing_reads_are_left_out() { + let (mut m, b, sink) = module(1); + let entry = b[0]; + let i32t = m.int(32); + let arr = m.array(2, i32t); + let (one, two) = (m.i32(1), m.i32(2)); + let init = m.aggregate(arr, &[one, two]); + let unread = m.constant_global("unread", init); + let read = m.constant_global("read", init); + let zero = m.i32(0); + let p = m.element(entry, unread, zero); + let _ = m.load(entry, p); + let q = m.element(entry, read, one); + let x = m.load(entry, q); + let _ = m.call(entry, sink, vec![x]); + m.terminate(entry, Term::Ret); + let plan = m.plan(); + let ((globals, n), _) = m.kept(&plan); + let (V::Global(u), V::Global(r)) = (unread, read) else { unreachable!() }; + assert_eq!((globals[u as usize], globals[r as usize], n), (u32::MAX, 0, 1)); + let _ = m.write(); + } + + /// What the shader flags declare is what written instructions use: a + /// heap handle or a 64-bit operation only a dropped value or a never + /// taken edge reaches counts for nothing. + #[test] + fn uses_count_only_what_is_written() { + let (mut m, b, sink) = module(3); + let [entry, live, dead] = b[..] else { unreachable!() }; + let (i32t, i64t, handle_t) = (m.int(32), m.int(64), m.int(8)); + let i1t = m.int(1); + let heap_ty = m.func_ty(handle_t, vec![i32t, i32t, i1t, i1t]); + let heap = m.function("dx.op.createHandleFromHeap", heap_ty, Some(Attr::ReadNone), false); + let (op, zero, no) = (m.i32(218), m.i32(0), m.bool(false)); + let yes = m.bool(true); + // An unread heap handle and 64-bit add where the program goes; a + // read sampler-heap handle behind a constant branch's other edge. + let _ = m.call(entry, heap, vec![op, zero, no, no]); + let five = m.int_const(i64t, 5); + let _ = m.bin(entry, Bin::Add, five, five); + m.terminate(entry, Term::CondBr(yes, live, dead)); + let one = m.i32(1); + let _ = m.call(live, sink, vec![one]); + m.terminate(live, Term::Ret); + let h = m.call(dead, heap, vec![op, zero, yes, no]); + let _ = m.call(dead, sink, vec![one]); + let _ = h; + m.terminate(dead, Term::Ret); + assert_eq!(m.uses(), Uses::default()); + // Read where the program goes: counted. + let h = m.call(live, heap, vec![op, zero, no, no]); + let wide = m.bin(live, Bin::Add, five, five); + let t = m.cast(live, Cast::Trunc, wide, i32t); + let _ = (m.call(live, sink, vec![t]), h); + let u = m.uses(); + assert!(u.int64 && !u.heap && !u.sampler_heap, "{u:?}"); + } + #[test] fn successors_of_each_terminator() { assert!(successors(None).is_empty()); @@ -1246,13 +1645,13 @@ mod tests { assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]); } - /// The written bytes are pinned to what the writer produced before the - /// worklist and the reused record buffers. + /// The written bytes are pinned (anew when the writer began to drop + /// unread values: the module's last call became one with effects). #[test] fn written_bytes_unchanged() { for ((regs, stages, read), len, hash) in [ - ((64, 64, 64), 38_916, 0x9586_730c_f953_4a45), - ((128, 256, 32), 295_952, 0x89e5_de2d_64f0_8785), + ((64, 64, 64), 38_956, 0xf0d5_9e83_b39d_a635), + ((128, 256, 32), 252_532, 0x5961_0d0b_12c3_4414), ] { let bytes = synthetic(regs, stages, read).write(); assert_eq!((bytes.len(), fnv(&bytes)), (len, hash), "{regs}x{stages}"); diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 69fda31a9e..65e61147ea 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -1483,17 +1483,19 @@ fn translated_compute_matches_pc() { } Err(e) => panic!("{name}: {e}"), }; - // Our root views follow the user data in root parameter order. + // Our root views follow the user data in root parameter order: the + // case's own, then the host's view-stride table (16-bit typed + // accesses read their view's format kind there). let mut roots = vec![(0, Root::Constants(user_data(&cs_c, &k)))]; let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); root_views.sort_unstable(); for (n, (slot, srv)) in root_views.into_iter().enumerate() { - assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); - let data = if srv { - root_srv.clone() + let data = if srv && slot == super::VIEW_STRIDES { + super::host::view_strides(&views) } else { - root_cbv.clone() + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + if srv { root_srv.clone() } else { root_cbv.clone() } }; roots.push((1 + n as u32, Root::View { srv, data })); } diff --git a/crates/victory-shader/src/emit/flow_tests.rs b/crates/victory-shader/src/emit/flow_tests.rs index 8945cdd1aa..73484c9bbd 100644 --- a/crates/victory-shader/src/emit/flow_tests.rs +++ b/crates/victory-shader/src/emit/flow_tests.rs @@ -252,6 +252,29 @@ const PS_CASES: &[(&str, &str)] = &[ return float4(ddx_fine(v), ddy_fine(v), v, 1); }"#, ), + // Derivatives and quad reads of values each pixel computes, on a + // triangle whose edge crosses quads: the neighbours outside it are + // helpers (`EDGE`). + ( + "derivatives and quad reads across a triangle edge", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float v = p.x * 3.0 + p.y * 5.0 + 1; + v = v * v; + return float4(ddx_fine(v), ddy_fine(v), QuadReadAcrossDiagonal(v), QuadReadLaneAt(v, 0)); + }"#, + ), + // The same with some neighbours discarded before the reads: helpers too. + ( + "discard, then derivatives and quad reads across a triangle edge", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float v = p.x * 3.0 + p.y * 5.0 + 1; + v = v * v; + if (((p.x * 7 + p.y * 3) & 5) == 5) discard; + return float4(ddx_fine(v), ddy_fine(v), QuadReadAcrossDiagonal(v), QuadReadLaneAt(v, 0)); + }"#, + ), ( "discard with depth and a second target", r#"struct O { float4 c : SV_Target0; float4 d : SV_Target1; float z : SV_Depth; }; @@ -268,6 +291,9 @@ const PS_CASES: &[(&str, &str)] = &[ ), ]; +/// Pixel cases named with this draw a triangle whose edge crosses quads. +const EDGE: &str = "triangle edge"; + /// Per-lane inputs: four dwords per lane from a fixed hash (low bits vary /// lane to lane; a few lanes hold larger values). fn lane_inputs(lanes: u32) -> Vec { @@ -441,17 +467,23 @@ fn run(pick: &dyn Fn(&str) -> bool) -> Vec { )); } } - // Pixel shapes. + // Pixel shapes: a triangle covering the target, or for cases named + // with `EDGE` one whose diagonal crosses quads. let vertices = [ -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // -1.0, 3.0, 0.5, 1.0, 0.0, -1.0, // 3.0, -1.0, 0.5, 1.0, 2.0, 1.0, ]; - let draw = |roots| Draw { + let half = [ + -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // + -1.0, 1.1, 0.5, 1.0, 0.0, -0.05, // + 1.1, -1.0, 0.5, 1.0, 1.05, 1.0, + ]; + let draw = |roots, edge: bool| Draw { roots, textures: &[], samplers: &[], - vertices: &vertices, + vertices: if edge { &half } else { &vertices }, stride: 24, size: (16, 16), mesh_groups: 0, @@ -481,10 +513,13 @@ fn run(pick: &dyn Fn(&str) -> bool) -> Vec { .draw( &root_t, &pso_t, - &draw(vec![ - (0, Root::Constants(console_user_data(&vs_c))), - (1, Root::Constants(console_user_data(&ps_c))), - ]), + &draw( + vec![ + (0, Root::Constants(console_user_data(&vs_c))), + (1, Root::Constants(console_user_data(&ps_c))), + ], + name.contains(EDGE), + ), ) .unwrap_or_else(|e| panic!("{name}: {label}: {e}")); let (vs_p, ps_p) = ( @@ -499,7 +534,7 @@ fn run(pick: &dyn Fn(&str) -> bool) -> Vec { .draw( &root_p, &pso_p, - &draw(vec![(0, Root::Constants(vec![0; 4]))]), + &draw(vec![(0, Root::Constants(vec![0; 4]))], name.contains(EDGE)), ) .unwrap(); let bad: Vec = (0..got.len()).filter(|&t| got[t] != want[t]).collect(); diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 57a30dbf19..f61510c7a8 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1263,6 +1263,9 @@ pub enum View<'a> { Uint2TextureUav(u32, u32), /// A typed RGBA16F buffer UAV of this many elements, zeroed. HalfUav(u32), + /// A typed buffer UAV in this format, of this many elements of this many + /// bytes, zeroed. + TypedUav(DXGI_FORMAT, u32, u32), /// A constant buffer of these dwords. Cbv(&'a [u32]), /// A buffer SRV over these dwords. @@ -1281,6 +1284,34 @@ pub enum View<'a> { NullBuffers, } +/// The host's view-stride table (`t`[`super::VIEW_STRIDES`]) for a view +/// heap of `views`, as `victory_gpu` fills it: per slot the element size of +/// a buffer view (4 for raw ones), with [`super::VIEW_INTEGER`] (and +/// [`super::VIEW_SIGNED`]) for typed views of integer formats; 0 elsewhere. +#[cfg(test)] +pub fn view_strides(views: &[View]) -> Vec { + let kind = |f: DXGI_FORMAT| match f { + DXGI_FORMAT_R32G32B32A32_UINT | DXGI_FORMAT_R16G16B16A16_UINT | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R10G10B10A2_UINT | DXGI_FORMAT_R8G8B8A8_UINT | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R8G8_UINT | DXGI_FORMAT_R16_UINT | DXGI_FORMAT_R8_UINT => super::VIEW_INTEGER, + DXGI_FORMAT_R32G32B32A32_SINT | DXGI_FORMAT_R16G16B16A16_SINT | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R8G8B8A8_SINT | DXGI_FORMAT_R16G16_SINT | DXGI_FORMAT_R32_SINT + | DXGI_FORMAT_R8G8_SINT | DXGI_FORMAT_R16_SINT | DXGI_FORMAT_R8_SINT => super::VIEW_INTEGER | super::VIEW_SIGNED, + _ => 0, + }; + views + .iter() + .map(|v| match *v { + View::Buffer { stride: Stride::Raw, .. } | View::RawUav(_) => 4, + View::Buffer { stride: Stride::Typed, .. } => 16, + View::Buffer { stride: Stride::Structured(n), .. } => n, + View::Buffer { stride: Stride::Format(f, n), .. } | View::TypedUav(f, _, n) => n | kind(f), + View::HalfUav(_) => 8, + _ => 0, + }) + .collect() +} + /// How [`View::Buffer`] is viewed. #[cfg(test)] #[derive(Clone, Copy)] @@ -1426,6 +1457,32 @@ impl Host { b.Unmap(0, None); Ok(b) }; + // Zeros a UAV made as a copy destination (`size`: a texture's, + // `n` its words per texel, else a buffer's dwords) and returns + // the upload buffer to keep. A new committed resource is not + // always zeroed: WARP hands out memory a freed buffer of ours held. + let zero = |r: &ID3D12Resource, size: Option<(u32, u32)>, n: u32| { + let zeros = match size { + Some((w, h)) => { + let pitch = (w * 4 * n).next_multiple_of(256); + let zeros = upload(&vec![0; (pitch * h / 4) as usize])?; + let from = footprint_as(&zeros, w, h, n); + list.CopyTextureRegion(&subresource(r), 0, 0, 0, &from, None); + zeros + } + None => { + let zeros = upload(&vec![0; n as usize])?; + list.CopyBufferRegion(r, 0, &zeros, 0, u64::from(n) * 4); + zeros + } + }; + list.ResourceBarrier(&[transition( + r, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + Ok::<_, String>(zeros) + }; let slots = match d.views.last() { Some(View::NullBuffers) => super::HEAP_VIEWS as usize, _ => d.views.len(), @@ -1567,7 +1624,7 @@ impl Host { dev.CreateShaderResourceView(&tex, None, at); keep.push(tex); } - View::RawUav(_) | View::HalfUav(_) => { + View::RawUav(_) | View::HalfUav(_) | View::TypedUav(..) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { View::HalfUav(e) => ( @@ -1576,6 +1633,9 @@ impl Host { e, D3D12_BUFFER_UAV_FLAG_NONE, ), + View::TypedUav(format, e, bytes) => { + ((e * bytes).div_ceil(4), format, e, D3D12_BUFFER_UAV_FLAG_NONE) + } View::RawUav(n) => { (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) } @@ -1585,7 +1645,7 @@ impl Host { let b = make( D3D12_HEAP_TYPE_DEFAULT, &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, )?; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: format, @@ -1599,6 +1659,7 @@ impl Host { }, }; dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + keep.push(zero(&b, None, n)?); let rb = make( D3D12_HEAP_TYPE_READBACK, &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), @@ -1610,9 +1671,10 @@ impl Host { let t = make( D3D12_HEAP_TYPE_DEFAULT, &texture(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_DEST, )?; dev.CreateUnorderedAccessView(&t, None, None, at); + keep.push(zero(&t, Some((w, h)), 4)?); let pitch = (w * 16).next_multiple_of(256); let rb = make( D3D12_HEAP_TYPE_READBACK, @@ -1629,9 +1691,10 @@ impl Host { let t = make( D3D12_HEAP_TYPE_DEFAULT, &texture_as(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, format), - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_DEST, )?; dev.CreateUnorderedAccessView(&t, None, None, at); + keep.push(zero(&t, Some((w, h)), words)?); let pitch = (w * 4 * words).next_multiple_of(256); let rb = make( D3D12_HEAP_TYPE_READBACK, @@ -1829,9 +1892,10 @@ impl Host { let b = make( D3D12_HEAP_TYPE_DEFAULT, &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, )?; list.SetComputeRootUnorderedAccessView(*param, b.GetGPUVirtualAddress()); + keep.push(zero(&b, None, n)?); let rb = make( D3D12_HEAP_TYPE_READBACK, &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), @@ -1844,7 +1908,6 @@ impl Host { let [x, y, z] = d.groups; list.Dispatch(x, y, z); for (r, size, n, rb) in &uavs { - // (Buffers were promoted from the common state by the dispatch.) list.ResourceBarrier(&[transition( r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7807ceece4..50dcd038f0 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -11,11 +11,11 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use super::UserData; use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; use super::container::SigElement; -use super::shader::{Shader, VIEW_STRIDES, flags}; +use super::shader::{Shader, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, flags}; use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Elsewhere, Export, Input, Interp, Io, Target}; -use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::ir::{Block, EXEC, Exit, Inst, Phi, Program, Reg, Value}; use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER_DATA}; use crate::structure::{Atom, Bool, LaneExit, Structured}; @@ -47,7 +47,8 @@ pub(crate) struct Lowered { pub memory: bool, /// Writes there (the written-pages bitmap). pub memory_writes: bool, - /// Reads buffer views' addresses from descriptors (the view addresses). + /// Reads buffer views' addresses or texture views' sizes from + /// descriptors (the view addresses). pub view_addresses: bool, /// Takes descriptors from the resource heap itself (root type 5, not /// a table), and whether as unordered access views. @@ -64,6 +65,9 @@ pub(crate) struct Lowered { /// The first word of every heap handle's properties. #[cfg(test)] pub heap_props: Vec, + /// Heap handles written. + #[cfg(test)] + pub heap_handles: u32, /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, @@ -179,6 +183,10 @@ fn half_shift(width: u32) -> u32 { if width == 16 { 0 } else { 15 - width } } +/// A descriptor load's address given by root parameters alone: root +/// parameter and byte offset. +type EntryAddress = (usize, u32); + struct Lower<'a> { s: Shader, x: &'a Parts<'a>, @@ -212,6 +220,14 @@ struct Lower<'a> { exports: HashMap, interps: HashMap, handles: HashMap<(usize, Site, u8, bool, u32), V>, + /// Handles made in the entry block for descriptors at addresses the + /// root parameters alone give (table and heap loads with no other + /// term), by base value, byte offset, dword, offset register, sampler + /// heap and properties ([`Lower::entry_address`]). + entry_handles: HashMap<(EntryAddress, u8, bool, u32), V>, + /// Handles of descriptors chosen by control flow, made in their join + /// block, by the choice (its `Debug` text), sampler heap and properties. + join_handles: HashMap<(String, bool, u32), V>, /// Blocks splitting the edge from one IR block to another. edges: HashMap<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -466,6 +482,40 @@ fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } +/// The scalar instruction defining an SSA value in this block and its operands. +fn scalar_def<'a, const N: usize>( + block: &'a Block, + value: Value, + op: &str, +) -> Option<(&'a Inst, [Operand; N])> { + let inst = block + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == value))?; + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + (inst.name() == op).then_some((inst, src.as_slice().try_into().ok()?)) +} + +fn sgpr_operand(inst: &Inst, operand: Operand) -> Option { + match operand { + Operand::Scalar { + code: code @ 0..=101, + dwords: 1, + } => inst.read(Reg::S(code)), + _ => None, + } +} + +fn scalar_constant(operand: Operand) -> Option { + match operand { + Operand::Const(code) => crate::resource::inline(code), + Operand::Literal(value) => Some(value), + _ => None, + } +} + /// The dwords an `s_load_dword*` reads. fn smem_dwords(name: &str) -> Option { match name.strip_prefix("s_load_dword")? { @@ -619,6 +669,8 @@ impl<'a> Lower<'a> { exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), handles: HashMap::new(), + entry_handles: HashMap::new(), + join_handles: HashMap::new(), edges: HashMap::new(), exported: vec![false; p.blocks.len()], rpo: vec![usize::MAX; p.blocks.len()], @@ -1341,6 +1393,8 @@ impl<'a> Lower<'a> { #[cfg(test)] heap_props: std::mem::take(&mut self.s.heap_props), #[cfg(test)] + heap_handles: self.s.m.written_calls("dx.op.createHandleFromHeap") as u32, + #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, #[cfg(test)] op_names: self.s.op_names.clone(), @@ -2898,6 +2952,16 @@ impl<'a> Lower<'a> { r } + /// Whether a quad-local read must reach helper lanes: in a pixel program + /// every quad a triangle edge crosses has some (the console's whole-quad + /// mode runs them; discarded pixels stay helpers too), and only quad + /// reads see them on the host (wave reads give 0 from them on AMD: wrong + /// derivatives of computed values along every triangle edge). + fn helpers_read(&self, quad: bool) -> bool { + quad && self.s.pixel + } + + /// `v_readfirstlane_b32`'s result `first` of `own` in a pixel shader: /// a helper lane takes its own value instead. /// @@ -2922,14 +2986,6 @@ impl<'a> Lower<'a> { self.s.m.select(c, helper, own, first) } - /// Whether a quad-local read must reach discarded lanes: after a pixel's - /// discard they are the host's helpers, which only quad reads see (wave - /// reads give 0 from them on AMD). - fn helpers_read(&self, quad: bool) -> bool { - quad && self.s.pixel && !self.x.st.discards.is_empty() - } - - fn read_lane(&mut self, x: V, lane: V) -> V { self.s.op( self.cur, @@ -4360,6 +4416,14 @@ impl<'a> Lower<'a> { /// The byte stride of the buffer view at heap index `index`, from the /// view-stride table (`t`[`VIEW_STRIDES`]). fn stride_at(&mut self, index: V) -> V { + let word = self.view_word(index); + let bits = self.s.m.i32(VIEW_STRIDE_BITS); + self.s.m.bin(self.cur, Bin::And, word, bits) + } + + /// Dword `index` of the view-stride table: the stride and the format + /// kind bits ([`VIEW_INTEGER`], [`VIEW_SIGNED`]). + fn view_word(&mut self, index: V) -> V { let c = self.cur; let four = self.s.m.i32(4); let at = self.s.m.bin(c, Bin::Mul, index, four); @@ -4367,6 +4431,22 @@ impl<'a> Lower<'a> { self.raw_dword(table, at) } + /// Whether the typed buffer view a handle names has an integer format, + /// and whether a signed one, from the view-stride table; `None` if the + /// handle's heap index is not known. + fn integer_view(&mut self, h: V) -> Option<(V, V)> { + let index = *self.s.view_index.get(&h)?; + let word = self.view_word(index); + let c = self.cur; + let zero = self.s.m.i32(0); + let [int, signed] = [VIEW_INTEGER, VIEW_SIGNED].map(|bit| { + let bit = self.s.m.i32(bit); + let x = self.s.m.bin(c, Bin::And, word, bit); + self.s.m.cmp(c, pred::NE, x, zero) + }); + Some((int, signed)) + } + /// Title memory at a raw GPU address (decision 0005: the unified-memory /// item). Every access to an address the program computes goes through /// here: scalar and global loads, stores and atomics, the BVH node @@ -4498,12 +4578,18 @@ impl<'a> Lower<'a> { /// A descriptor load from a table or heap whose dwords the program only /// reads as numbers: the base address of a buffer view (dwords 0 and 1, - /// as a pointer to title memory: the BVH's address in its SRV). They - /// come from the host's view addresses, `t1` in - /// [`super::shader::MEMORY_SPACE`]: two dwords per heap index. + /// as a pointer to title memory: the BVH's address in its SRV) or, for + /// a whole image descriptor (eight dwords), also the size fields of + /// dwords 1-3 (width, height, first and last level, type: size queries + /// of a texture the program never samples). They come from the host's + /// view addresses, `t1` in [`super::shader::MEMORY_SPACE`]: four dwords + /// per heap index. // shortcut: dword 1 holds the address bits only (stride and swizzle read - // 0); the other dwords stop the program when read; the table offset's - // computed part is taken as whole descriptors (32-byte multiples). + // 0) or a texture's width bits, dword 3 a texture's size fields (format, + // tiling and swizzle choice read 0 or the identity); dword 4 on and a + // buffer's dwords 2-3 (record count, format) stop the program when read; + // the table offset's computed part is taken as whole descriptors + // (32-byte multiples). fn view_addresses(&mut self, inst: &Inst, site: Site, code: u8, count: u32) -> Result<(), Why> { const OTHER: Why = "a descriptor read only as data"; let a = *self.scalar.get(&site).ok_or("a descriptor read only as data")?; @@ -4513,14 +4599,17 @@ impl<'a> Lower<'a> { ) { return Err("a descriptor read only as data"); } + // The compiler loads image descriptors whole, buffer ones as four + // dwords. + let known = if count == 8 && a.offset.is_multiple_of(32) { 4 } else { 2 }; let views = self.s.view_addresses_handle(); for k in 0..count { let word = (a.offset / 4 + k) % 8; - let val = if word < 2 { + let val = if word < known { let index = self.heap_index(site, k as u8, false)?; let c = self.cur; - let three = self.s.m.i32(3); - let at = self.s.m.bin(c, Bin::Shl, index, three); + let four = self.s.m.i32(4); + let at = self.s.m.bin(c, Bin::Shl, index, four); let w = self.s.m.i32(4 * word); let at = self.s.m.bin(c, Bin::Add, at, w); Val::I32(self.raw_dword(views, at)) @@ -4598,10 +4687,7 @@ impl<'a> Lower<'a> { /// typed loads do (channels past the format's read 0, 0, 0, 1). // shortcut: the descriptor's channel swizzle is taken as the identity // (it is for raw views and the descriptors code builds), elements of 4 - // bytes or more as dword-aligned. Norm formats divide, which the AMD - // driver does 1 ULP off the hardware's correctly rounded conversion for - // some values; correct it with an integer check if a title compares - // converted values exactly. + // bytes or more as dword-aligned. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result, Why> { let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; let c = self.cur; @@ -4664,10 +4750,15 @@ impl<'a> Lower<'a> { // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00. let x = match numeric { Numeric::Unorm => { - let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); let top = (1u64 << w) - 1; - let max = self.s.m.f32((top as f32).to_bits()); - let q = self.s.m.bin(c, Bin::SDiv, f, max); + let q = if w <= 16 { + let q = self.norm_quotient(field, w); + self.as_float(q) + } else { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + let max = self.s.m.f32((top as f32).to_bits()); + self.s.m.bin(c, Bin::SDiv, f, max) + }; let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits())); let at_top = self.s.m.cmp(c, pred::EQ, field, high); let q = self.s.m.select(c, at_top, one, q); @@ -4675,10 +4766,23 @@ impl<'a> Lower<'a> { } Numeric::Snorm => { let s = signed(self); - let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); let top = (1u32 << (w - 1)) - 1; - let max = self.s.m.f32((top as f32).to_bits()); - let q = self.s.m.bin(c, Bin::SDiv, f, max); + let q = if w <= 17 { + // The magnitude's quotient, signed (codes at and + // below -top are -1.0 below). + let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000)); + let neg = self.s.m.cmp(c, pred::SLT, s, zero); + let minus = self.s.m.bin(c, Bin::Sub, zero, s); + let m = self.s.m.select(c, neg, minus, s); + let q = self.norm_quotient(m, w - 1); + let sign = self.s.m.select(c, neg, sign, zero); + let q = self.s.m.bin(c, Bin::Or, q, sign); + self.as_float(q) + } else { + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + let max = self.s.m.f32((top as f32).to_bits()); + self.s.m.bin(c, Bin::SDiv, f, max) + }; // The lowest value is -1.0 too, as is the one above it. let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); let at_top = self.s.m.cmp(c, pred::SGE, s, high); @@ -4728,6 +4832,144 @@ impl<'a> Lower<'a> { Ok(out) } + /// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes + /// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for + /// a normalized code. The host's division is not exact (the RX 6700 XT + /// returns 8-bit codes one ulp high and some 16-bit codes one ulp low), + /// and titles truncate `x * d` back to the code (a material index in a + /// vertex colour's alpha), which a quotient one ulp low turns into the + /// code below. + /// + /// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K = + /// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1: + /// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d` + /// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when + /// its highest dropped bit is set, and the result is that integer (at + /// most 2^24, so its conversion is exact on any host) scaled by a power + /// of two; `Q` itself when it fits, the quotient's further bits then + /// lying below half an ulp. That holds for every code of every width but + /// 11 and 12 (checked for all codes of widths 2 to 16), which take + /// [`Self::exact_norm`]. The host's conversion of a larger integer is + /// not relied on: WARP rounds those above 2^31 otherwise. + fn norm_quotient(&mut self, a: V, w: u32) -> V { + if matches!(w, 11 | 12) { + return self.exact_norm(a, w); + } + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, kv) = (k(self, 1), k(self, kk)); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + if r != 1 { + let (rv, dv) = (k(self, r), k(self, d)); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + } + // The bits to drop (1 to 8) from the exponent of `q >> 8`, which + // converts exactly (fewer than 25 bits); none when `q` fits. + let k8 = k(self, 8); + let top = self.s.m.bin(c, Bin::LShr, q, k8); + let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32); + let top = self.as_int(top); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::LShr, top, k23); + let bias = k(self, 127 + 15); + let shift = self.s.m.bin(c, Bin::Sub, e, bias); + let (zero, b24) = (k(self, 0), k(self, 1 << 24)); + let fits = self.s.m.cmp(c, pred::IULT, q, b24); + let shift = self.s.m.select(c, fits, zero, shift); + // Rounded up when the highest dropped bit is set: `a / d` is never + // exact, so a dropped half is more than half, never a tie. + let up = self.s.m.bin(c, Bin::Shl, q, one); + let up = self.s.m.bin(c, Bin::LShr, up, shift); + let up = self.s.m.bin(c, Bin::And, up, one); + let m = self.s.m.bin(c, Bin::LShr, q, shift); + let m = self.s.m.bin(c, Bin::Add, m, up); + // At most 2^24: exact as a float, and so its scale by 2^(shift - 32). + let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32); + let b95 = k(self, 127 - 32); + let scale = self.s.m.bin(c, Bin::Add, shift, b95); + let scale = self.s.m.bin(c, Bin::Shl, scale, k23); + let scale = self.as_float(scale); + let f = self.s.m.bin(c, Bin::Mul, f, scale); + self.as_int(f) + } + + /// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q` + /// as there, 8 more bits when that leaves fewer than 25 (codes of wide + /// formats near 0), then rounded to 24 bits to nearest even with the + /// remainder as sticky bit, and assembled as float bits. + fn exact_norm(&mut self, a: V, w: u32) -> V { + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8)); + let kv = k(self, kk); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + let mut rem = a; + if r != 1 { + let rv = k(self, r); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + rem = self.s.m.bin(c, Bin::URem, t, dv); + } + // The exponent's bias less the 32 (or 40) fraction bits of `q`; the + // shift below is added. + let mut bias = k(self, 127 + 23 - 32); + if kk < 1 << 24 { + // Fewer than 25 bits for the smallest codes: 8 more. + let t = self.s.m.bin(c, Bin::Shl, rem, k8); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + let rest = self.s.m.bin(c, Bin::URem, t, dv); + let wide = self.s.m.bin(c, Bin::Shl, q, k8); + let wide = self.s.m.bin(c, Bin::Or, wide, more); + let limit = k(self, 1 << 24); + let small = self.s.m.cmp(c, pred::IULT, q, limit); + q = self.s.m.select(c, small, wide, q); + rem = self.s.m.select(c, small, rest, rem); + let b40 = k(self, 127 + 23 - 40); + bias = self.s.m.select(c, small, b40, bias); + } + // Bits to drop: the bit length less 24, 1 to 8. + let mut shift = one; + for bit in 25..32 { + let at = k(self, 1 << bit); + let ge = self.s.m.cmp(c, pred::IUGE, q, at); + let add = self.s.m.select(c, ge, one, zero); + shift = self.s.m.bin(c, Bin::Add, shift, add); + } + let mant = self.s.m.bin(c, Bin::LShr, q, shift); + let below = self.s.m.bin(c, Bin::Sub, shift, one); + let half = self.s.m.bin(c, Bin::LShr, q, below); + let half = self.s.m.bin(c, Bin::And, half, one); + let low = self.s.m.bin(c, Bin::Shl, one, below); + let low = self.s.m.bin(c, Bin::Sub, low, one); + let low = self.s.m.bin(c, Bin::And, q, low); + let rest = self.s.m.bin(c, Bin::Or, low, rem); + let sticky = self.s.m.cmp(c, pred::NE, rest, zero); + let odd = self.s.m.bin(c, Bin::And, mant, one); + let tie = self.s.m.select(c, sticky, one, odd); + let up = self.s.m.bin(c, Bin::And, half, tie); + let mant = self.s.m.bin(c, Bin::Add, mant, up); + // Rounding up to 2^24 moves to the next exponent. + let k24 = k(self, 24); + let carry = self.s.m.bin(c, Bin::LShr, mant, k24); + let mant = self.s.m.bin(c, Bin::LShr, mant, carry); + let e = self.s.m.bin(c, Bin::Add, bias, shift); + let e = self.s.m.bin(c, Bin::Add, e, carry); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::Shl, e, k23); + let fraction = k(self, 0x7F_FFFF); + let m = self.s.m.bin(c, Bin::And, mant, fraction); + let bits = self.s.m.bin(c, Bin::Or, e, m); + let is_zero = self.s.m.cmp(c, pred::EQ, a, zero); + self.s.m.select(c, is_zero, zero, bits) + } + /// Channels of buffer format `format`, as [`Self::format_load`] gives /// them, as d16 data: 16 bits each, two per dword, low half first (an /// odd last high half 0). Integer formats keep their low 16 bits; the @@ -4816,7 +5058,9 @@ impl<'a> Lower<'a> { &[table, at, iu, mask, four], ); let x = self.s.m.extract(c, r, 0); - Ok(self.as_int(x)) + let word = self.as_int(x); + let bits = self.s.m.i32(VIEW_STRIDE_BITS); + Ok(self.s.m.bin(c, Bin::And, word, bits)) } /// The used-resource entry a descriptor loaded from a table falls in. @@ -4859,8 +5103,22 @@ impl<'a> Lower<'a> { .max_by_key(|u| u.table_offset_dwords) } - /// A handle for the descriptor `src` read at `site`. - fn handle( + /// A handle for the descriptor `src` read at `site`; the heap index of + /// a texture shader view the program takes from the heap itself is noted + /// for the instruction's read mark (handles are made once per block, + /// often before the instruction). A view read through a table needs + /// none: the host makes the slot for the draw. + fn handle(&mut self, site: Site, src: &Source, sampler: bool, props: (u32, u32)) -> Result { + let h = self.handle_made(site, src, sampler, props)?; + if let Some(&index) = self.s.texture_index.get(&h) + && self.is_heap_direct(src) + { + self.s.texture_reads.push(index); + } + Ok(h) + } + + fn handle_made( &mut self, site: Site, src: &Source, @@ -4880,6 +5138,25 @@ impl<'a> Lower<'a> { self.heap[1] |= props.0 & 0x1000 != 0; } match src { + Source::Loaded { load, first } + if let Some(address) = self.entry_address(*load) => + { + // The same descriptor wherever it is loaded: the console + // compiler reloads one before every use rather than keep it + // (ActivateRays: 2,399 loads of one), and one handle made in + // the entry block serves them all. + let key = (address, *first, sampler, props.0); + if let Some(&h) = self.entry_handles.get(&key) { + return Ok(h); + } + let here = std::mem::replace(&mut self.cur, self.s.entry); + let index = self.entry_heap_index(address, *first, sampler); + let index = self.buffer_guard(src, index, sampler, props); + let h = self.s.heap_handle(self.cur, index, sampler, false, props); + self.cur = here; + self.entry_handles.insert(key, h); + Ok(h) + } Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props.0); if let Some(&h) = self.handles.get(&key) { @@ -4986,29 +5263,25 @@ impl<'a> Lower<'a> { self.s.sampler_choices.push((ha, hb, phi)); Ok(ha) } - Source::Phi { block, args } => { - // Each predecessor computes its heap index at its end; the - // join picks one with a phi. + Source::Phi { block, .. } => { + // One handle at the join for every access the choice reaches + // (each is in a block the join dominates). let _ = site; - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); + let key = (format!("{src:?}"), sampler, props.0); + if let Some(&h) = self.join_handles.get(&key) { + return Ok(h); } let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); - let index = self.buffer_guard(src, phi, sampler, props); - Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + let here = std::mem::replace(&mut self.cur, join); + let index = self.uniform_heap_index(src, sampler); + let h = index.map(|index| { + let index = self.buffer_guard(src, index, sampler, props); + self.s.heap_handle(self.cur, index, sampler, false, props) + }); + self.cur = here; + let h = h?; + self.join_handles.insert(key, h); + Ok(h) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -5091,6 +5364,66 @@ impl<'a> Lower<'a> { }) } + /// The address of the descriptor load at `load` when root parameters + /// alone give it (a table or a heap, at a fixed offset: resource + /// tracking found no other term), and not per lane. + fn entry_address(&self, load: Site) -> Option { + let a = self.scalar.get(&load)?; + let fixed = a.dynamic.is_none() && !self.x.res.waterfall.loads.contains(&load); + let root = self.x.native.layout.get(a.param)?.root; + let heap = matches!(root, RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap); + (fixed && heap).then_some((a.param, a.offset)) + } + + /// [`Lower::heap_index`] of a descriptor at a fixed address + /// ([`Lower::entry_address`]), in the entry block. + fn entry_heap_index(&mut self, (param, offset): EntryAddress, first: u8, sampler: bool) -> V { + let entry = self.s.entry; + let base = match self.x.native.layout[param].root { + RootType::Table => self.user_dword(param, 0), + _ => self.s.m.i32(0), + }; + let k = self.s.m.i32(offset.wrapping_add(4 * u32::from(first))); + let addr = self.s.m.bin(entry, Bin::Add, base, k); + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + self.s.m.bin(entry, Bin::LShr, addr, shift) + } + + /// The heap index of a descriptor every lane shares, computed in the + /// current block. One chosen by control flow is a phi at its join of the + /// index each predecessor computes at its end; an edge may bring another + /// join's (nested if/else). + fn uniform_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Phi { block, args } => { + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or("a descriptor chosen by control flow")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + // No lane comes this way (`resource` gave it another + // edge's source): any index will do. + if self.never_taken(q, *block) { + incoming.push((self.s.m.i32(0), at)); + continue; + } + let here = std::mem::replace(&mut self.cur, at); + let index = self.uniform_heap_index(arg, sampler); + self.cur = here; + incoming.push((index?, at)); + } + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + _ => Err("a descriptor chosen by control flow"), + } + } + /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -5260,7 +5593,12 @@ impl<'a> Lower<'a> { } return r; } - let mut guard = self.guard(b, i)?; + // A scalar result (`v_readlane`, `v_readfirstlane`) is written + // whatever EXEC holds. + let mut guard = match v.dst { + Some(Operand::Scalar { .. }) => None, + _ => self.guard(b, i)?, + }; if let Some(d) = v.dpp { let (x, enable) = self.dpp(inst, d)?; guard = match (guard, enable) { @@ -7600,11 +7938,56 @@ impl<'a> Lower<'a> { all } + /// Whether every lane enters IR block `b` along the edge the console's + /// wave takes, so that an SGPR joined there holds what that edge + /// brought: every branch into it is uniform (SCC values). The wave runs + /// one path; a per-lane branch into the join (an EXEC skip, a loop's + /// per-lane exit) is where lanes would take edges the wave did not, and + /// the console compiler's if/else always skips into its join that way. + /// Lanes that left EXEC inside a uniform loop (the BVH walks) take no + /// edge into its header; the others take the wave's. + fn uniform_join(&self, b: usize) -> bool { + let st = self.x.st; + let preds = &self.x.p.blocks[b].preds; + preds.iter().filter(|&&q| self.block[q].is_some()).all(|&q| match st.exits[q] { + LaneExit::Branch { when, taken, not_taken } if taken != not_taken => { + st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) + } + _ => true, + }) + } + /// Whether no lane goes from IR block `q` to `b`. fn never_taken(&self, q: usize, b: usize) -> bool { !self.x.st.bools.meet(&self.lane_edge(q, b)) } + /// Whether, at a per-lane join `b` of a lane mask whose register holds + /// data along edge `n`, some edge brings a mask and no lane taking edge + /// `n` is in any of them (a compare inside a region those lanes skip). + /// The console wave runs one path: on a mask edge, the lanes of edge `n` + /// read their bit of that mask, 0. The compiler merges no value for them, + /// so it holds none for them either where the whole wave skips (the data + /// there is a reused register): 0 is theirs. + fn no_mask_lane_on_edge(&self, b: usize, args: &[Value], n: usize) -> bool { + let st = self.x.st; + let preds = &self.x.p.blocks[b].preds; + let on_n = self.lane_edge(preds[n], b); + let mut some = false; + for (k, arg) in args.iter().enumerate() { + let Some(&m) = st.masks.get(arg).filter(|_| k != n) else { + continue; + }; + some = true; + let mut lanes = on_n.clone(); + lanes.push((m, true)); + if st.bools.meet(&lanes) { + return false; + } + } + some + } + /// Whether IR block `b` can reach itself. fn on_cycle(&self, b: usize) -> bool { let blocks = &self.x.p.blocks; @@ -7661,7 +8044,48 @@ impl<'a> Lower<'a> { .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[f]) } + /// An image instruction, its reads of texture views marked (module + /// notes, "Read marks") after it. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + self.s.texture_reads.clear(); + let lowered = self.image_op(inst, b, i); + for index in std::mem::take(&mut self.s.texture_reads) { + if lowered.is_ok() { + self.mark_view_read(index); + } + } + lowered + } + + /// Sets the read mark of resource-heap index `index` (module notes, + /// "Read marks") where it is still clear. Nothing without + /// [`Parts::view_marks`]. + fn mark_view_read(&mut self, index: V) { + if !self.x.view_marks { + return; + } + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let bitmap = self.s.view_writes_handle(); + let c = self.cur; + let (base, k5, k2, k31, one, zero) = + (k(self, super::VIEW_READS), k(self, 5), k(self, 2), k(self, 31), k(self, 1), k(self, 0)); + let n = self.s.m.bin(c, Bin::Add, index, base); + let word = self.s.m.bin(c, Bin::LShr, n, k5); + let word = self.s.m.bin(c, Bin::Shl, word, k2); + let bit = self.s.m.bin(c, Bin::And, n, k31); + let bit = self.s.m.bin(c, Bin::Shl, one, bit); + // Most reads find their slot marked: a load, not an atomic. + let old = self.raw_dword(bitmap, word); + let set = self.s.m.bin(c, Bin::And, old, bit); + let clear = self.s.m.cmp(c, pred::EQ, set, zero); + let at = self.begin_guarded(Some(clear)); + let iu = self.s.m.undef(self.s.t.i32); + // Operation 2 is OR. + self.s.op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, self.s.t.i32, 78, &[bitmap, k2, word, iu, iu, bit]); + self.end_guarded(at, &[]); + } + + fn image_op(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { let Fields::Image { data, addr, @@ -8937,9 +9361,19 @@ impl<'a> Lower<'a> { let regs = if d16 { count.div_ceil(2) } else { count }; let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; + let typed_h = if typed { + Some(self.handle(site, src, false, (10 | u, 0x409))?) + } else { + None + }; if d16 { - // shortcut: d16 data is taken as f16 (integer formats would - // keep 16 bits), widened for the 32-bit float store. + // d16 data is f16 for float and normalized formats, widened + // for the 32-bit float store; for integer formats (the view's + // kind, from the view-stride table) the 16-bit integer, zero- + // or sign-extended (stored through the float-typed handle as + // loads read: see there). + let integer = typed_h.and_then(|h| self.integer_view(h)); + let c = self.cur; let mut wide = Vec::new(); for k in 0..count { let mut x = vals[(k / 2) as usize]; @@ -8951,7 +9385,16 @@ impl<'a> Lower<'a> { let f = self .s .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); - wide.push(self.as_int(f)); + let mut w = self.as_int(f); + if let Some((int, signed)) = integer { + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let zero_ext = self.s.m.bin(c, Bin::And, x, low); + let up = self.s.m.bin(c, Bin::Shl, x, k16); + let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16); + let n = self.s.m.select(c, signed, sign_ext, zero_ext); + w = self.s.m.select(c, int, n, w); + } + wide.push(w); } vals = wide; } @@ -8965,7 +9408,7 @@ impl<'a> Lower<'a> { if count != 4 || *offen || *offset != 0 { return Err("a typed buffer store of some channels or at an offset"); } - let h = self.handle(site, src, false, (10 | u, 0x409))?; + let h = typed_h.ok_or("a typed buffer store")?; let element = index.unwrap_or(self.s.m.i32(0)); args.push(h); args.extend([element, iu]); @@ -9070,6 +9513,7 @@ impl<'a> Lower<'a> { self.write(inst, Reg::V(reg), x, guard); return Ok(()); } + let mut typed_h = None; let r = if typed { if *offen || matches!(off, V::Inst(_)) || *offset != 0 { return Err("a typed buffer load at an offset"); @@ -9078,6 +9522,7 @@ impl<'a> Lower<'a> { self.s.flags |= flags::TYPED_UAV_LOADS; } let h = self.handle(site, src, false, (10 | u, 0x409))?; + typed_h = Some(h); let index = index.unwrap_or(self.s.m.i32(0)); self.s.op( c, @@ -9126,16 +9571,31 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; if d16 { - // Two f16 channels per VGPR (an odd last high half 0). + // Two 16-bit channels per VGPR (an odd last high half 0): f16 for + // float and normalized formats; for integer formats (the view's + // kind, from the view-stride table) the integer's low 16 bits. + // shortcut: an integer view is read and written through the + // float-typed handle, so its channels' bits travel as the driver + // passes a mismatched component type (unchanged on the RX 6700 + // XT and WARP, `stride_tests`); an integer-typed second handle + // for the slot would not rely on it. + let integer = typed_h.and_then(|h| self.integer_view(h)); + let c = self.cur; let k16 = self.s.m.i32(16); let i32t = self.s.t.i32; for k in 0..count.div_ceil(2) { let mut x = None; for ch in (2 * k..(2 * k + 2).min(count)).rev() { let f = self.s.m.extract(c, r, ch); - let h = self + let mut h = self .s .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + if let Some((int, _)) = integer { + let bits = self.as_int(f); + let low = self.s.m.i32(0xFFFF); + let low = self.s.m.bin(c, Bin::And, bits, low); + h = self.s.m.select(c, int, low, h); + } x = Some(match x { Some(hi) => { let hi = self.s.m.bin(c, Bin::Shl, hi, k16); @@ -9920,6 +10380,171 @@ impl<'a> Lower<'a> { live } + /// An unguarded indexed write replaces the incoming value before a + /// consumer can observe it, either on this edge or in a counted loop. + fn overwritten_movreld_edge(&self, b: usize, phi: &Phi, edge: usize) -> Option<()> { + let Reg::V(reg) = phi.reg else { return None }; + let p = self.x.p; + let block = &p.blocks[b]; + if self.sections.contains_key(&b) + || self.sections.contains_key(&block.preds[edge]) + || p.blocks + .iter() + .flat_map(|bb| &bb.phis) + .any(|ph| ph.args.contains(&phi.value)) + { + return None; + } + let mut uses = p.blocks.iter().enumerate().flat_map(|(bb, block)| { + block.insts.iter().enumerate().filter_map(move |(i, inst)| { + inst.reads + .iter() + .any(|r| r.1 == phi.value) + .then_some((bb, i, inst)) + }) + }); + let (bb, i, mov) = uses.next()?; + if uses.next().is_some() + || bb != b + || self.x.st.guards[b][i].is_some() + || mov.name() != "v_movreld_b32" + || mov.read(phi.reg) != Some(phi.value) + { + return None; + } + let Fields::Valu(v) = &mov.fields else { + return None; + }; + let ( + Some(Operand::Vector { + reg: base, + dwords: 1, + }), + [ + Operand::Vector { + reg: src, + dwords: 1, + }, + ], + ) = (v.dst, v.src.as_slice()) + else { + return None; + }; + if v.dpp.is_some() + || v.sdwa.is_some() + || mov.read(Reg::V(*src))? == phi.value + || mov.write(phi.reg).is_none() + { + return None; + } + let index = u32::from(reg.checked_sub(base)?); + // Follow M0 to a copy of a scalar phi in this block, then the + // constant written on the corresponding predecessor. + let (copy, [src]) = scalar_def(block, mov.read(Reg::S(crate::ir::M0))?, "s_mov_b32")?; + let scalar = sgpr_operand(copy, src)?; + let index_phi = block.phis.iter().find(|ph| ph.value == scalar)?; + let (_, [initial]) = scalar_def( + &p.blocks[block.preds[edge]], + index_phi.args[edge], + "s_mov_b32", + )?; + let known = scalar_constant(initial)?; + if index == known { + return Some(()); + } + if index < known { + return None; // Reaching this slot would require the index to wrap. + } + self.counted_movreld_index(b, edge, phi, index_phi, mov, index) + } + + /// An unguarded move fills one more register on every iteration. + /// Values from before the loop can only survive in slots the index skips. + fn counted_movreld_index( + &self, + b: usize, + edge: usize, + phi: &Phi, + indices: &Phi, + mov: &Inst, + slot: u32, + ) -> Option<()> { + let p = self.x.p; + let st = self.x.st; + let block = &p.blocks[b]; + let LaneExit::Branch { + when, + taken: latch, + not_taken: exit, + } = st.exits[b] + else { + return None; + }; + let back = block.preds.iter().position(|&q| q == latch)?; + if block.preds.len() != 2 + || back == edge + || b == latch + || b == exit + || exit == latch + || self.sections.contains_key(&latch) + || st.exits[latch] != LaneExit::Jump(b) + || p.blocks[latch].preds != [b] + || p.blocks[exit].preds != [b] + || st.exits[exit] != LaneExit::End + || self.rpo[b] >= self.rpo[latch] + || self.rpo[block.preds[edge]] >= self.rpo[b] + { + return None; + } + // The indexed result may only go around the loop as its own old + // value or be consumed in the normal exit block. + let result = mov.write(phi.reg)?; + if phi.args[back] != result { + return None; + } + for (bb, block) in p.blocks.iter().enumerate() { + if bb != exit + && block + .insts + .iter() + .any(|inst| inst.reads.iter().any(|r| r.1 == result)) + { + return None; + } + if block.phis.iter().any(|other| { + other + .args + .iter() + .enumerate() + .any(|(n, &arg)| arg == result && (other.value != phi.value || n != back)) + }) { + return None; + } + } + // Follow the latch copy to the unit increment, then require that + // this very increment is compared for equality to the exit bound. + let (copy, [src]) = scalar_def(&p.blocks[latch], indices.args[back], "s_mov_b32")?; + let next = sgpr_operand(copy, src)?; + let (increment, [from, step]) = scalar_def(block, next, "s_add_i32")?; + if sgpr_operand(increment, from)? != indices.value || scalar_constant(step)? != 1 { + return None; + } + let (Atom::Uniform(scc), Bool::TRUE, Bool::FALSE) = st.bools.node(when)? else { + return None; + }; + let branch = block.insts.last()?; + if branch.name() != "s_cbranch_scc0" || branch.read(Reg::Scc) != Some(scc) { + return None; + } + let (cmp, [tested, bound]) = scalar_def(block, scc, "s_cmp_eq_u32")?; + if sgpr_operand(cmp, tested)? != next { + return None; + } + let limit = scalar_constant(bound)?; + // The initial index is below this slot. The loop must pass it before exit. + (slot < limit).then_some(()) + } + fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; let live = self.live_edges(); @@ -9945,9 +10570,27 @@ impl<'a> Lower<'a> { self.s.m.i32(0) } } + // An input an unguarded counted `v_movreld` loop overwrites + // before anything reads it (PR #457). + (Some(Val::Missing("barycentrics read directly")), false) + if read && self.overwritten_movreld_edge(b, phi, n).is_some() => + { + self.s.m.undef(self.s.t.i32) + } (Some(Val::Bit(_)), false) if read => { return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); } + // A lane mask joined with data at a join every lane + // enters along one edge: the register holds the mask's + // number there (console lanes, so exact). + _ if read + && !bit + && self.mask_data == MaskData::Console + && (self.x.st.masks.contains_key(&arg) || self.x.st.highs.contains_key(&arg)) + && self.uniform_join(b) => + { + self.mask_dword(arg).map_err(|w| Stop::Retry(phi.value, w))? + } (Some(Val::Missing(why)), _) if read => { return Err(Stop::Retry(phi.value, why)); } @@ -9971,11 +10614,20 @@ impl<'a> Lower<'a> { for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); - let m = - *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| { - unsupported(offset, "a lane-mask join of an untracked mask") - })?; - let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; + let arg = phi.args[n]; + const UNTRACKED: Why = "a lane-mask join of an untracked mask"; + // Data joined with masks where the wave takes one edge (the BVH + // walks pop masks from memory): with console lanes the lane's + // own bit of the number, as `Atom::Opaque`. + let number = self.console_lanes && !self.x.native.wave64 && self.uniform_join(b); + let x = match (self.x.st.masks.get(&arg), self.vals.get(&arg)) { + (Some(&m), _) => self.boolean(m, qb).map_err(|w| unsupported(offset, w))?, + (None, Some(&Val::I32(word))) if number => self.lane_bit(qb, word, None), + (None, _) if !self.uniform_join(b) && self.no_mask_lane_on_edge(b, &phi.args, n) => { + self.s.m.bool(false) + } + (None, _) => return Err(unsupported(offset, UNTRACKED)), + }; incoming.push((x, qb)); } self.s.m.set_phi(v, incoming); @@ -10736,6 +11388,186 @@ mod tests { } } + #[test] + fn an_address_half_set_where_only_lanes_that_never_run_skip_is_known() { + // As `indirect_light_probes:CS_Alpha_Schedule` after its texture: a + // table address whose high half (s25 = 0) is set inside the region + // that only a skip no lane takes bypasses; the skip edge would bring + // the stale input s25. + let words = [ + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo + 0xBE98_0300, // s_mov_b32 s24, s0 + 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 + 0xBF88_0001, // s_cbranch_execz -> join + 0xBE99_0380, // s_mov_b32 s25, 0 + 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 + 0xF408_0A0C, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[24:25], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0)]; + lower_with(&words, layout, used).expect("the high half is 0 wherever a lane runs"); + } + + #[test] + fn a_descriptor_skipped_only_by_lanes_that_never_run_needs_no_source() { + // As `indirect_light_probes:CS_Alpha_Schedule`: the texture is + // loaded under the lanes that ran before `s_wqm`, skipped when there + // are none, and sampled with the helper lanes after the join. With + // every lane running from the start nothing takes the skip, so the + // registers it would bring (no descriptor) are never read. + let words = [ + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 + 0xBF88_0002, // s_cbranch_execz -> join + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E04_02F0, // v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0)]; + let l = lower_with(&words, layout, used).unwrap(); + assert_eq!(l.nonuniform_handles, 0); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + + #[test] + fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1: entry 0 if s1 is 0, else + // entry 1 if it is 1, else entry 0 again, the inner if/else joined + // before the outer one. The join's edges are a load and a join. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0003, // s_cbranch_scc0 -> 0x38 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF82_0008, // s_branch -> 0x58 + 0xBF06_8101, // 0x38: s_cmp_eq_u32 s1, 1 + 0xBF84_0003, // s_cbranch_scc0 -> 0x4c + 0xF40C_0302, + 0xFA00_0020, // s_load_dwordx8 s[12:19], s[4:5], 0x20 + 0xBF82_0002, // s_branch -> 0x54 + 0xF40C_0302, + 0xFA00_0000, // 0x4c: s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBE86_0301, // 0x54: s_mov_b32 s6, s1 + 0x7E04_02F0, // 0x58: v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle from the joins' heap index, the same in all lanes. + assert_eq!(l.nonuniform_handles, 0); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + + #[test] + fn descriptors_reloaded_from_a_root_table_share_one_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1. Entry 0 is loaded and sampled + // in a branch, then loaded again and sampled after it (the console + // compiler reloads a descriptor before each use rather than keep it). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E04_02F0, // v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0005, // s_cbranch_scc0 -> the reload + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 (again) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle made in the entry block for both loads, and the + // UAV's. + assert_eq!(l.heap_handles, 2); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } + } + #[test] fn scalar_bit_tests_lower() { // Each tests one bit of a constant into SCC and branches on it (only @@ -10829,6 +11661,59 @@ mod tests { assert_eq!(refusal(&words), refusal(&direct)); } + #[test] + fn a_mask_joined_with_data_needs_a_uniform_join() { + // s6: lanes below 24, then shifted (data) on each back edge; read + // after the loop. Lanes leaving the loop at different iterations + // (per lane) see different numbers than the console's register: + // refused. The uniform loop is `synthetic_tests:: + // a_mask_joined_with_data_at_a_uniform_loop_is_its_number`. + let mut words = [ + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x8706_7E6A, // s_and_b32 s6, vcc_lo, exec_lo + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x9006_8406, // header: s_lshr_b32 s6, s6, 4 + 0x8007_8107, // s_add_u32 s7, s7, 1 + 0x7D88_0007, // v_cmp_gt_u32 vcc_lo, s7, v0 + 0x8A7E_6A7E, // s_andn2_b32 exec_lo, exec_lo, vcc_lo + 0xBF89_FFFB, // s_cbranch_execnz header + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let Err(crate::ShaderError::Unsupported { what, .. }) = lowers(&words, 1 << 7) else { + panic!("a per-lane loop's mask join translated"); + }; + assert!(what.contains("lane mask"), "{what}"); + // Leaving on a uniform condition instead: the mask's number. + words[5] = 0xBF0A_8207; // s_cmp_lt_u32 s7, 2 + words[6] = 0xBF80_0000; // s_nop 0 + words[7] = 0xBF85_FFFB; // s_cbranch_scc1 header + lowers(&words, 1 << 7).expect("a uniform loop's mask join"); + } + + #[test] + fn a_scalar_result_needs_no_exec() { + // s6 is 0 where every lane skips and the saved EXEC where some run: + // no lane mask at the per-lane join. EXEC taken from it guards only + // a `v_readlane` (written whatever EXEC holds) before it is restored + // (`CS_IrradianceCache_Shade`). + let words = [ + 0xBE86_0380, // s_mov_b32 s6, 0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE84_3C6A, // s_and_saveexec_b32 s4, vcc_lo + 0xBF88_0001, // s_cbranch_execz +1 + 0xBE86_0304, // s_mov_b32 s6, s4 + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD760_0002, // v_readlane_b32 s2, v0, 3 + 0x0001_0700, + 0xBEFE_0304, // s_mov_b32 exec_lo, s4 + S_ENDPGM, + ]; + lowers(&words, 1 << 7).expect("a lane read under an EXEC with no mask"); + } + #[test] fn a_missing_value_on_a_path_no_lane_takes_is_dead() { let refusal = |code: &[u32]| match lowers(code, 1 << 7) { diff --git a/crates/victory-shader/src/emit/memory_tests.rs b/crates/victory-shader/src/emit/memory_tests.rs index f500a0e982..c228e98ecf 100644 --- a/crates/victory-shader/src/emit/memory_tests.rs +++ b/crates/victory-shader/src/emit/memory_tests.rs @@ -5,7 +5,8 @@ //! global and a scalar load, follows a pointer it loaded with another //! scalar load, stores through a pointer it computes (64-bit multiply-add) //! and does float min/max atomics, reads through the address it takes -//! from a buffer view's descriptor (the host's view addresses), reads +//! from a buffer view's descriptor and an image descriptor's size fields +//! (the host's view addresses), reads //! pointers into memory no copy holds (zeros, marked missed) and stores and //! loads through a root UAV (title memory in such a program). @@ -104,6 +105,14 @@ fn program() -> HostShader { w.extend(global(12, 9, 1, 0, 6, 0x24)); // global_load_dword v9, v1, s[6:7] w.push(S_WAITCNT_ALL); w.extend(buffer_store_dword(9, 8, 20)); + // The image descriptor at heap index 2 loaded whole and read only for + // its size fields (dwords 1-3). + w.extend(s_load(3, 28, 4, 0x40)); // s[28:35] + w.push(S_WAITCNT_ALL); + for (k, at) in [(29, 24), (30, 28), (31, 32)] { + w.push(v_mov_b32(5, k)); + w.extend(buffer_store_dword(5, 8, at)); + } w.push(S_ENDPGM); let native = NativeProgram { stage: HwStage::Cs, @@ -241,9 +250,12 @@ fn title_memory_is_read_and_written_at_computed_addresses() { memory[0x80 / 4] = 1.0f32.to_bits(); memory[0x84 / 4] = (-1.0f32).to_bits(); let value = 0xCAFE_F00D; - // Heap index 1 (the memory's view) has the title address. - let mut view_addresses = vec![0u32; 2 * 5]; - view_addresses[2..4].copy_from_slice(&[TITLE as u32, (TITLE >> 32) as u32]); + // Heap index 1 (the memory's view) has the title address, index 2 a + // texture's size fields. + let mut view_addresses = vec![0u32; 4 * 5]; + view_addresses[4..6].copy_from_slice(&[TITLE as u32, (TITLE >> 32) as u32]); + let image = [0xC000_0000, 0x0957_C0F9, 0x9004_2FAC]; + view_addresses[9..12].copy_from_slice(&image); let mut ran = 0; for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { @@ -275,7 +287,7 @@ fn title_memory_is_read_and_written_at_computed_addresses() { (3, Root::View { srv: true, data: view_addresses.clone() }), ], views: &[ - View::RawUav(6), + View::RawUav(9), View::Memory(&memory), View::Pair, View::NullPair, @@ -288,7 +300,7 @@ fn title_memory_is_read_and_written_at_computed_addresses() { .unwrap_or_else(|e| panic!("{label}: {e}")); assert_eq!( out[0], - [0x1111_1111, 0x2222_2222, 0x2222_2222, 0, 0, 0x3333_3333], + [0x1111_1111, 0x2222_2222, 0x2222_2222, 0, 0, 0x3333_3333, image[0], image[1], image[2]], "{label}: reads" ); assert_eq!(out[1][0x40 / 4], value, "{label}: the store"); @@ -613,3 +625,130 @@ fn writes_through_views_mark_their_pages() { } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } + +/// Reads of texture views the program takes from the resource heap itself +/// mark their heap index (`emit`, "Read marks"): an `image_load` of the view +/// at heap byte offset 32 (index 1) sets exactly the bit one past +/// [`super::VIEW_READS`]. The same read through a table marks nothing (a +/// table read makes its slot on the host). +#[test] +fn heap_direct_texture_reads_mark_their_heap_index() { + let lower_with = |root: RootType, used: Vec, offset: u32| { + let mut w = vec![s_mov_b32(5, ZERO as u8)]; + w.extend(s_load(3, 12, 4, offset)); + w.push(S_WAITCNT_ALL); + w.extend((0..2).map(|v| v_mov_b32(v, ZERO))); + // image_load v[2:5], v[0:1], s[12:19] dmask:0xf dim:2D unorm + w.extend([0xF000_1F08, 0x0003_0200]); + w.push(S_WAITCNT_ALL); + w.push(S_ENDPGM); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used, + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: w.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + view_marks: true, + }) + .expect("lower") + }; + let table = lower_with( + RootType::Table, + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 4, + slot: 0, + }], + 0, + ); + assert!(!table.view_marks, "a table read marks nothing"); + let l = lower_with(RootType::ResourceHeap, Vec::new(), 32); + assert!(l.view_marks && l.heap, "a heap-direct read is marked"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: l.dxil, + user_data: l.user_data, + samplers: l.samplers, + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + memory: l.memory, + memory_writes: l.memory_writes, + view_addresses: l.view_addresses, + heap: l.heap, + heap_writes: l.heap_writes, + view_marks: l.view_marks, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let words = (super::VIEW_READS + 64) / 32; + let texel = [[0.5f32; 4]]; + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("pipeline"); + // The heap's base is 0 in the user data (`emit`, "Binding"). + let ud = vec![0u32; shader.user_data_dwords() as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + (1, Root::View { srv: true, data: vec![super::VIEW_MARK_NONE; 4] }), + (2, Root::Uav(words)), + ], + views: &[View::Texture(1, 1, &texel), View::Texture(1, 1, &texel)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: {e}")); + let bits = &out[0]; + let marked: Vec = (0..bits.len() * 32).filter(|&b| bits[b / 32] >> (b % 32) & 1 != 0).collect(); + assert_eq!(marked, [super::VIEW_READS as usize + 1], "{label}: the slot read"); + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 943638b69e..d929dd7cd2 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -81,7 +81,8 @@ //! loads and per-lane rows), so tables are never copied per draw. //! * **Rectangle lists** ([`rectangle_gs`]): a geometry shader made from a //! vertex shader's outputs completes each rectangle with its fourth -//! corner `v0 + v2 - v1`, as the console's hardware does. +//! corner opposite the right angle ([`right_angle`]), as the console's +//! hardware does. //! * **Heap indices** (added 2026-11-24) are clamped to [`HEAP_VIEWS`] − 1 //! (samplers [`HEAP_SAMPLERS`] − 1): the host's heaps have at least that //! many slots, those past its own null, so an index past the heap (data @@ -142,9 +143,14 @@ //! a copy holding each such address. //! * **View addresses** ([`HostShader::view_addresses`]): a buffer //! descriptor's dwords 0-1 read as numbers (the BVH SRV's base address) -//! come from the root SRV `t1` in [`MEMORY_SPACE`]: per resource-heap -//! index, two dwords, the buffer view's title address (high dword bits -//! 0-15; stride bits 0), zeros for no buffer view. +//! and an image descriptor's dwords 1-3 read only for sizes come from the +//! root SRV `t1` in [`MEMORY_SPACE`]: per resource-heap index, four +//! dwords, a console descriptor's first four as far as the host knows +//! them: a buffer view's title address (high dword bits 0-15; stride bits +//! 0), a texture view's width and height - 1 (dword 1 bits 30-31, dword 2 +//! bits 0-13 and 14-29), first and last level (dword 3 bits 12-15, 16-19) +//! and type (bits 28-31) with an identity swizzle; zeros for anything +//! else. //! * **Write marks** ([`HostShader::view_marks`], with //! [`Options::view_marks`]; added 2026-11-25): every store or atomic //! through an unordered buffer view from the heap (tables, the heap @@ -161,6 +167,13 @@ //! a view the bit of its first byte's page as base with that byte's //! offset in its page as phase. Writes at computed addresses mark the //! page-table bitmap instead ("Title memory"). +//! * **Read marks** (with [`Options::view_marks`]; added 2026-11-25): +//! every image instruction that reads a texture shader view the program +//! takes from the resource heap itself (not through a table, whose slots +//! the host makes for the draw) also sets bit +//! [`VIEW_READS`] + the view's heap index in the same bitmap, after the +//! written pages, where still clear: the host makes views it left null +//! until a shader reads them (textures the title placed itself). //! //! Entry points: [`translate`] (container bytes as the title passes them //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the @@ -194,7 +207,7 @@ mod flow_tests; pub mod host; mod lower; mod rect; -pub use rect::rectangle_gs; +pub use rect::{rectangle_gs, right_angle}; #[cfg(all(test, windows))] mod memory_tests; mod sampler; @@ -220,7 +233,8 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; pub use shader::{ HEAP_SAMPLERS, HEAP_VIEWS, MEMORY_SPACE, NULL_BUFFER_VIEW, ROOT_CBV_SPACE, SAMPLER_SPACE, - USER_DATA_SPACE, VIEW_MARK_NONE, VIEW_MARKS, VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, + USER_DATA_SPACE, VIEW_INTEGER, VIEW_MARK_NONE, VIEW_MARKS, VIEW_READS, VIEW_SIGNED, VIEW_STRIDE_BITS, + VIEW_STRIDES, VIEW_WRITE_BITS, VIEW_WRITES, }; /// The loop limit without an override: 2^20. @@ -310,9 +324,9 @@ pub struct HostShader { /// Whether the host binds the page bitmap `u0` in [`MEMORY_SPACE`] /// (pages written and pages missed): whenever [`HostShader::memory`]. pub memory_writes: bool, - /// Whether it reads buffer views' title addresses from their - /// descriptors: the host binds the view addresses `t1` in - /// [`MEMORY_SPACE`] (module notes, "Title memory"). + /// Whether it reads buffer views' title addresses or texture views' + /// sizes from their descriptors: the host binds the view addresses `t1` + /// in [`MEMORY_SPACE`] (module notes, "View addresses"). pub view_addresses: bool, /// Whether it takes descriptors from the resource heap at indices it /// computes (root type 5, not through a table): the host cannot tell @@ -653,6 +667,180 @@ mod tests { use super::*; use crate::native::{ComputeIo, StageIo}; + #[test] + fn indexed_move_initializes_an_input_before_its_first_use() { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Case { + Complete, + NonzeroBase, + WrongStart, + SkippedSlot, + Decrement, + Wrap, + UnknownStart, + ShortLoop, + ClobberedScc, + EarlyExit, + DivergentExit, + MaskedWrite, + SourceIsOld, + ReadBeforeWrite, + ReadOnBackedge, + } + use Case::*; + + // A two-block do-while loop writes v[M0] from v2, then exports v1. + // On the first two passes M0 selects v0 and v1 respectively. Both + // registers initially contain raw perspective-center barycentrics. + let words = |case| { + let init = match case { + WrongStart => 0xbe80_0382, // s_mov_b32 s0, 2 + Wrap => 0xbe80_03c1, // s_mov_b32 s0, -1 + UnknownStart => 0x8000_8080, // s_add_u32 s0, 0, 0 + _ => 0xbe80_0380, // s_mov_b32 s0, 0 + }; + let mut w = vec![init, 0x7e04_0281, 0xbf82_0000]; // v_mov_b32 v2, 1; s_branch header + let latch = w.len(); + if case == EarlyExit { + w.extend([0xbf06_8000, 0xbf85_0000]); // s_cmp_eq_u32 s0, 0; s_cbranch_scc1 exit + } + w.push(0xbe80_0302); // s_mov_b32 s0, s2 + let header = w.len(); + w[2] |= (header - 3) as u32; + w.push(0xbefc_0300); // s_mov_b32 m0, s0 + w.push(match case { + SkippedSlot => 0x8102_8200, // s_add_i32 s2, s0, 2 + Decrement => 0x8102_c100, // s_add_i32 s2, s0, -1 + _ => 0x8102_8100, // s_add_i32 s2, s0, 1 + }); + if case == ReadBeforeWrite { + w.push(0x7e06_0301); + } // v_mov_b32 v3, v1 + if case == MaskedWrite { + w.extend([0x7d84_0480, 0xbe84_3c6a]); // v_cmp_eq_u32 vcc, 0, v2; s_and_saveexec_b32 s4, vcc_lo + } + w.push(match case { + SourceIsOld => 0x7e00_8501, // v_movreld_b32 v0, v1 + NonzeroBase => 0x7e02_8502, // v_movreld_b32 v1, v2 + _ => 0x7e00_8502, // v_movreld_b32 v0, v2 + }); + if case == MaskedWrite { + w.push(0x887e_047e); + } // s_or_b32 exec_lo, exec_lo, s4 + if case == ReadOnBackedge { + w.push(0x7e06_0301); + } // v_mov_b32 v3, v1 + let branch = if case == DivergentExit { + w.push(0x7d84_0480); // v_cmp_eq_u32 vcc, 0, v2 + 0xbf87_0000 // s_cbranch_vccnz latch + } else { + w.push(if matches!(case, ShortLoop | NonzeroBase) { + 0xbf06_8102 + } else { + 0xbf06_8402 + }); // s_cmp_eq_u32 s2, 1/4 + if case == ClobberedScc { + w.push(0xbf06_8000); // s_cmp_eq_u32 s0, 0 exits on the first pass + } + 0xbf84_0000 // s_cbranch_scc0 latch + }; + let rel = latch as i32 - (w.len() as i32 + 1); + w.push(branch | u32::from(rel as u16)); + let exit = w.len(); + if case == EarlyExit { + w[latch + 1] |= (exit - latch - 2) as u32; + } + let output = if matches!(case, ReadBeforeWrite | ReadOnBackedge) { + 3 + } else { + 1 + }; + w.extend([0xf800_1801, output, 0xbf81_0000]); // exp mrt0.x done vm; s_endpgm + w + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let sig = super::container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &sig)]); + let c = Container::parse(&bytes).unwrap(); + for case in [ + Complete, + NonzeroBase, + WrongStart, + SkippedSlot, + Decrement, + Wrap, + UnknownStart, + ShortLoop, + ClobberedScc, + EarlyExit, + DivergentExit, + MaskedWrite, + SourceIsOld, + ReadBeforeWrite, + ReadOnBackedge, + ] { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 2, + db_shader_control: 0, + patches: vec![], + }, + code: words(case).iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let shader = emit(&c, &native, &p, &st, &io, &res); + if matches!(case, Complete | NonzeroBase) { + let shader = shader.unwrap(); + assert!( + Container::parse(&shader.dxil) + .unwrap() + .part(FourCC::DXIL) + .is_some() + ); + #[cfg(windows)] + if let Ok(mut validator) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + let mut dxil = shader.dxil; + validator.validate(&mut dxil).unwrap(); + eprintln!("synthetic {case:?} SDK valid bytes={}", dxil.len()); + } + } else { + eprintln!("synthetic {case:?} {:?}", shader.as_ref().err()); + assert!( + matches!( + shader, + Err(ShaderError::Unsupported { + what: "barycentrics read directly", + .. + }) + ), + "{case:?}" + ); + } + } + } + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose /// output signature has SV_StencilRef, and the feature bit diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 1eb5f9a1a4..7de61bf5e7 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -1,16 +1,37 @@ //! The console's rectangle lists on the host. A rectangle comes as three -//! corners, the second between the other two, and the hardware adds the -//! fourth at `v0 + v2 - v1`, for the position and every attribute. The host -//! has no such primitive; a geometry shader made for the vertex shader that -//! feeds it takes each triangle `(v0, v1, v2)` and emits it with its -//! completion `(v0, v2, v3)`, both turning the same way. Integer outputs -//! (which can only be flat) keep `v0`'s value at the fourth corner. +//! corners in any order (the blits put the right angle at `v1`, the tiled +//! lighting at `v0`), and the hardware adds the fourth opposite the right +//! angle `vc`, at `va + vb - vc`, for the position and every attribute. The +//! host has no such primitive; a geometry shader made for the vertex shader +//! that feeds it takes each triangle `(v0, v1, v2)`, finds the right angle +//! opposite its longest side, and emits the triangle with its completion +//! `(va, vb, v3)` (`va` before `vc`, `vb` after it), both turning the same +//! way. Integer outputs (which can only be flat) keep `va`'s value at the +//! fourth corner. -use super::bitcode::{Attr, Bin, Term}; +use super::bitcode::{Attr, Bin, Term, V, pred}; use super::shader::Shader; use crate::ShaderError; use crate::dxbc::{Container, FourCC}; +/// Which of a rectangle's three corners (x and y of each) holds the right +/// angle: the one opposite the longest side, else (ties, NaN) `1`. The +/// geometry shader of [`rectangle_gs`] makes the same choice on the GPU. +pub fn right_angle(xy: [[f32; 2]; 3]) -> usize { + let side = |i: usize, j: usize| { + let (dx, dy) = (xy[i][0] - xy[j][0], xy[i][1] - xy[j][1]); + dx * dx + dy * dy + }; + let (d12, d20, d01) = (side(1, 2), side(2, 0), side(0, 1)); + if d12 > d20 && d12 > d01 { + 0 + } else if d01 > d12 && d01 > d20 { + 2 + } else { + 1 + } +} + /// The geometry shader that completes the rectangles of the vertex shader /// container `vs` (its output signature is the shader's input and output). pub fn rectangle_gs(vs: &[u8]) -> Result, ShaderError> { @@ -45,25 +66,59 @@ pub fn rectangle_gs(vs: &[u8]) -> Result, ShaderError> { } corners.push(values); } - let fourth: Vec> = elements + // The right angle, as [`right_angle`] picks it from the position. + let position = elements .iter() - .enumerate() - .map(|(id, e)| { - (0..usize::from(e.cols)) - .map(|col| { - let [v0, v1, v2] = [0, 1, 2].map(|k| corners[k][id][col]); - if e.comp == 9 { - let sum = s.m.bin(b, Bin::Add, v0, v2); - s.m.bin(b, Bin::Sub, sum, v1) - } else { - v0 - } - }) - .collect() - }) - .collect(); - corners.push(fourth); - for triangle in [[0, 1, 2], [0, 2, 3]] { + .position(|e| e.kind == 3 && e.cols >= 2 && e.comp == 9) + .ok_or(ShaderError::Malformed("a rectangle list without a position"))?; + let side = |s: &mut Shader, i: usize, j: usize| { + let mut sum = None; + for (&p, &q) in corners[i][position].iter().zip(&corners[j][position]).take(2) { + let d = s.m.bin(b, Bin::Sub, p, q); + let sq = s.m.bin(b, Bin::Mul, d, d); + sum = Some(match sum { + Some(x) => s.m.bin(b, Bin::Add, x, sq), + None => sq, + }); + } + sum.expect("two columns") + }; + let (d12, d20, d01) = (side(&mut s, 1, 2), side(&mut s, 2, 0), side(&mut s, 0, 1)); + let longest = |s: &mut Shader, d: V, others: [V; 2]| { + let [x, y] = others.map(|o| s.m.cmp(b, pred::OGT, d, o)); + s.m.bin(b, Bin::And, x, y) + }; + let (at0, at2) = (longest(&mut s, d12, [d20, d01]), longest(&mut s, d01, [d12, d20])); + // `x0` if the right angle is at v0, `x2` if at v2, else `x1`. + let pick = |s: &mut Shader, [x0, x1, x2]: [V; 3]| { + let x = s.m.select(b, at2, x2, x1); + s.m.select(b, at0, x0, x) + }; + // The completing triangle (va, vb, v3), element by element. + let mut second: [Vec>; 3] = Default::default(); + for (id, e) in elements.iter().enumerate() { + let mut cols: [Vec; 3] = Default::default(); + let [c0, c1, c2] = [0, 1, 2].map(|k| &corners[k][id]); + for ((&v0, &v1), &v2) in c0.iter().zip(c1).zip(c2) { + let va = pick(&mut s, [v2, v0, v1]); + let vb = pick(&mut s, [v1, v2, v0]); + let v3 = if e.comp == 9 { + let vc = pick(&mut s, [v0, v1, v2]); + let sum = s.m.bin(b, Bin::Add, va, vb); + s.m.bin(b, Bin::Sub, sum, vc) + } else { + va + }; + for (k, v) in [va, vb, v3].into_iter().enumerate() { + cols[k].push(v); + } + } + for (k, c) in cols.into_iter().enumerate() { + second[k].push(c); + } + } + corners.extend(second); + for triangle in [[0, 1, 2], [3, 4, 5]] { for k in triangle { for (id, e) in elements.iter().enumerate() { let suffix = if e.comp == 9 { ".f32" } else { ".i32" }; @@ -85,6 +140,25 @@ pub fn rectangle_gs(vs: &[u8]) -> Result, ShaderError> { Ok(s.finish()) } +#[cfg(test)] +mod rule_tests { + use super::right_angle; + + /// The right angle is found wherever it is; triangles that are no + /// rectangle's take the corner opposite their longest side (their + /// widest angle), and ties and NaN keep the blits' corner, `v1`. + #[test] + fn right_angles_are_found_in_any_order() { + let (tl, bl, br, tr) = ([0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]); + assert_eq!(right_angle([tl, bl, br]), 1); + assert_eq!(right_angle([tl, bl, tr]), 0); + assert_eq!(right_angle([bl, tr, tl]), 2); + assert_eq!(right_angle([[0.0, 0.0], [3.0, 1.0], [1.0, 0.0]]), 2, "obtuse at v2"); + assert_eq!(right_angle([tl, tl, tl]), 1, "a point"); + assert_eq!(right_angle([tl, [f32::NAN, 0.0], br]), 1); + } +} + #[cfg(all(test, windows))] mod tests { use super::super::bitcode::{Attr, Term}; @@ -150,9 +224,12 @@ mod tests { s.finish() } - /// One rectangle (top left, bottom left, bottom right) with a - /// coordinate attribute: every pixel of the square is drawn, the - /// attribute interpolated over it, the top-right half included. + /// One rectangle with a coordinate attribute, its right angle at each of + /// the three corners in turn (the blits' top left, bottom left, bottom + /// right; the tiled lighting's top left, bottom left, top right; and + /// one with it last): every pixel of the square is drawn, the attribute + /// interpolated over it, the missing half included. Three corners on one + /// line draw nothing. #[test] fn rectangles_get_their_fourth_corner() { let (vs, ps) = (shader(false), shader(true)); @@ -164,33 +241,33 @@ mod tests { v.validate(&mut c.clone()).unwrap(); } } - #[rustfmt::skip] - let vertices = [ - -0.5, 0.5, 0.5, 1.0, -0.5, 0.5, - -0.5, -0.5, 0.5, 1.0, -0.5, -0.5, - 0.5, -0.5, 0.5, 1.0, 0.5, -0.5, - ]; + let corner = |x: f32, y: f32| [x, y, 0.5, 1.0, x, y]; + let (tl, bl, br, tr) = (corner(-0.5, 0.5), corner(-0.5, -0.5), corner(0.5, -0.5), corner(0.5, 0.5)); + let orders = [[tl, bl, br], [tl, bl, tr], [bl, tr, tl], [tl, corner(0.0, 0.0), br]]; for warp in [false, true] { let Ok(host) = Host::new(warp) else { continue }; let root = host.root_signature_for(&[]).unwrap(); let pso = host.pipeline_gs(&root, &vs, &gs, &ps).unwrap(); - let draw = Draw { - roots: Vec::new(), - textures: &[], - samplers: &[], - vertices: &vertices, - stride: 24, - size: (32, 32), - mesh_groups: 0, - }; - let texels = host.draw(&root, &pso, &draw).unwrap(); - for (i, t) in texels.iter().enumerate() { - let (x, y) = ((i % 32) as f32, (i / 32) as f32); - let (u, v) = ((x + 0.5) / 16.0 - 1.0, 1.0 - (y + 0.5) / 16.0); - let inside = u.abs() < 0.5 && v.abs() < 0.5; - let want = if inside { [u, v, 1.0, 1.0] } else { [0.0; 4] }; - let near = t.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4); - assert!(near, "warp {warp} pixel ({x}, {y}): {t:?}, want {want:?}"); + for (n, order) in orders.iter().enumerate() { + let vertices = order.concat(); + let draw = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 24, + size: (32, 32), + mesh_groups: 0, + }; + let texels = host.draw(&root, &pso, &draw).unwrap(); + for (i, t) in texels.iter().enumerate() { + let (x, y) = ((i % 32) as f32, (i / 32) as f32); + let (u, v) = ((x + 0.5) / 16.0 - 1.0, 1.0 - (y + 0.5) / 16.0); + let inside = n < 3 && u.abs() < 0.5 && v.abs() < 0.5; + let want = if inside { [u, v, 1.0, 1.0] } else { [0.0; 4] }; + let near = t.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4); + assert!(near, "warp {warp} order {n} pixel ({x}, {y}): {t:?}, want {want:?}"); + } } } } diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 1ee100d8b4..ea1cbd5107 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -14,8 +14,16 @@ pub const SAMPLER_SPACE: u32 = 0; pub const ROOT_CBV_SPACE: u32 = 1; /// The root SRV slot (`t255` in [`ROOT_CBV_SPACE`], past every title root /// parameter) of the view-stride table: dword `i` is the byte stride of -/// the buffer view at view-heap index `i`. +/// the buffer view at view-heap index `i` ([`VIEW_STRIDE_BITS`]), with +/// [`VIEW_INTEGER`] and [`VIEW_SIGNED`] for typed views of integer formats. pub const VIEW_STRIDES: u8 = 255; +/// The bits of a view-stride table dword holding the stride. +pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; +/// In a view-stride table dword: a typed buffer view of an integer format +/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits. +pub const VIEW_INTEGER: u32 = 1 << 31; +/// With [`VIEW_INTEGER`]: a signed (`SINT`) format. +pub const VIEW_SIGNED: u32 = 1 << 30; /// Where the title-memory page table is bound: `t0` (a raw root SRV) in /// this space (see `emit` "Title memory"). pub const MEMORY_SPACE: u32 = 2; @@ -40,6 +48,10 @@ pub const VIEW_MARK_NONE: u32 = u32::MAX; /// Bits in the written-pages bitmap of buffer views; marks past it go to /// the last bit. pub const VIEW_WRITE_BITS: u32 = 1 << 22; +/// The first bit of the read marks of texture views (`emit`, "Read +/// marks"), after the written pages in the same bitmap: one bit per +/// resource-heap index, [`HEAP_VIEWS`] of them. +pub const VIEW_READS: u32 = VIEW_WRITE_BITS; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { @@ -47,6 +59,8 @@ pub(crate) mod flags { pub const VIEWPORT_RT_INDEX: u64 = 1 << 9; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + /// UAVs in a vertex, geometry or mesh program. + pub const UAVS_EVERY_STAGE: u64 = 1 << 16; pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const INT64: u64 = 1 << 20; @@ -119,6 +133,11 @@ pub(crate) struct Shader { /// The heap index of each handle of an unordered buffer view (writes /// through it are marked by the index's view-mark entry). pub view_index: std::collections::HashMap, + /// The heap index of each handle of a texture shader view (its reads + /// are marked, `emit` "Read marks"), and those the instruction being + /// lowered uses. + pub texture_index: std::collections::HashMap, + pub texture_reads: Vec, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, @@ -192,6 +211,8 @@ impl Shader { view_marks: None, view_writes: None, view_index: std::collections::HashMap::new(), + texture_index: std::collections::HashMap::new(), + texture_reads: Vec::new(), flags: 0, nonuniform_handles: 0, #[cfg(test)] @@ -386,8 +407,9 @@ impl Shader { } /// The handle of the view addresses (`t1` in [`MEMORY_SPACE`], a raw - /// buffer: per resource-heap index, a buffer view's title address as a - /// buffer descriptor's dwords 0 and 1), made in the entry block. + /// buffer: per resource-heap index, a descriptor's dwords 0-3 as far as + /// the host knows them, `emit` "View addresses"), made in the entry + /// block. pub fn view_addresses_handle(&mut self) -> V { if let Some(h) = self.view_addresses { return h; @@ -557,10 +579,16 @@ impl Shader { &[index, s, n], ); let h = self.annotate(block, h, props.0, props.1); - // Unordered typed, raw and structured buffers (kinds 10-12). - if !sampler && props.0 & 0x1000 != 0 && (10..=12).contains(&(props.0 & 0xFF)) { + // Unordered typed, raw and structured buffers (kinds 10-12), and + // typed buffers read (their format kind, `Lower::view_word`). + let kind = props.0 & 0xFF; + if !sampler && (kind == 10 || props.0 & 0x1000 != 0 && (11..=12).contains(&kind)) { self.view_index.insert(h, index); } + // Texture shader views (kinds 1-9). + if !sampler && props.0 & 0x1000 == 0 && (1..=9).contains(&kind) { + self.texture_index.insert(h, index); + } h } @@ -568,6 +596,26 @@ impl Shader { pub fn finish(mut self) -> Vec { let ud_size = (self.user_data * 4).next_multiple_of(16); self.fix_user_data_size(ud_size); + // The flags of what lowering made, as the module writes it: what only + // unread values or never-taken edges used is not written. + let uses = self.m.uses(); + for (flag, used) in [ + (flags::RESOURCE_HEAP, uses.heap), + (flags::SAMPLER_HEAP, uses.sampler_heap), + (flags::WAVE_OPS, uses.wave), + (flags::INT64, uses.int64), + ] { + self.flags = if used { self.flags | flag } else { self.flags & !flag }; + } + // UAVs outside pixel and compute programs (the write and read marks + // of vertex, geometry and mesh programs), as DXC counts them: UAV + // ranges declared below, not UAVs indexed from the heap. + let compute = self.threads.is_some() && self.mesh.is_none() && self.gs.is_none(); + let declared_uavs = + !self.root_uavs.is_empty() || self.memory_dirty.is_some() || self.view_writes.is_some(); + if declared_uavs && !self.pixel && !compute { + self.flags |= flags::UAVS_EVERY_STAGE; + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { @@ -680,7 +728,7 @@ impl Shader { srvs = Some(self.m.md_node(list)); } let mut uavs = None; - if !self.root_uavs.is_empty() || self.memory_dirty.is_some() || self.view_writes.is_some() { + if declared_uavs { let ty = self .m .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); @@ -903,6 +951,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::UAVS_EVERY_STAGE != 0 { + features |= 0x4; + } if self.flags & flags::STENCIL_REF != 0 { features |= 0x200; } @@ -1014,9 +1065,10 @@ impl Shader { } } -#[cfg(test)] +#[cfg(all(test, windows))] mod tests { - use super::{HEAP_SAMPLERS, HEAP_VIEWS, Shader}; + use super::super::bitcode::Term; + use super::*; fn handle_index(limit: Option, sampler: bool, index: u32) -> u32 { let mut s = Shader::new(false); @@ -1042,4 +1094,50 @@ mod tests { } } } + + /// A program that sets a bit through the write marks' UAV, or (`heap`) + /// through a UAV indexed from the heap: a vertex (`pixel` false, no + /// thread-group size), pixel or compute program. + fn marked(pixel: bool, threads: Option<[u32; 3]>, heap: bool) -> Vec { + let mut s = Shader::new(pixel); + s.threads = threads; + let b = s.entry; + let h = if heap { + let index = s.m.i32(0); + s.heap_handle(b, index, false, false, (11 | 0x1000, 0)) + } else { + s.view_writes_handle() + }; + let (or, zero, one) = (s.m.i32(2), s.m.i32(0), s.m.i32(1)); + let iu = s.m.undef(s.t.i32); + let i32t = s.t.i32; + s.op(b, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &[h, or, zero, iu, iu, one]); + s.m.terminate(b, Term::Ret); + s.finish() + } + + /// A vertex program writing a declared UAV declares UAVs at every stage + /// (the validator refuses it otherwise: "Flags must match usage", the + /// 5,046 programs of the title's list); pixel and compute programs need + /// not, nor a vertex program whose UAVs all come from the heap (the + /// validator counts declared ranges only: 26 mesh and vertex programs). + #[test] + fn uavs_outside_pixel_and_compute_programs_are_declared() { + let mut validator = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) + .ok(); + for (name, pixel, threads, heap) in [ + ("vertex", false, None, false), + ("pixel", true, None, false), + ("compute", false, Some([1, 1, 1]), false), + ("vertex, heap", false, None, true), + ] { + let mut dxil = marked(pixel, threads, heap); + if let Some(v) = validator.as_mut() { + v.validate(&mut dxil) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + } } diff --git a/crates/victory-shader/src/emit/stride_tests.rs b/crates/victory-shader/src/emit/stride_tests.rs index fc160f5f98..20615b2e50 100644 --- a/crates/victory-shader/src/emit/stride_tests.rs +++ b/crates/victory-shader/src/emit/stride_tests.rs @@ -7,8 +7,13 @@ use windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC; +use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R16G16B16A16_UINT, +}; + use super::host::{Dispatch, Host, Root, Stride, View}; -use super::{HostShader, StaticSampler, VIEW_STRIDES, lower, validator}; +use super::{HostShader, StaticSampler, VIEW_INTEGER, VIEW_STRIDES, lower, validator}; use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; @@ -573,4 +578,169 @@ fn a_sampler_chosen_by_a_uniform_branch_samples_as_chosen() { ran += 1; } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); -} \ No newline at end of file +} +/// User data: s0 a table with a typed buffer UAV, s1 a table with a raw +/// buffer of 2 dwords a lane, s2 a table with a raw UAV. Each lane stores +/// its 4 halves to element `lane` of the typed view (`_d16`), loads them +/// back the same way and stores what it read to dwords `2 lane, 2 lane + 1` +/// of the raw UAV. +const D16_ROUND_TRIP_WAVE32: &[u32] = &[ + 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], 0x0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0303, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[6:7], 0x0 + 0xBE94_0302, // s_mov_b32 s20, s2 + 0xBE95_0380, // s_mov_b32 s21, 0 + 0xF408_040A, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[20:21], 0x0 + 0x3406_0083, // v_lshlrev_b32 v3, 3, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE034_1000, + 0x8003_0103, // buffer_load_dwordx2 v[1:2], v3, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE21C_2000, + 0x8002_0100, // buffer_store_format_d16_xyzw v[1:2], v0, s[8:11], 0 idxen + 0xE20C_2000, + 0x8002_0400, // buffer_load_format_d16_xyzw v[4:5], v0, s[8:11], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE074_1000, + 0x8004_0403, // buffer_store_dwordx2 v[4:5], v3, s[16:19], 0 offen + 0xBF81_0000, // s_endpgm +]; + +/// User data: s0 a table with a typed buffer SRV, s1 a table with a raw UAV. +/// Each lane loads element `lane` (`_d16_x`) and stores the dword it got to +/// dword `lane` of the raw UAV. +const D16_X_LOAD_WAVE32: &[u32] = &[ + 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], 0x0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0403, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[6:7], 0x0 + 0x3406_0082, // v_lshlrev_b32 v3, 2, v0 + 0x7E08_0280, // v_mov_b32 v4, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE200_2000, + 0x8002_0400, // buffer_load_format_d16_x v4, v0, s[8:11], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000, + 0x8004_0403, // buffer_store_dword v4, v3, s[16:19], 0 offen + 0xBF81_0000, // s_endpgm +]; + +/// Runs `shader` (user data: tables at heap indices 0, 1, 2 in order) on +/// hardware and WARP with `views` and the view-stride table `strides`; +/// each adapter's UAV contents. +fn run_tables(shader: &HostShader, views: &[View], strides: Vec) -> Vec<(&'static str, Vec>)> { + assert_eq!(shader.root_srvs, [VIEW_STRIDES]); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut out = Vec::new(); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + // Table k is the view at heap index k (32 bytes a view). + ud[u.index as usize] = 32 * u32::from(u.slot); + } + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud)), (1, Root::View { srv: true, data: strides.clone() })], + views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words)); + } + assert!(!out.is_empty(), "neither hardware nor WARP SM 6.6 device available"); + out +} + +/// 16-bit typed stores and loads (`_d16`) through views of integer formats +/// pass the bits (the console's buffer format decides the conversion; d16 +/// only packs 16-bit results), and through float views convert as halves: +/// Grand Theft Auto VI's face network keeps its halves in UINT views. +#[test] +fn d16_typed_buffer_accesses_pass_bits_through_integer_views() { + let shader = build( + D16_ROUND_TRIP_WAVE32, + vec![ + param(RootType::Table, 0), + param(RootType::Table, 1), + param(RootType::Table, 2), + ], + vec![ + entry(ResourceType::Uav, 4, 0), + entry(ResourceType::Srv, 4, 1), + entry(ResourceType::Uav, 4, 2), + ], + 32, + ); + // Lane l: negative zero and small, signalling NaN, denormal and + // all-ones patterns as bits; normal halves for the float view. + let bits: Vec = (0..32u32) + .flat_map(|l| [(0x8000 | l) | (0x7C01 + l) << 16, (1 + l) | (0xFFFF - l) << 16]) + .collect(); + let halves: Vec = (0..32u32) + .flat_map(|l| [(0x3C00 + l) | (0xC000 + 3 * l) << 16, (0x1400 + l) | (0x5BFF - l) << 16]) + .collect(); + let cases: [(DXGI_FORMAT, u32, &[u32]); 2] = [ + (DXGI_FORMAT_R16G16B16A16_UINT, 8 | VIEW_INTEGER, &bits), + (DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &halves), + ]; + for (format, stride, data) in cases { + let views = [ + View::TypedUav(format, 32, 8), + View::Buffer { data, stride: Stride::Raw }, + View::RawUav(64), + ]; + for (label, words) in run_tables(&shader, &views, vec![stride, 4, 4]) { + assert_eq!(words[0], data, "{label} {format:?}: the typed view's bytes"); + assert_eq!(words[1], data, "{label} {format:?}: what the loads read"); + } + } +} + +/// A one-channel `_d16_x` load from a typed SRV: an integer view's 16 bits +/// as they are, a float view's half as it is. +#[test] +fn d16_x_loads_read_r16_uint_and_r16_float_views() { + let shader = build( + D16_X_LOAD_WAVE32, + vec![param(RootType::Table, 0), param(RootType::Table, 1)], + vec![entry(ResourceType::Srv, 4, 0), entry(ResourceType::Uav, 4, 1)], + 32, + ); + let pack = |h: &dyn Fn(u32) -> u32| -> Vec { (0..16u32).map(|k| h(2 * k) | h(2 * k + 1) << 16).collect() }; + let uint = |l: u32| 0xF000 | l; + let half = |l: u32| 0x3C00 + 5 * l; + let cases: [(DXGI_FORMAT, u32, Vec, Vec); 2] = [ + (DXGI_FORMAT_R16_UINT, 2 | VIEW_INTEGER, pack(&uint), (0..32).map(uint).collect()), + (DXGI_FORMAT_R16_FLOAT, 2, pack(&half), (0..32).map(half).collect()), + ]; + for (format, stride, data, want) in cases { + let views = [View::Buffer { data: &data, stride: Stride::Format(format, 2) }, View::RawUav(32)]; + for (label, words) in run_tables(&shader, &views, vec![stride, 4]) { + assert_eq!(words[0], want, "{label} {format:?}"); + } + } +} diff --git a/crates/victory-shader/src/emit/synthetic_tests.rs b/crates/victory-shader/src/emit/synthetic_tests.rs index 249e734e7e..487ee4f7e0 100644 --- a/crates/victory-shader/src/emit/synthetic_tests.rs +++ b/crates/victory-shader/src/emit/synthetic_tests.rs @@ -369,6 +369,264 @@ fn permutes_read_the_lane_named_and_zero_from_lanes_left_out() { } } +/// A lane mask joined with data at a uniform loop's header, as the title's +/// wave-uniform BVH walks push lane masks to memory and pop them +/// (`shadowmask:CS_TraceShadowRays_Checkerboard`): the register holds the +/// mask on entry and a number from the back edge, read both as a number and +/// as a mask. +#[test] +fn a_mask_joined_with_data_at_a_uniform_loop_is_its_number() { + // s6 = lanes below 24, shifted right by 4 and passed through a VGPR in + // each of two iterations; v4 takes each lane's bit of it on every pass. + let shader = build(&[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x8706_7E6A, // s_and_b32 s6, vcc_lo, exec_lo + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xD501_0004, + 0x0019_0280, // header: v_cndmask_b32 v4, 0, 1, s6 + 0x9006_8406, // s_lshr_b32 s6, s6, 4 + 0x7E0A_0206, // v_mov_b32 v5, s6 + 0x7E0C_0505, // v_readfirstlane_b32 s6, v5 + 0x8007_8107, // s_add_u32 s7, s7, 1 + 0xBF0A_8207, // s_cmp_lt_u32 s7, 2 + 0xBF85_FFF8, // s_cbranch_scc1 header + 0x7E06_0206, // v_mov_b32 v3, s6 + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + 0xE070_1080, + 0x800A_0410, // buffer_store_dword v4, v16, s[40:43], 0 offen offset:128 + 0xBF81_0000, // s_endpgm + ]) + .expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(64), + ]; + let mut want = vec![0x00FF_FFFF >> 8; 32]; + want.extend((0..32).map(|lane| u32::from(lane < 20))); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + assert!(warp, "{label}: no pipeline for a wave of 32"); + eprintln!("{label}: no pipeline for a wave of 32; skipped"); + continue; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{label}"); + } +} + +/// A lane mask a compare makes inside a region the other lanes skip, joined +/// with data in the same register on the skip edge (a reused register): the +/// skipping lanes read 0, their bit of the compare, as on the console. A +/// mask holding lanes outside its edge (the saved EXEC) stays refused. +#[test] +fn a_compare_mask_joined_with_data_on_the_skip_edge_is_0_there() { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBE86_0385, // s_mov_b32 s6, 5 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE88_3C6A, // s_and_saveexec_b32 s8, vcc_lo + 0xBF88_0002, // s_cbranch_execz +2 + 0xD4C4_0006, + 0x0002_0088, // v_cmp_gt_u32 s6, 8, v0 + 0xBEFE_0308, // s_mov_b32 exec_lo, s8 + 0xD501_0003, + 0x0019_0280, // v_cndmask_b32 v3, 0, 1, s6 + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + let shader = build(&words).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(32), + ]; + let want: Vec = (0..32).map(|lane| u32::from(lane < 8)).collect(); + { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + assert!(warp, "{label}: no pipeline for a wave of 32"); + eprintln!("{label}: no pipeline for a wave of 32; skipped"); + continue; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{label}"); + } + } + // The saved EXEC instead (every lane): the skipping lanes' bit would be + // 1 on the console. + words[10..12].copy_from_slice(&[0xBE86_0308, 0xBF80_0000]); // s_mov_b32 s6, s8; s_nop 0 + let Err(crate::ShaderError::Unsupported { what, .. }) = build(&words) else { + panic!("a mask holding lanes off its edge joined with data translated"); + }; + assert!(what.contains("lane-mask join"), "{what}"); +} + +/// A register array (v3-v14) indexed through M0 in waterfall loops, as +/// `tiled_lighting:CS_PrescalarizeLightLoop` builds its per-tile light +/// masks: each lane's index (clamped to 0-11 by `v_med3_u32`) becomes M0 in +/// the loop pass that handles the lanes holding it; a `v_movrels` reads the +/// lane's array element, a `v_movreld` writes it back with the lane's bit +/// added. Twice, so the second pass reads what the first wrote. +#[test] +fn relative_moves_in_waterfall_loops_reach_each_lane_s_element() { + let mut w = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + ]; + w.extend((3..15u32).map(|k| 0x7E00_0280 | k << 17)); // v_mov_b32 vk, 0 + w.extend([ + 0x2C38_0081, // v_lshrrev_b32 v28, 1, v0 + 0xD559_001C, + 0x022D_011C, // v_med3_u32 v28, v28, 0, 11 + 0x7E3A_0281, // v_mov_b32 v29, 1 + 0x343A_3B00, // v_lshlrev_b32 v29, v0, v29 + ]); + let pass = [ + 0xBEA4_037E, // s_mov_b32 s36, exec_lo + 0x7E4C_051C, // read: v_readfirstlane_b32 s38, v28 + 0xD4C2_0006, + 0x0002_3826, // v_cmp_eq_u32 s6, s38, v28 + 0xBE86_3C06, // s_and_saveexec_b32 s6, s6 + 0xBEFC_0326, // s_mov_b32 m0, s38 + 0x7E3E_8703, // v_movrels_b32 v31, v3 + 0x897E_067E, // s_xor_b32 exec_lo, exec_lo, s6 + 0xBF89_FFF8, // s_cbranch_execnz read + 0xBEFE_0324, // s_mov_b32 exec_lo, s36 + 0x383A_3B1F, // v_or_b32 v29, v31, v29 + 0x7E4C_051C, // write: v_readfirstlane_b32 s38, v28 + 0xD4C2_0006, + 0x0002_3826, // v_cmp_eq_u32 s6, s38, v28 + 0xBE86_3C06, // s_and_saveexec_b32 s6, s6 + 0xBEFC_0326, // s_mov_b32 m0, s38 + 0x7E06_851D, // v_movreld_b32 v3, v29 + 0x897E_067E, // s_xor_b32 exec_lo, exec_lo, s6 + 0xBF89_FFF8, // s_cbranch_execnz write + 0xBEFE_0324, // s_mov_b32 exec_lo, s36 + ]; + w.extend(pass); + w.extend([0x7E3A_02FF, 0x8000_0000]); // v_mov_b32 v29, 0x80000000 + w.extend(pass); + for k in 3..15u32 { + // buffer_store_dword vk, v16, s[40:43], 0 offen offset:128 * (k - 3) + w.extend([0xE070_1000 | (128 * (k - 3)), 0x800A_0010 | k << 8]); + } + w.push(0xBF81_0000); // s_endpgm + let shader = build(&w).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(12 * 32), + ]; + let want: Vec = (0..12u32) + .flat_map(|k| (0..32u32).map(move |lane| if (lane >> 1).min(11) == k { 1 << lane | 0x8000_0000 } else { 0 })) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + assert!(warp, "{label}: no pipeline for a wave of 32"); + eprintln!("{label}: no pipeline for a wave of 32; skipped"); + continue; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{label}"); + } +} + #[test] fn ordered_pixel_sections_use_rasterizer_ordered_views() { // A pixel program's ordered section (POPS) as the title's compiler diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index c52ce4f5a9..aed3633dea 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -378,6 +378,66 @@ fn normalized_buffer_formats_load_their_ends_exactly() { } } +/// Codes of the normalized formats sampled below: every 8-bit code; for +/// 16 bits a stride, the RX 6700 XT's division misses (257, 261, ...) and +/// the ends. +fn normalized_codes(bits: u32) -> Vec { + if bits <= 10 { + return (0..1 << bits).collect(); + } + let edges = [1, 2, 3, 255, 256, 257, 261, 265, 269, 511, 512, 1000, 0x7FFF, 0x8000, 0x8001, 0xFFFE]; + (0..=0xFFFF).step_by(257).chain(edges).collect() +} + +/// Every normalized code loads as the float nearest its exact quotient, +/// as the console's buffer unit converts it, not as the host divides (the +/// RX 6700 XT gave 125 of the 8-bit codes one ulp high and 16-bit codes +/// such as 257 one ulp low): unsigned and signed, 8, 10 (the x channel of +/// 2_10_10_10) and 16 bits, the signed formats' two lowest codes -1.0. +#[test] +fn normalized_buffer_formats_load_correctly_rounded_quotients() { + let x = 0; + // (format, bits, signed): 8_UNORM, 16_UNORM, 8_SNORM, 16_SNORM, + // 2_10_10_10_UNORM and _SNORM. + for (format, bits, signed) in [(1u8, 8u32, false), (7, 16, false), (2, 8, true), (8, 16, true), (50, 10, false), (51, 10, true)] { + let shader = tbuffer_load_of_v1(x, format); + let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect(); + run_cases(&shader, &cases, |backend, _, [a, ..], got| { + let want = if signed { + let top = (1i32 << (bits - 1)) - 1; + let s = ((a << (32 - bits)) as i32) >> (32 - bits); + (s.max(-top) as f32 / top as f32).to_bits() + } else { + (a as f32 / ((1u32 << bits) - 1) as f32).to_bits() + }; + let sign = if signed { "signed" } else { "unsigned" }; + assert_eq!(got, want, "{backend}: {bits}-bit {sign} normalized {a:#x} loads as {got:#010x}, want {want:#010x}"); + }); + } +} + +/// A title truncates `x * (2^n - 1)` back to the code it stored (the +/// material index a mesh program reads from a vertex colour's alpha, as +/// `v_mul_legacy_f32` by 255.0 then `v_cvt_u32_f32`): every code comes back +/// as itself, on hardware and WARP, which a quotient one ulp low breaks. +#[test] +fn normalized_codes_truncate_back_to_themselves() { + let x = 0; + for (format, bits) in [(1u8, 8u32), (7, 16)] { + let scale = (((1u32 << bits) - 1) as f32).to_bits(); + let mut body = buffer_store_dword(1, 8, 0).to_vec(); + body.extend(mtbuf(x, 0, 8, format)); + // v_mul_legacy_f32 v0, literal, v0; v_cvt_u32_f32 v0, v0. + body.extend([0x07 << 25 | 0xFF, scale]); + body.push(vop1(0x07, 0, vgpr(0))); + let shader = build_valu_cs(&body); + let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect(); + run_cases(&shader, &cases, |backend, _, [a, ..], got| { + assert_eq!(got, a, "{backend}: {bits}-bit code {a} comes back as {got}"); + }); + } +} + #[test] fn packed_add_selects_halves_of_inline_constants() { // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index f3804e8e28..7e9c30a730 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -950,6 +950,25 @@ impl<'a> Tracer<'a> { || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) )) + || self.joined_on_taken_edges(hi) == Some(want) + } + + /// What phi `t` holds in every lane that reads it: the one value its + /// args bring along the edges some lane takes (a register set inside a + /// region that only a skip no lane takes bypasses, as + /// `indirect_light_probes:CS_Alpha_Schedule`'s table address). + fn joined_on_taken_edges(&self, t: Term) -> Option { + let Term::Value(v) = t else { return None }; + let (b, i) = self.phis[v.0 as usize]?; + let block = &self.p.blocks[b]; + let mut taken = block.phis[i] + .args + .iter() + .zip(&block.preds) + .filter(|&(_, &q)| self.edge_taken(q, b)) + .map(|(&a, _)| self.origin(a)); + let first = taken.next()?; + taken.all(|x| x == first).then_some(first) } /// `hi` adds something (with carry) to `high`: `s_addc_u32` or @@ -1161,22 +1180,53 @@ impl<'a> Tracer<'a> { } joins.push(block); let phis = &self.p.blocks[block].phis; - let args = (0..self.p.blocks[block].preds.len()) - .map(|j| { - let edge: Vec = words - .iter() - .map(|w| match phi_of(w) { - Some((_, i)) => self.origin(phis[i].args[j]), - None => *w, - }) - .collect(); - self.classify(&edge, joins, known) - }) - .collect::>(); + let preds = &self.p.blocks[block].preds; + // An edge no lane takes (a skip only helper lanes would take, say) + // brings nothing a lane reads: it takes a taken edge's source, and + // lowering joins no value there (`never_taken`). + let taken: Vec = preds.iter().map(|&q| self.edge_taken(q, block)).collect(); + let edge = |j: usize, joins: &mut Vec, known: &mut Known| { + let edge: Vec = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect(); + self.classify(&edge, joins, known) + }; + let args = match taken.iter().position(|&t| t) { + Some(first) if taken.contains(&false) => edge(first, joins, known).and_then(|live| { + (0..preds.len()) + .map(|j| if taken[j] { edge(j, joins, known) } else { Ok(live.clone()) }) + .collect::>() + }), + _ => (0..preds.len()).map(|j| edge(j, joins, known)).collect::>(), + }; joins.pop(); Ok(Some(Source::Phi { block, args: args? })) } + /// Whether some lane goes from block `q` to `b` (true without the + /// lanes' paths): `Lower::never_taken`'s test. + fn edge_taken(&self, q: usize, b: usize) -> bool { + let Some(lanes) = self.lanes else { + return true; + }; + let mut edge = vec![(lanes.reach[q], true)]; + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + edge.push((when, taken == b)); + } + // The very test lowering makes, so both drop the same edges. + lanes.bools.meet(&edge) + } + /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced /// per outcome (other words are the same for both). fn select(